pax_global_header00006660000000000000000000000064132343602220014507gustar00rootroot0000000000000052 comment=88a69fda0f2187ad8714cedffd7a8872dceaa4c2 composer-1.6.3/000077500000000000000000000000001323436022200133455ustar00rootroot00000000000000composer-1.6.3/.gitattributes000066400000000000000000000012501323436022200162360ustar00rootroot00000000000000# Auto-detect text files, ensure they use LF. * text=auto eol=lf # These files are always considered text and should use LF. # See core.whitespace @ http://git-scm.com/docs/git-config for whitespace flags. *.php text eol=lf whitespace=blank-at-eol,blank-at-eof,space-before-tab,tab-in-indent,tabwidth=4 diff=php *.json text eol=lf whitespace=blank-at-eol,blank-at-eof,space-before-tab,tab-in-indent,tabwidth=4 *.test text eol=lf whitespace=blank-at-eol,blank-at-eof,space-before-tab,tab-in-indent,tabwidth=4 *.yml text eol=lf whitespace=blank-at-eol,blank-at-eof,space-before-tab,tab-in-indent,tabwidth=2 # Exclude non-essential files from dist /tests export-ignore composer-1.6.3/.github/000077500000000000000000000000001323436022200147055ustar00rootroot00000000000000composer-1.6.3/.github/CONTRIBUTING.md000066400000000000000000000043431323436022200171420ustar00rootroot00000000000000Contributing to Composer ======================== Please note that this project is released with a [Contributor Code of Conduct](http://contributor-covenant.org/version/1/4/). By participating in this project you agree to abide by its terms. Reporting Issues ---------------- When reporting issues, please try to be as descriptive as possible, and include as much relevant information as you can. A step by step guide on how to reproduce the issue will greatly increase the chances of your issue being resolved in a timely manner. For example, if you are experiencing a problem while running one of the commands, please provide full output of said command in very very verbose mode (`-vvv`, e.g. `composer install -vvv`). If your issue involves installing, updating or resolving dependencies, the chance of us being able to reproduce your issue will be much higher if you share your `composer.json` with us. Security Reports ---------------- Please send any sensitive issue to [security@packagist.org](mailto:security@packagist.org). Thanks! Installation from Source ------------------------ Prior to contributing to Composer, you must be able to run the test suite. To achieve this, you need to acquire the Composer source code: 1. Run `git clone https://github.com/composer/composer.git` 2. Download the [`composer.phar`](https://getcomposer.org/composer.phar) executable 3. Run Composer to get the dependencies: `cd composer && php ../composer.phar install` You can run the test suite by executing `vendor/bin/phpunit` when inside the composer directory, and run Composer by executing the `bin/composer`. To test your modified Composer code against another project, run `php /path/to/composer/bin/composer` inside that project's directory. Contributing policy ------------------- Fork the project, create a feature branch, and send us a pull request. To ensure a consistent code base, you should make sure the code follows the [PSR-2 Coding Standards](http://www.php-fig.org/psr/psr-2/). You can also run [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) with the configuration file that can be found in the project root directory. If you would like to help, take a look at the [list of open issues](https://github.com/composer/composer/issues). composer-1.6.3/.github/ISSUE_TEMPLATE.md000066400000000000000000000003671323436022200174200ustar00rootroot00000000000000My `composer.json`: ```json ...replace me... ``` Output of `composer diagnose`: ``` ...replace me... ``` When I run this command: ``` ...replace me... ``` I get the following output: ``` ...replace me... ``` And I expected this to happen: composer-1.6.3/.gitignore000066400000000000000000000001671323436022200153410ustar00rootroot00000000000000/.settings /.project /.buildpath /composer.phar /vendor /nbproject phpunit.xml .vagrant Vagrantfile .idea .php_cs.cachecomposer-1.6.3/.php_cs000066400000000000000000000036261323436022200146310ustar00rootroot00000000000000 Jordi Boggiano For the full copyright and license information, please view the LICENSE file that was distributed with this source code. EOF; $finder = PhpCsFixer\Finder::create() ->files() ->in(__DIR__.'/src') ->in(__DIR__.'/tests') ->name('*.php') ->notPath('Fixtures') ; return PhpCsFixer\Config::create() ->setUsingCache(true) //->setUsingLinter(false) ->setRiskyAllowed(true) ->setRules(array( '@PSR2' => true, 'binary_operator_spaces' => true, 'blank_line_before_return' => true, 'cast_spaces' => true, 'header_comment' => array('header' => $header), 'include' => true, 'array_syntax' => array('syntax' => 'long'), 'method_separation' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_consecutive_blank_lines' => true, 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_unused_imports' => true, 'no_useless_else' => true, 'no_whitespace_in_blank_line' => true, 'object_operator_without_whitespace' => true, 'phpdoc_align' => true, 'phpdoc_indent' => true, 'phpdoc_no_access' => true, 'phpdoc_no_package' => true, 'phpdoc_order' => true, 'phpdoc_scalar' => true, 'phpdoc_trim' => true, 'phpdoc_types' => true, 'psr0' => true, 'single_blank_line_before_namespace' => true, 'short_scalar_cast' => true, 'standardize_not_equals' => true, 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline_array' => true, )) ->setFinder($finder) ; composer-1.6.3/.travis.yml000066400000000000000000000033001323436022200154520ustar00rootroot00000000000000language: php sudo: false dist: trusty git: depth: 5 cache: directories: - $HOME/.composer/cache addons: apt: packages: - parallel php: - 5.4 - 5.5 - 5.6 - 7.0 - 7.1 - 7.2 - nightly matrix: include: - dist: precise php: 5.3 fast_finish: true allow_failures: - php: nightly before_install: # determine INI file - if [[ $TRAVIS_PHP_VERSION = hhvm* ]]; then export INI=/etc/hhvm/php.ini; else export INI=~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini; fi # disable xdebug if available - phpenv config-rm xdebug.ini || echo "xdebug not available" # disable default memory limit - echo memory_limit = -1 >> $INI install: # flags to pass to install - flags="--ansi --prefer-dist --no-interaction --optimize-autoloader --no-suggest --no-progress" # install dependencies using system provided composer binary - composer install $flags # install dependencies using composer from source - bin/composer install $flags before_script: # make sure git tests do not complain about user/email not being set - git config --global user.name travis-ci - git config --global user.email travis@example.com script: # run test suite directories in parallel using GNU parallel - ls -d tests/Composer/Test/* | parallel --gnu --keep-order 'echo "Running {} tests"; ./vendor/bin/phpunit -c tests/complete.phpunit.xml --colors=always {} || (echo -e "\e[41mFAILED\e[0m {}" && exit 1);' before_deploy: - php -d phar.readonly=0 bin/compile deploy: provider: releases api_key: $GITHUB_TOKEN file: composer.phar skip_cleanup: true on: tags: true repo: composer/composer php: '7.1' composer-1.6.3/CHANGELOG.md000066400000000000000000001314141323436022200151620ustar00rootroot00000000000000### [1.6.3] 2018-01-31 * Fixed GitLab downloads failing in some edge cases * Fixed ctrl-C handling during create-project * Fixed GitHub VCS repositories not prompting for a token in some conditions * Fixed SPDX license identifiers being case sensitive * Fixed and clarified a few dependency resolution error reporting strings * Fixed SVN commit log fetching in verbose mode when using private repositories ### [1.6.2] 2018-01-05 * Fixed more autoloader regressions * Fixed support for updating dist refs in gitlab URLs ### [1.6.1] 2018-01-04 * Fixed upgrade regression due to some autoloader cleanups * Fixed some overly loose version constraints ### [1.6.0] 2018-01-04 * Added support for SPDX license identifiers v3.0, deprecates GPL/LGPL/AGPL identifiers, which should now have a `-only` or `-or-later` suffix added. * Added support for COMPOSER_MEMORY_LIMIT env var to make Composer set the PHP memory limit explicitly * Added support for simple strings for the `bin` * Fixed `check-platform-reqs` bug in version checking ### [1.6.0-RC] 2017-12-19 * Improved performance of installs and updates from git clones when checking out known commits * Added `check-platform-reqs` command that checks that your PHP and extensions versions match the platform requirements of the installed packages * Added `--with-all-dependencies` to the `update` and `require` commands which updates all dependencies of the listed packages, including those that are direct root requirements * Added `scripts-descriptions` key to composer.json to customize the description and document your custom commands * Added support for the uppercase NO_PROXY env var * Added support for COMPOSER_DEFAULT_{AUTHOR,LICENSE,EMAIL,VENDOR} env vars to pre-populate init command values * Added support for local fossil repositories * Added suggestions for alternative spellings when entering packages in `init` and `require` commands and nothing can be found * Fixed installed.json data to be sorted alphabetically by package name * Fixed compatibility with Symfony 4.x components that Composer uses ### [1.5.6] - 2017-12-18 * Fixed root package version guessed when a tag is checked out * Fixed support for GitLab repos hosted on non-standard ports * Fixed regression in require command when requiring unstable packages, part 3 ### [1.5.5] - 2017-12-01 * Fixed regression in require command when requiring unstable packages, part 2 ### [1.5.4] - 2017-12-01 * Fixed regression in require command when requiring unstable packages ### [1.5.3] - 2017-11-30 * Fixed require/remove commands reverting the composer.json change when a non-solver-related error occurs * Fixed GitLabDriver to support installations of GitLab not at the root of the domain * Fixed create-project not following the optimize-autoloader flag of the root package * Fixed Authorization header being forwarded across domains after a redirect * Improved some error messages for clarity ### [1.5.2] - 2017-09-11 * Fixed GitLabDriver looping endlessly in some conditions * Fixed GitLabDriver support for unauthenticated requests * Fixed GitLab zip downloads not triggering credentials prompt if unauthenticated * Fixed path repository support of COMPOSER_ROOT_VERSION, it now applies to all path repos within the same git repository * Fixed path repository handling of copies to avoid copying VCS files and others * Fixed sub-directory call to ignore list and create-project commands as well as calls to Composer using --working-dir * Fixed invalid warning appearing when calling `remove` on an non-stable package ### [1.5.1] - 2017-08-09 * Fixed regression in GitLabDriver with repos containing >100 branches or tags * Fixed sub-directory call support to respect the COMPOSER env var ### [1.5.0] - 2017-08-08 * Changed the package install order to ensure that plugins are always installed as soon as possible * Added ability to call composer from within sub-directories of a project * Added support for GitLab API v4 * Added support for GitLab sub-groups * Added some more rules to composer validate * Added support for reading the `USER` env when guessing the username in `composer init` * Added warning when uncompressing files with the same name but difference cases on case insensitive filesystems * Added `htaccess-protect` option / `COMPOSER_HTACCESS_PROTECT` env var to disable the .htaccess creation in home dir (defaults to true) * Improved `clear-cache` command * Minor improvements/fixes and many documentation updates ### [1.4.3] - 2017-08-06 * Fixed GitLab URLs * Fixed root package version detection using latest git versions * Fixed inconsistencies in date format in composer.lock when installing from source * Fixed Mercurial support regression * Fixed exclude-from-classmap not being applied when autoloading files for Composer plugins * Fixed exclude-from-classmap being ignored when cwd has the wrong case on case insensitive filesystems * Fixed several other minor issues ### [1.4.2] - 2017-05-17 * Fixed Bitbucket API handler parsing old deleted branches in hg repos * Fixed regression in gitlab downloads * Fixed output inconsistencies * Fixed unicode handling in `init` command for author names * Fixed useless warning when doing partial updates/removes on packages that are not currently installed * Fixed xdebug disabling issue when combined with disable_functions and allow_url_fopen CLI overrides ### [1.4.1] - 2017-03-10 * Fixed `apcu-autoloader` config option being ignored in `dump-autoload` command * Fixed json validation not allowing boolean for trunk-path, branches-path and tags-path in svn repos * Fixed json validation not allowing repository URLs without scheme ### [1.4.0] - 2017-03-08 * Improved memory usage of dependency solver * Added `--format json` option to the `outdated` and `show` command to get machine readable package listings * Added `--ignore-filters` flag to `archive` command to bypass the .gitignore and co * Added support for `outdated` output without ansi colors * Added support for Bitbucket API v2 * Changed the require command to follow minimum-stability / prefer-stable values when picking a version * Fixed regression when using composer in a Mercurial repository ### [1.3.3] - 2017-03-08 * **Capifony users beware**: This release has output format tweaks that mess up capifony interactive mode, see #6233 * Improved baseline psr-4 autoloader performance for projects with many nested namespaces configured * Fixed issues with gitlab API access when the token had insufficient permissions * Fixed some HHVM strict type issues * Fixed version guessing of headless git checkouts in some conditions * Fixed compatibility with subversion 1.8 * Fixed version guessing not working with svn/hg * Fixed script/exec errors not being output correctly * Fixed PEAR repository bug with pear.php.net ### [1.3.2] - 2017-01-27 * Added `COMPOSER_BINARY` env var that is defined within the scope of a Composer run automatically with the path to the phar file * Fixed create-project ending in a detached HEAD when installing aliased packages * Fixed composer show not returning non-zero exit code when the package does not exist * Fixed `@composer` handling in scripts when --working-dir is used together with it * Fixed private-GitLab handling of repos with dashes in them ### [1.3.1] - 2017-01-07 * Fixed dist downloads from Bitbucket * Fixed some regressions related to xdebug disabling * Fixed `--minor-only` flag in `outdated` command * Fixed handling of config.platform.php which did not replace other php-* package's versions ### [1.3.0] - 2016-12-24 * Fixed handling of annotated git tags vs lightweight tags leading to useless updates sometimes * Fixed ext-xdebug not being require-able anymore due to automatic xdebug disabling * Fixed case insensitivity of remove command ### [1.3.0-RC] - 2016-12-11 * Added workaround for xdebug performance impact by restarting PHP without xdebug automatically in case it is enabled * Added `--minor-only` to the `outdated` command to only show updates to minor versions and ignore new major versions * Added `--apcu-autoloader` to the `update`/`install` commands and `--apcu` to `dump-autoload` to enable an APCu-caching autoloader, which can be more efficient than --classmap-authoritative if you attempt to autoload many classes that do not exist, or if you can not use authoritative classmaps for some reason * Added summary of operations to be executed before they run, and made execution output more compact * Added `php-debug` and `php-zts` virtual platform packages * Added `gitlab-token` auth config for GitLab private tokens * Added `--strict` to the `outdated` command to return a non-zero exit code when there are outdated packages * Added ability to call php scripts using the current php interpreter (instead of finding php in PATH by default) in script handlers via `@php ...` * Added `COMPOSER_ALLOW_XDEBUG` env var to circumvent the xdebug-disabling behavior * Added `COMPOSER_MIRROR_PATH_REPOS` env var to force mirroring of path repositories vs symlinking * Added `COMPOSER_DEV_MODE` env var that is set by Composer to forward the dev mode to script handlers * Fixed support for git 2.11 * Fixed output from zip and rar leaking out when an error occured * Removed `hash` from composer.lock, only `content-hash` is now used which should reduce conflicts * Minor fixes and performance improvements ### [1.2.4] - 2016-12-06 * Fixed regression in output handling of scripts from 1.2.3 * Fixed support for LibreSSL detection as lib-openssl * Fixed issue with Zend Guard in the autoloader bootstrapping * Fixed support for loading partial provider repositories ### [1.2.3] - 2016-12-01 * Fixed bug in HgDriver failing to identify BitBucket repositories * Fixed support for loading partial provider repositories ### [1.2.2] - 2016-11-03 * Fixed selection of packages based on stability to be independent from package repository order * Fixed POST_DEPENDENCIES_SOLVING not containing some operations in edge cases * Fixed issue handling GitLab URLs containing dots and other special characters * Fixed issue on Windows when running composer at the root of a drive * Minor fixes ### [1.2.1] - 2016-09-12 * Fixed edge case issues with the static autoloader * Minor fixes ### [1.2.0] - 2016-07-19 * Security: Fixed [httpoxy](https://httpoxy.org/) vulnerability * Fixed `home` command to avoid rogue output on unix * Fixed output of git clones to clearly state when clones are from cache * (from 1.2 RC) Fixed ext-network-ipv6 to be php-ipv6 ### [1.2.0-RC] - 2016-07-04 * Added caching of git repositories if you have git 2.3+ installed. Repositories will now be cached once and then cloned from local cache so subsequent installs should be faster * Added detection of HEAD changes to the `status` command. If you `git checkout X` in a vendor directory for example it will tell you that it is not at the version that was installed * Added a virtual `php-ipv6` extension to require PHP compiled with IPv6 support * Added `--no-suggest` to `install` and `update` commands to skip output of suggestions at the end * Added `--type` to the `search` command to restrict to a given package type * Added fossil support as alternative to git/svn/.. for package downloads * Improved BitBucket OAuth support * Added support for blocking cache operations using COMPOSER_CACHE_DIR=/dev/null (or NUL on windows) * Added support for using declare(strict_types=1) in plugins * Added `--prefer-stable` and `--prefer-lowest` to the `require` command * Added `--no-scripts` to the `require` and `remove` commands * Added `_comment` top level key to the schema to endorse using it as a place to store comments (it can be a string or array of strings) * Added support for justinrainbow/json-schema 2.0 * Fixed binaries not being re-installed if deleted by users or the bin-dir changes. `update` and `install` will now re-install them * Many minor UX and docs improvements ### [1.1.3] - 2016-06-26 * Fixed bitbucket oauth instructions * Fixed version parsing issue * Fixed handling of bad proxies that modify JSON content on the fly ### [1.1.2] - 2016-05-31 * Fixed degraded mode issue when accessing packagist.org * Fixed GitHub access_token being added on subsequent requests in case of redirections * Fixed exclude-from-classmap not working in some circumstances * Fixed openssl warning preventing the use of config command for disabling tls ### [1.1.1] - 2016-05-17 * Fixed regression in handling of #reference which made it update every time * Fixed dev platform requirements being required even in --no-dev install from a lock file * Fixed parsing of extension versions that do not follow valid numbers, we now try to parse x.y.z and ignore the rest * Fixed exact constraints warnings appearing for 0.x versions * Fixed regression in the `remove` command ### [1.1.0] - 2016-05-10 * Added fallback to SSH for https bitbucket URLs * Added BaseCommand::isProxyCommand that can be overridden to mark a command as being a mere proxy, which helps avoid duplicate warnings etc on composer startup * Fixed archiving generating long paths in zip files on Windows ### [1.1.0-RC] - 2016-04-29 * Added ability for plugins to register their own composer commands * Optimized the autoloader initialization using static loading on PHP 5.6 and above, this reduces the load time for large classmaps to almost nothing * Added `--latest` to `show` command to show the latest version available of your dependencies * Added `--outdated` to `show` command an `composer outdated` alias for it, to show only packages in need of update * Added `--direct` to `show` and `outdated` commands to show only your direct dependencies in the listing * Added support for editing all top-level properties (name, minimum-stability, ...) as well as extra values via the `config` command * Added abandoned state warning to the `show` and `outdated` commands when listing latest packages * Added support for `~/` and `$HOME/` in the path repository paths * Added support for wildcards in the `show` command package filter, e.g. `composer show seld/*` * Added ability to call composer itself from scripts via `@composer ...` * Added untracked files detection to the `status` command * Added warning to `validate` command when using exact-version requires * Added warning once per domain when accessing insecure URLs with secure-http disabled * Added a dependency on composer/ca-bundle (extracted CA bundle management to a standalone lib) * Added support for empty directories when archiving to tar * Added an `init` event for plugins to react to, which occurs right after a Composer instance is fully initialized * Added many new detections of problems in the `why-not`/`prohibits` command to figure out why something does not get installed in the expected version * Added a deprecation notice for script event listeners that use legacy script classes * Fixed abandoned state not showing up if you had a package installed before it was marked abandoned * Fixed --no-dev updates creating an incomplete lock file, everything is now always resolved on update * Fixed partial updates in case the vendor dir was not up to date with the lock file ### [1.0.3] - 2016-04-29 * Security: Fixed possible command injection from the env vars into our sudo detection * Fixed interactive authentication with gitlab * Fixed class name replacement in plugins * Fixed classmap generation mistakenly detecting anonymous classes * Fixed auto-detection of stability flags in complex constraints like `2.0-dev || ^1.5` * Fixed content-length handling when redirecting to very small responses ### [1.0.2] - 2016-04-21 * Fixed regression in 1.0.1 on systems with mbstring.func_overload enabled * Fixed regression in 1.0.1 that made dev packages update to the latest reference even if not whitelisted in a partial update * Fixed init command ignoring the COMPOSER env var for choosing the json file name * Fixed error reporting bug when the dependency resolution fails * Fixed handling of `$` sign in composer config command in some cases it could corrupt the json file ### [1.0.1] - 2016-04-18 * Fixed URL updating when a package's URL changes, composer.lock now contains the right URL including correct reference * Fixed URL updating of the origin git remote as well for packages installed as git clone * Fixed binary .bat files generated from linux being incompatible with windows cmd * Fixed handling of paths with trailing slashes in path repository * Fixed create-project not using platform config when selecting a package * Fixed self-update not showing the channel it uses to perform the update * Fixed file downloads not failing loudly when the content does not match the Content-Length header * Fixed secure-http detecting some malformed URLs as insecure * Updated CA bundle ### [1.0.0] - 2016-04-05 * Added support for bitbucket-oauth configuration * Added warning when running composer as super user, set COMPOSER_ALLOW_SUPERUSER=1 to hide the warning if you really must * Added PluginManager::getGlobalComposer getter to retrieve the global instance (which can be null!) * Fixed dependency solver error reporting in many cases it now shows you proper errors instead of just saying a package does not exist * Fixed output of failed downloads appearing as 100% done instead of Failed * Fixed handling of empty directories when archiving, they are not skipped anymore * Fixed installation of broken plugins corrupting the vendor state when combined with symlinked path repositories ### [1.0.0-beta2] - 2016-03-27 * Break: The `install` command now turns into an `update` command automatically if you have no composer.lock. This was done only half-way before which caused inconsistencies * Break: By default the `remove` command now removes dependencies as well, and --update-with-dependencies is deprecated. Use --no-update-with-dependencies to get old behavior * Added support for update channels in `self-update`. All users will now update to stable builds by default. Run `self-update` with `--snapshot`, `--preview` or `--stable` to switch between update channels. * Added support for SSL_CERT_DIR env var and openssl.capath ini value * Added some conflict detection in `why-not` command * Added suggestion of root package's suggests in `create-project` command * Fixed `create-project` ignoring --ignore-platform-reqs when choosing a version of the package * Fixed `search` command in a directory without composer.json * Fixed path repository handling of symlinks on windows * Fixed PEAR repo handling to prefer HTTPS mirrors over HTTP ones * Fixed handling of Path env var on Windows, only PATH was accepted before * Small error reporting and docs improvements ### [1.0.0-beta1] - 2016-03-03 * Break: By default we now disable any non-secure protocols (http, git, svn). This may lead to issues if you rely on those. See `secure-http` config option. * Break: `show` / `list` command now only show installed packages by default. An `--all` option is added to show all packages. * Added VCS repo support for the GitLab API, see also `gitlab-oauth` and `gitlab-domains` config options * Added `prohibits` / `why-not` command to show what blocks an upgrade to a given package:version pair * Added --tree / -t to the `show` command to see all your installed packages in a tree view * Added --interactive / -i to the `update` command, which lets you pick packages to update interactively * Added `exec` command to run binaries while having bin-dir in the PATH for convenience * Added --root-reqs to the `update` command to update only your direct, first degree dependencies * Added `cafile` and `capath` config options to control HTTPS certificate authority * Added pubkey verification of composer.phar when running self-update * Added possibility to configure per-package `preferred-install` types for more flexibility between prefer-source and prefer-dist * Added unpushed-changes detection when updating dependencies and in the `status` command * Added COMPOSER_AUTH env var that lets you pass a json configuration like the auth.json file * Added `secure-http` and `disable-tls` config options to control HTTPS/HTTP * Added warning when Xdebug is enabled as it reduces performance quite a bit, hide it with COMPOSER_DISABLE_XDEBUG_WARN=1 if you must * Added duplicate key detection when loading composer.json * Added `sort-packages` config option to force sorting of the requirements when using the `require` command * Added support for the XDG Base Directory spec on linux * Added XzDownloader for xz file support * Fixed SSL support to fully verify peers in all PHP versions, unsecure HTTP is also disabled by default * Fixed stashing and cleaning up of untracked files when updating packages * Fixed plugins being enabled after installation even when --no-plugins * Many small bug fixes and additions ### [1.0.0-alpha11] - 2015-11-14 * Added config.platform to let you specify what your target environment looks like and make sure you do not inadvertently install dependencies that would break it * Added `exclude-from-classmap` in the autoload config that lets you ignore sub-paths of classmapped directories, or psr-0/4 directories when building optimized autoloaders * Added `path` repository type to install/symlink packages from local paths * Added possibility to reference script handlers from within other handlers using @script-name to reduce duplication * Added `suggests` command to show what packages are suggested, use -v to see more details * Added `content-hash` inside the composer.lock to restrict the warnings about outdated lock file to some specific changes in the composer.json file * Added `archive-format` and `archive-dir` config options to specify default values for the archive command * Added --classmap-authoritative to `install`, `update`, `require`, `remove` and `dump-autoload` commands, forcing the optimized classmap to be authoritative * Added -A / --with-dependencies to the `validate` command to allow validating all your dependencies recursively * Added --strict to the `validate` command to treat any warning as an error that then returns a non-zero exit code * Added a dependency on composer/semver, which is the externalized lib for all the version constraints parsing and handling * Added support for classmap autoloading to load plugin classes and script handlers * Added `bin-compat` config option that if set to `full` will create .bat proxy for binaries even if Composer runs in a linux VM * Added SPDX 2.0 support, and externalized that in a composer/spdx-licenses lib * Added warnings when the classmap autoloader finds duplicate classes * Added --file to the `archive` command to choose the filename * Added Ctrl+C handling in create-project to cancel the operation cleanly * Fixed version guessing to use ^ always, default to stable versions, and avoid versions that require a higher php version than you have * Fixed the lock file switching back and forth between old and new URL when a package URL is changed and many people run updates * Fixed partial updates updating things they shouldn't when the current vendor dir was out of date with the lock file * Fixed PHAR file creation to be more reproducible and always generate the exact same phar file from a given source * Fixed issue when checking out git branches or tags that are also the name of a file in the repo * Many minor fixes and documentation additions and UX improvements ### [1.0.0-alpha10] - 2015-04-14 * Break: The following event classes are deprecated and you should update your script handlers to use the new ones in type hints: - `Composer\Script\CommandEvent` is deprecated, use `Composer\Script\Event` - `Composer\Script\PackageEvent` is deprecated, use `Composer\Installer\PackageEvent` * Break: Output is now split between stdout and stderr. Any irrelevant output to each command is on stderr as per unix best practices. * Added support for npm-style semver operators (`^` and `-` ranges, ` ` = AND, `||` = OR) * Added --prefer-lowest to `update` command to allow testing a package with the lowest declared dependencies * Added support for parsing semver build metadata `+anything` at the end of versions * Added --sort-packages option to `require` command for sorting dependencies * Added --no-autoloader to `install` and `update` commands to skip autoload generation * Added --list to `run-script` command to see available scripts * Added --absolute to `config` command to get back absolute paths * Added `classmap-authoritative` config option, if enabled only the classmap info will be used by the composer autoloader * Added support for branch-alias on numeric branches * Added support for the `https_proxy`/`HTTPS_PROXY` env vars used only for https URLs * Added support for using real composer repos as local paths in `create-project` command * Added --no-dev to `licenses` command * Added support for PHP 7.0 nightly builds * Fixed detection of stability when parsing multiple constraints * Fixed installs from lock file containing updated composer.json requirement * Fixed the autoloader suffix in vendor/autoload.php changing in every build * Many minor fixes, documentation additions and UX improvements ### [1.0.0-alpha9] - 2014-12-07 * Added `remove` command to do the reverse of `require` * Added --ignore-platform-reqs to `install`/`update` commands to install even if you are missing a php extension or have an invalid php version * Added a warning when abandoned packages are being installed * Added auto-selection of the version constraint in the `require` command, which can now be used simply as `composer require foo/bar` * Added ability to define custom composer commands using scripts * Added `browse` command to open a browser to the given package's repo URL (or homepage with `-H`) * Added an `autoload-dev` section to declare dev-only autoload rules + a --no-dev flag to dump-autoload * Added an `auth.json` file, with `store-auths` config option * Added a `http-basic` config option to store login/pwds to hosts * Added failover to source/dist and vice-versa in case a download method fails * Added --path (-P) flag to the show command to see the install path of packages * Added --update-with-dependencies and --update-no-dev flags to the require command * Added `optimize-autoloader` config option to force the `-o` flag from the config * Added `clear-cache` command * Added a GzipDownloader to download single gzipped files * Added `ssh` support in the `github-protocols` config option * Added `pre-dependencies-solving` and `post-dependencies-solving` events * Added `pre-archive-cmd` and `post-archive-cmd` script events to the `archive` command * Added a `no-api` flag to GitHub VCS repos to skip the API but still get zip downloads * Added http-basic auth support for private git repos not on github * Added support for autoloading `.hh` files when running HHVM * Added support for PHP 5.6 * Added support for OTP auth when retrieving a GitHub API key * Fixed isolation of `files` autoloaded scripts to ensure they can not affect anything * Improved performance of solving dependencies * Improved SVN and Perforce support * A boatload of minor fixes, documentation additions and UX improvements ### [1.0.0-alpha8] - 2014-01-06 * Break: The `install` command now has --dev enabled by default. --no-dev can be used to install without dev requirements * Added `composer-plugin` package type to allow extensibility, and deprecated `composer-installer` * Added `psr-4` autoloading support and deprecated `target-dir` since it is a better alternative * Added --no-plugins flag to replace --no-custom-installers where available * Added `global` command to operate Composer in a user-global directory * Added `licenses` command to list the license of all your dependencies * Added `pre-status-cmd` and `post-status-cmd` script events to the `status` command * Added `post-root-package-install` and `post-create-project-cmd` script events to the `create-project` command * Added `pre-autoload-dump` script event * Added --rollback flag to self-update * Added --no-install flag to create-project to skip installing the dependencies * Added a `hhvm` platform package to require Facebook's HHVM implementation of PHP * Added `github-domains` config option to allow using GitHub Enterprise with Composer's GitHub support * Added `prepend-autoloader` config option to allow appending Composer's autoloader instead of the default prepend behavior * Added Perforce support to the VCS repository * Added a vendor/composer/autoload_files.php file that lists all files being included by the files autoloader * Added support for the `no_proxy` env var and other proxy support improvements * Added many robustness tweaks to make sure zip downloads work more consistently and corrupted caches are invalidated * Added the release date to `composer -V` output * Added `autoloader-suffix` config option to allow overriding the randomly generated autoloader class suffix * Fixed BitBucket API usage * Fixed parsing of inferred stability flags that are more stable than the minimum stability * Fixed installation order of plugins/custom installers * Fixed tilde and wildcard version constraints to be more intuitive regarding stabilities * Fixed handling of target-dir changes when updating packages * Improved performance of the class loader * Improved memory usage and performance of solving dependencies * Tons of minor bug fixes and improvements ### [1.0.0-alpha7] - 2013-05-04 * Break: For forward compatibility, you should change your deployment scripts to run `composer install --no-dev`. The install command will install dev dependencies by default starting in the next release * Break: The `update` command now has --dev enabled by default. --no-dev can be used to update without dev requirements, but it will create an incomplete lock file and is discouraged * Break: Removed support for lock files created before 2012-09-15 due to their outdated unusable format * Added `prefer-stable` flag to pick stable packages over unstable ones when possible * Added `preferred-install` config option to always enable --prefer-source or --prefer-dist * Added `diagnose` command to to system/network checks and find common problems * Added wildcard support in the update whitelist, e.g. to update all packages of a vendor do `composer update vendor/*` * Added `archive` command to archive the current directory or a given package * Added `run-script` command to manually trigger scripts * Added `proprietary` as valid license identifier for non-free code * Added a `php-64bit` platform package that you can require to force a 64bit php * Added a `lib-ICU` platform package * Added a new official package type `project` for project-bootstrapping packages * Added zip/dist local cache to speed up repetitive installations * Added `post-autoload-dump` script event * Added `Event::getDevMode` to let script handlers know if dev requirements are being installed * Added `discard-changes` config option to control the default behavior when updating "dirty" dependencies * Added `use-include-path` config option to make the autoloader look for files in the include path too * Added `cache-ttl`, `cache-files-ttl` and `cache-files-maxsize` config option * Added `cache-dir`, `cache-files-dir`, `cache-repo-dir` and `cache-vcs-dir` config option * Added support for using http(s) authentication to non-github repos * Added support for using multiple autoloaders at once (e.g. PHPUnit + application both using Composer autoloader) * Added support for .inc files for classmap autoloading (legacy support, do not do this on new projects!) * Added support for version constraints in show command, e.g. `composer show monolog/monolog 1.4.*` * Added support for svn repositories containing packages in a deeper path (see package-path option) * Added an `artifact` repository to scan a directory containing zipped packages * Added --no-dev flag to `install` and `update` commands * Added --stability (-s) flag to create-project to lower the required stability * Added --no-progress to `install` and `update` to hide the progress indicators * Added --available (-a) flag to the `show` command to display only available packages * Added --name-only (-N) flag to the `show` command to show only package names (one per line, no formatting) * Added --optimize-autoloader (-o) flag to optimize the autoloader from the `install` and `update` commands * Added -vv and -vvv flags to get more verbose output, can be useful to debug some issues * Added COMPOSER_NO_INTERACTION env var to do the equivalent of --no-interaction (should be set on build boxes, CI, PaaS) * Added PHP 5.2 compatibility to the autoloader configuration files so they can be used to configure another autoloader * Fixed handling of platform requirements of the root package when installing from lock * Fixed handling of require-dev dependencies * Fixed handling of unstable packages that should be downgraded to stable packages when updating to new version constraints * Fixed parsing of the `~` operator combined with unstable versions * Fixed the `require` command corrupting the json if the new requirement was invalid * Fixed support of aliases used together with `#` constraints * Improved output of dependency solver problems by grouping versions of a package together * Improved performance of classmap generation * Improved mercurial support in various places * Improved lock file format to minimize unnecessary diffs * Improved the `config` command to support all options * Improved the coverage of the `validate` command * Tons of minor bug fixes and improvements ### [1.0.0-alpha6] - 2012-10-23 * Schema: Added ability to pass additional options to repositories (i.e. ssh keys/client certificates to secure private repos) * Schema: Added a new `~` operator that should be preferred over `>=`, see http://getcomposer.org/doc/01-basic-usage.md#package-versions * Schema: Version constraints `` flags in require for restricting packages to a certain stability * Schema: Removed `recommend` * Schema: `suggest` is now informational and can use any description for a package, not only a constraint * Break: vendor/.composer/autoload.php has been moved to vendor/autoload.php, other files are now in vendor/composer/ * Added caching of repository metadata (faster startup times & failover if packagist is down) * Added removal of packages that are not needed anymore * Added include_path support for legacy projects that are full of require_once statements * Added installation notifications API to allow better statistics on Composer repositories * Added support for proxies that require authentication * Added support for private github repositories over https * Added autoloading support for root packages that use target-dir * Added awareness of the root package presence and support for it's provide/replace/conflict keys * Added IOInterface::isDecorated to test for colored output support * Added validation of licenses based on the [SPDX registry](https://spdx.org/licenses/) * Improved repository protocol to have large cacheable parts * Fixed various bugs relating to package aliasing, proxy configuration, binaries * Various bug fixes and docs improvements ### [1.0.0-alpha2] - 2012-04-03 * Added `create-project` command to install a project from scratch with composer * Added automated `classmap` autoloading support for non-PSR-0 compliant projects * Added human readable error reporting when deps can not be solved * Added support for private GitHub and SVN repositories (use --no-interaction for CI) * Added "file" downloader type to download plain files * Added support for authentication with svn repositories * Added autoload support for PEAR repositories * Improved clones from GitHub which now automatically select between git/https/http protocols * Improved `validate` command to give more feedback * Improved the `search` & `show` commands output * Removed dependency on filter_var * Various robustness & error handling improvements, docs fixes and more bug fixes ### 1.0.0-alpha1 - 2012-03-01 * Initial release [1.6.3]: https://github.com/composer/composer/compare/1.6.2...1.6.3 [1.6.2]: https://github.com/composer/composer/compare/1.6.1...1.6.2 [1.6.1]: https://github.com/composer/composer/compare/1.6.0...1.6.1 [1.6.0]: https://github.com/composer/composer/compare/1.6.0-RC...1.6.0 [1.6.0-RC]: https://github.com/composer/composer/compare/1.5.6...1.6.0-RC [1.5.6]: https://github.com/composer/composer/compare/1.5.5...1.5.6 [1.5.5]: https://github.com/composer/composer/compare/1.5.4...1.5.5 [1.5.4]: https://github.com/composer/composer/compare/1.5.3...1.5.4 [1.5.3]: https://github.com/composer/composer/compare/1.5.2...1.5.3 [1.5.2]: https://github.com/composer/composer/compare/1.5.1...1.5.2 [1.5.1]: https://github.com/composer/composer/compare/1.5.0...1.5.1 [1.5.0]: https://github.com/composer/composer/compare/1.4.3...1.5.0 [1.4.3]: https://github.com/composer/composer/compare/1.4.2...1.4.3 [1.4.2]: https://github.com/composer/composer/compare/1.4.1...1.4.2 [1.4.1]: https://github.com/composer/composer/compare/1.4.0...1.4.1 [1.4.0]: https://github.com/composer/composer/compare/1.3.3...1.4.0 [1.3.3]: https://github.com/composer/composer/compare/1.3.2...1.3.3 [1.3.2]: https://github.com/composer/composer/compare/1.3.1...1.3.2 [1.3.1]: https://github.com/composer/composer/compare/1.3.0...1.3.1 [1.3.0]: https://github.com/composer/composer/compare/1.3.0-RC...1.3.0 [1.3.0-RC]: https://github.com/composer/composer/compare/1.2.4...1.3.0-RC [1.2.4]: https://github.com/composer/composer/compare/1.2.3...1.2.4 [1.2.3]: https://github.com/composer/composer/compare/1.2.2...1.2.3 [1.2.2]: https://github.com/composer/composer/compare/1.2.1...1.2.2 [1.2.1]: https://github.com/composer/composer/compare/1.2.0...1.2.1 [1.2.0]: https://github.com/composer/composer/compare/1.2.0-RC...1.2.0 [1.2.0-RC]: https://github.com/composer/composer/compare/1.1.3...1.2.0-RC [1.1.3]: https://github.com/composer/composer/compare/1.1.2...1.1.3 [1.1.2]: https://github.com/composer/composer/compare/1.1.1...1.1.2 [1.1.1]: https://github.com/composer/composer/compare/1.1.0...1.1.1 [1.1.0]: https://github.com/composer/composer/compare/1.0.3...1.1.0 [1.1.0-RC]: https://github.com/composer/composer/compare/1.0.3...1.1.0-RC [1.0.3]: https://github.com/composer/composer/compare/1.0.2...1.0.3 [1.0.2]: https://github.com/composer/composer/compare/1.0.1...1.0.2 [1.0.1]: https://github.com/composer/composer/compare/1.0.0...1.0.1 [1.0.0]: https://github.com/composer/composer/compare/1.0.0-beta2...1.0.0 [1.0.0-beta2]: https://github.com/composer/composer/compare/1.0.0-beta1...1.0.0-beta2 [1.0.0-beta1]: https://github.com/composer/composer/compare/1.0.0-alpha11...1.0.0-beta1 [1.0.0-alpha11]: https://github.com/composer/composer/compare/1.0.0-alpha10...1.0.0-alpha11 [1.0.0-alpha10]: https://github.com/composer/composer/compare/1.0.0-alpha9...1.0.0-alpha10 [1.0.0-alpha9]: https://github.com/composer/composer/compare/1.0.0-alpha8...1.0.0-alpha9 [1.0.0-alpha8]: https://github.com/composer/composer/compare/1.0.0-alpha7...1.0.0-alpha8 [1.0.0-alpha7]: https://github.com/composer/composer/compare/1.0.0-alpha6...1.0.0-alpha7 [1.0.0-alpha6]: https://github.com/composer/composer/compare/1.0.0-alpha5...1.0.0-alpha6 [1.0.0-alpha5]: https://github.com/composer/composer/compare/1.0.0-alpha4...1.0.0-alpha5 [1.0.0-alpha4]: https://github.com/composer/composer/compare/1.0.0-alpha3...1.0.0-alpha4 [1.0.0-alpha3]: https://github.com/composer/composer/compare/1.0.0-alpha2...1.0.0-alpha3 [1.0.0-alpha2]: https://github.com/composer/composer/compare/1.0.0-alpha1...1.0.0-alpha2 composer-1.6.3/LICENSE000066400000000000000000000020541323436022200143530ustar00rootroot00000000000000Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. composer-1.6.3/PORTING_INFO000066400000000000000000000031001323436022200152170ustar00rootroot00000000000000 * add rule * p = direct literal; always < 0 for installed rpm rules * d, if < 0 direct literal, if > 0 offset into whatprovides, if == 0 rule is assertion (look at p only) * * * A requires b, b provided by B1,B2,B3 => (-A|B1|B2|B3) * * p < 0 : pkg id of A * d > 0 : Offset in whatprovidesdata (list of providers of b) * * A conflicts b, b provided by B1,B2,B3 => (-A|-B1), (-A|-B2), (-A|-B3) * p < 0 : pkg id of A * d < 0 : Id of solvable (e.g. B1) * * d == 0: unary rule, assertion => (A) or (-A) * * Install: p > 0, d = 0 (A) user requested install * Remove: p < 0, d = 0 (-A) user requested remove (also: uninstallable) * Requires: p < 0, d > 0 (-A|B1|B2|...) d: * Updates: p > 0, d > 0 (A|B1|B2|...) d: * Conflicts: p < 0, d < 0 (-A|-B) either p (conflict issuer) or d (conflict provider) (binary rule) * also used for obsoletes * ?: p > 0, d < 0 (A|-B) * No-op ?: p = 0, d = 0 (null) (used as policy rule placeholder) * * resulting watches: * ------------------ * Direct assertion (no watch needed)( if d <0 ) --> d = 0, w1 = p, w2 = 0 * Binary rule: p = first literal, d = 0, w2 = second literal, w1 = p * every other : w1 = p, w2 = whatprovidesdata[d]; * Disabled rule: w1 = 0 * * always returns a rule for non-rpm rules p > 0, d = 0, (A), w1 = p, w2 = 0 p < 0, d = 0, (-A), w1 = p, w2 = 0 p !=0, d = 0, (p|q), w1 = p, w2 = q composer-1.6.3/README.md000066400000000000000000000052011323436022200146220ustar00rootroot00000000000000Composer - Dependency Management for PHP ======================================== Composer helps you declare, manage, and install dependencies of PHP projects. See [https://getcomposer.org/](https://getcomposer.org/) for more information and documentation. [![Build Status](https://travis-ci.org/composer/composer.svg?branch=master)](https://travis-ci.org/composer/composer) [![Dependency Status](https://www.versioneye.com/php/composer:composer/dev-master/badge.svg)](https://www.versioneye.com/php/composer:composer/dev-master) [![Reference Status](https://www.versioneye.com/php/composer:composer/reference_badge.svg?style=flat)](https://www.versioneye.com/php/composer:composer/references) Installation / Usage -------------------- Download and install Composer by following the [official instructions](https://getcomposer.org/download/). For usage, see [the documentation](https://getcomposer.org/doc/). Packages -------- Find packages on [Packagist](https://packagist.org). Community --------- IRC channels are on irc.freenode.org: [#composer](irc://irc.freenode.org/composer) for users and [#composer-dev](irc://irc.freenode.org/composer-dev) for development. For support, Stack Overflow also offers a good collection of [Composer related questions](https://stackoverflow.com/questions/tagged/composer-php). Please note that this project is released with a [Contributor Code of Conduct](http://contributor-covenant.org/version/1/4/). By participating in this project and its community you agree to abide by those terms. Requirements ------------ PHP 5.3.2 or above (at least 5.3.4 recommended to avoid potential bugs) Authors ------- - Nils Adermann | [GitHub](https://github.com/naderman) | [Twitter](https://twitter.com/naderman) | | [naderman.de](http://naderman.de) - Jordi Boggiano | [GitHub](https://github.com/Seldaek) | [Twitter](https://twitter.com/seldaek) | | [seld.be](http://seld.be) See also the list of [contributors](https://github.com/composer/composer/contributors) who participated in this project. Security Reports ---------------- Please send any sensitive issue to [security@packagist.org](mailto:security@packagist.org). Thanks! License ------- Composer is licensed under the MIT License - see the [LICENSE](LICENSE) file for details Acknowledgments --------------- - This project's Solver started out as a PHP port of openSUSE's [Libzypp satsolver](https://en.opensuse.org/openSUSE:Libzypp_satsolver). - This project uses hiddeninput.exe to prompt for passwords on windows, sources and details can be found on the [github page of the project](https://github.com/Seldaek/hidden-input). composer-1.6.3/appveyor.yml000066400000000000000000000013731323436022200157410ustar00rootroot00000000000000build: false clone_depth: 5 environment: PHP_CHOCO_VERSION: 7.2.0 PHP_CACHE_DIR: C:\tools\php cache: - '%PHP_CACHE_DIR% -> appveyor.yml' init: - SET PATH=%PHP_CACHE_DIR%;%PATH% - SET COMPOSER_CACHE_DIR=%PHP_CACHE_DIR% - SET COMPOSER_NO_INTERACTION=1 - SET PHP=0 - SET ANSICON=121x90 (121x90) install: - IF EXIST %PHP_CACHE_DIR% (SET PHP=1) - IF %PHP%==0 cinst php -y --version %PHP_CHOCO_VERSION% --params "/InstallDir:%PHP_CACHE_DIR%" - IF %PHP%==0 cinst composer -y --ia "/DEV=%PHP_CACHE_DIR%" - php -v - IF %PHP%==0 (composer --version) ELSE (composer self-update) - cd %APPVEYOR_BUILD_FOLDER% - composer install --prefer-dist --no-progress test_script: - cd %APPVEYOR_BUILD_FOLDER% - vendor\bin\phpunit --colors=always composer-1.6.3/bin/000077500000000000000000000000001323436022200141155ustar00rootroot00000000000000composer-1.6.3/bin/compile000077500000000000000000000017061323436022200154770ustar00rootroot00000000000000#!/usr/bin/env php compile(); } catch (\Exception $e) { echo 'Failed to compile phar: ['.get_class($e).'] '.$e->getMessage().' at '.$e->getFile().':'.$e->getLine().PHP_EOL; exit(1); } composer-1.6.3/bin/composer000077500000000000000000000030631323436022200156740ustar00rootroot00000000000000#!/usr/bin/env php check(); unset($xdebug); if (function_exists('ini_set')) { @ini_set('display_errors', 1); $memoryInBytes = function ($value) { $unit = strtolower(substr($value, -1, 1)); $value = (int) $value; switch($unit) { case 'g': $value *= 1024; // no break (cumulative multiplier) case 'm': $value *= 1024; // no break (cumulative multiplier) case 'k': $value *= 1024; } return $value; }; $memoryLimit = trim(ini_get('memory_limit')); // Increase memory_limit if it is lower than 1.5GB if ($memoryLimit != -1 && $memoryInBytes($memoryLimit) < 1024 * 1024 * 1536) { @ini_set('memory_limit', '1536M'); } // Set user defined memory limit if ($memoryLimit = getenv('COMPOSER_MEMORY_LIMIT')) { @ini_set('memory_limit', $memoryLimit); } unset($memoryInBytes, $memoryLimit); } putenv('COMPOSER_BINARY='.realpath($_SERVER['argv'][0])); // run the command application $application = new Application(); $application->run(null, $output); composer-1.6.3/composer.json000066400000000000000000000042071323436022200160720ustar00rootroot00000000000000{ "name": "composer/composer", "description": "Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere.", "keywords": ["package", "dependency", "autoload"], "homepage": "https://getcomposer.org/", "type": "library", "license": "MIT", "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "http://www.naderman.de" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" } ], "support": { "irc": "irc://irc.freenode.org/composer", "issues": "https://github.com/composer/composer/issues" }, "require": { "php": "^5.3.2 || ^7.0", "justinrainbow/json-schema": "^3.0 || ^4.0 || ^5.0", "composer/ca-bundle": "^1.0", "composer/semver": "^1.0", "composer/spdx-licenses": "^1.2", "seld/jsonlint": "^1.4", "symfony/console": "^2.7 || ^3.0 || ^4.0", "symfony/finder": "^2.7 || ^3.0 || ^4.0", "symfony/process": "^2.7 || ^3.0 || ^4.0", "symfony/filesystem": "^2.7 || ^3.0 || ^4.0", "seld/phar-utils": "^1.0", "seld/cli-prompt": "^1.0", "psr/log": "^1.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35 || ^5.7", "phpunit/phpunit-mock-objects": "^2.3 || ^3.0" }, "config": { "platform": { "php": "5.3.9" } }, "suggest": { "ext-zip": "Enabling the zip extension allows you to unzip archives", "ext-zlib": "Allow gzip compression of HTTP requests", "ext-openssl": "Enabling the openssl extension allows you to access https URLs for repositories and packages" }, "autoload": { "psr-4": { "Composer\\": "src/Composer" } }, "autoload-dev": { "psr-4": { "Composer\\Test\\": "tests/Composer/Test" } }, "bin": ["bin/composer"], "extra": { "branch-alias": { "dev-master": "1.6-dev" } }, "scripts": { "test": "phpunit" } } composer-1.6.3/composer.lock000066400000000000000000001655151323436022200160630ustar00rootroot00000000000000{ "_readme": [ "This file locks the dependencies of your project to a known state", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], "content-hash": "8c8fe8c8c57c958b318515f636a6839e", "packages": [ { "name": "composer/ca-bundle", "version": "1.1.0", "source": { "type": "git", "url": "https://github.com/composer/ca-bundle.git", "reference": "943b2c4fcad1ef178d16a713c2468bf7e579c288" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/composer/ca-bundle/zipball/943b2c4fcad1ef178d16a713c2468bf7e579c288", "reference": "943b2c4fcad1ef178d16a713c2468bf7e579c288", "shasum": "" }, "require": { "ext-openssl": "*", "ext-pcre": "*", "php": "^5.3.2 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35", "psr/log": "^1.0", "symfony/process": "^2.5 || ^3.0 || ^4.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { "Composer\\CaBundle\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" } ], "description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.", "keywords": [ "cabundle", "cacert", "certificate", "ssl", "tls" ], "time": "2017-11-29T09:37:33+00:00" }, { "name": "composer/semver", "version": "1.4.2", "source": { "type": "git", "url": "https://github.com/composer/semver.git", "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/composer/semver/zipball/c7cb9a2095a074d131b65a8a0cd294479d785573", "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573", "shasum": "" }, "require": { "php": "^5.3.2 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.5 || ^5.0.5", "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { "Composer\\Semver\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "http://www.naderman.de" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" }, { "name": "Rob Bast", "email": "rob.bast@gmail.com", "homepage": "http://robbast.nl" } ], "description": "Semver library that offers utilities, version constraint parsing and validation.", "keywords": [ "semantic", "semver", "validation", "versioning" ], "time": "2016-08-30T16:08:34+00:00" }, { "name": "composer/spdx-licenses", "version": "1.3.0", "source": { "type": "git", "url": "https://github.com/composer/spdx-licenses.git", "reference": "7e111c50db92fa2ced140f5ba23b4e261bc77a30" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/composer/spdx-licenses/zipball/7e111c50db92fa2ced140f5ba23b4e261bc77a30", "reference": "7e111c50db92fa2ced140f5ba23b4e261bc77a30", "shasum": "" }, "require": { "php": "^5.3.2 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5", "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { "Composer\\Spdx\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "http://www.naderman.de" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" }, { "name": "Rob Bast", "email": "rob.bast@gmail.com", "homepage": "http://robbast.nl" } ], "description": "SPDX licenses list and validation library.", "keywords": [ "license", "spdx", "validator" ], "time": "2018-01-31T13:17:27+00:00" }, { "name": "justinrainbow/json-schema", "version": "5.2.6", "source": { "type": "git", "url": "https://github.com/justinrainbow/json-schema.git", "reference": "d283e11b6e14c6f4664cf080415c4341293e5bbd" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/d283e11b6e14c6f4664cf080415c4341293e5bbd", "reference": "d283e11b6e14c6f4664cf080415c4341293e5bbd", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { "friendsofphp/php-cs-fixer": "^2.1", "json-schema/json-schema-test-suite": "1.2.0", "phpunit/phpunit": "^4.8.22" }, "bin": [ "bin/validate-json" ], "type": "library", "extra": { "branch-alias": { "dev-master": "5.0.x-dev" } }, "autoload": { "psr-4": { "JsonSchema\\": "src/JsonSchema/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Bruno Prieto Reis", "email": "bruno.p.reis@gmail.com" }, { "name": "Justin Rainbow", "email": "justin.rainbow@gmail.com" }, { "name": "Igor Wiedler", "email": "igor@wiedler.ch" }, { "name": "Robert Schönthal", "email": "seroscho@googlemail.com" } ], "description": "A library to validate a json schema.", "homepage": "https://github.com/justinrainbow/json-schema", "keywords": [ "json", "schema" ], "time": "2017-10-21T13:15:38+00:00" }, { "name": "psr/log", "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", "shasum": "" }, "require": { "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { "Psr\\Log\\": "Psr/Log/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "http://www.php-fig.org/" } ], "description": "Common interface for logging libraries", "homepage": "https://github.com/php-fig/log", "keywords": [ "log", "psr", "psr-3" ], "time": "2016-10-10T12:19:37+00:00" }, { "name": "seld/cli-prompt", "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/Seldaek/cli-prompt.git", "reference": "a19a7376a4689d4d94cab66ab4f3c816019ba8dd" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/Seldaek/cli-prompt/zipball/a19a7376a4689d4d94cab66ab4f3c816019ba8dd", "reference": "a19a7376a4689d4d94cab66ab4f3c816019ba8dd", "shasum": "" }, "require": { "php": ">=5.3" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { "Seld\\CliPrompt\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be" } ], "description": "Allows you to prompt for user input on the command line, and optionally hide the characters they type", "keywords": [ "cli", "console", "hidden", "input", "prompt" ], "time": "2017-03-18T11:32:45+00:00" }, { "name": "seld/jsonlint", "version": "1.7.0", "source": { "type": "git", "url": "https://github.com/Seldaek/jsonlint.git", "reference": "9b355654ea99460397b89c132b5c1087b6bf4473" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/9b355654ea99460397b89c132b5c1087b6bf4473", "reference": "9b355654ea99460397b89c132b5c1087b6bf4473", "shasum": "" }, "require": { "php": "^5.3 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" }, "bin": [ "bin/jsonlint" ], "type": "library", "autoload": { "psr-4": { "Seld\\JsonLint\\": "src/Seld/JsonLint/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" } ], "description": "JSON Linter", "keywords": [ "json", "linter", "parser", "validator" ], "time": "2018-01-03T12:13:57+00:00" }, { "name": "seld/phar-utils", "version": "1.0.1", "source": { "type": "git", "url": "https://github.com/Seldaek/phar-utils.git", "reference": "7009b5139491975ef6486545a39f3e6dad5ac30a" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/Seldaek/phar-utils/zipball/7009b5139491975ef6486545a39f3e6dad5ac30a", "reference": "7009b5139491975ef6486545a39f3e6dad5ac30a", "shasum": "" }, "require": { "php": ">=5.3" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { "Seld\\PharUtils\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be" } ], "description": "PHAR file format utilities, for when PHP phars you up", "keywords": [ "phra" ], "time": "2015-10-13T18:44:15+00:00" }, { "name": "symfony/console", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/console.git", "reference": "46270f1ca44f08ebc134ce120fd2c2baf5fd63de" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/console/zipball/46270f1ca44f08ebc134ce120fd2c2baf5fd63de", "reference": "46270f1ca44f08ebc134ce120fd2c2baf5fd63de", "shasum": "" }, "require": { "php": ">=5.3.9", "symfony/debug": "^2.7.2|~3.0.0", "symfony/polyfill-mbstring": "~1.0" }, "require-dev": { "psr/log": "~1.0", "symfony/event-dispatcher": "~2.1|~3.0.0", "symfony/process": "~2.1|~3.0.0" }, "suggest": { "psr/log": "For using the console logger", "symfony/event-dispatcher": "", "symfony/process": "" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Console\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Console Component", "homepage": "https://symfony.com", "time": "2017-11-29T09:33:18+00:00" }, { "name": "symfony/debug", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/debug.git", "reference": "e72a0340dc2e273b3c4398d8eef9157ba51d8b95" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/debug/zipball/e72a0340dc2e273b3c4398d8eef9157ba51d8b95", "reference": "e72a0340dc2e273b3c4398d8eef9157ba51d8b95", "shasum": "" }, "require": { "php": ">=5.3.9", "psr/log": "~1.0" }, "conflict": { "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" }, "require-dev": { "symfony/class-loader": "~2.2|~3.0.0", "symfony/http-kernel": "~2.3.24|~2.5.9|^2.6.2|~3.0.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Debug\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Debug Component", "homepage": "https://symfony.com", "time": "2017-11-19T19:05:05+00:00" }, { "name": "symfony/filesystem", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", "reference": "15ceb6736a9eebd0d99f9e05a62296ab6ce1cf2b" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/filesystem/zipball/15ceb6736a9eebd0d99f9e05a62296ab6ce1cf2b", "reference": "15ceb6736a9eebd0d99f9e05a62296ab6ce1cf2b", "shasum": "" }, "require": { "php": ">=5.3.9" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Filesystem\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", "time": "2017-11-19T18:39:05+00:00" }, { "name": "symfony/finder", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", "reference": "efeceae6a05a9b2fcb3391333f1d4a828ff44ab8" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/finder/zipball/efeceae6a05a9b2fcb3391333f1d4a828ff44ab8", "reference": "efeceae6a05a9b2fcb3391333f1d4a828ff44ab8", "shasum": "" }, "require": { "php": ">=5.3.9" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Finder\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", "time": "2017-11-05T15:25:56+00:00" }, { "name": "symfony/polyfill-mbstring", "version": "v1.6.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", "reference": "2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296", "reference": "2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296", "shasum": "" }, "require": { "php": ">=5.3.3" }, "suggest": { "ext-mbstring": "For best performance" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.6-dev" } }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, "files": [ "bootstrap.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Nicolas Grekas", "email": "p@tchwork.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony polyfill for the Mbstring extension", "homepage": "https://symfony.com", "keywords": [ "compatibility", "mbstring", "polyfill", "portable", "shim" ], "time": "2017-10-11T12:05:26+00:00" }, { "name": "symfony/process", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/process.git", "reference": "d25449e031f600807949aab7cadbf267712f4eee" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/process/zipball/d25449e031f600807949aab7cadbf267712f4eee", "reference": "d25449e031f600807949aab7cadbf267712f4eee", "shasum": "" }, "require": { "php": ">=5.3.9" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Process\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Process Component", "homepage": "https://symfony.com", "time": "2017-11-05T15:25:56+00:00" } ], "packages-dev": [ { "name": "doctrine/instantiator", "version": "1.0.5", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d", "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d", "shasum": "" }, "require": { "php": ">=5.3,<8.0-DEV" }, "require-dev": { "athletic/athletic": "~0.1.8", "ext-pdo": "*", "ext-phar": "*", "phpunit/phpunit": "~4.0", "squizlabs/php_codesniffer": "~2.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Marco Pivetta", "email": "ocramius@gmail.com", "homepage": "http://ocramius.github.com/" } ], "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", "homepage": "https://github.com/doctrine/instantiator", "keywords": [ "constructor", "instantiate" ], "time": "2015-06-14T21:17:01+00:00" }, { "name": "phpdocumentor/reflection-docblock", "version": "2.0.5", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", "reference": "e6a969a640b00d8daa3c66518b0405fb41ae0c4b" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/e6a969a640b00d8daa3c66518b0405fb41ae0c4b", "reference": "e6a969a640b00d8daa3c66518b0405fb41ae0c4b", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "~4.0" }, "suggest": { "dflydev/markdown": "~1.0", "erusev/parsedown": "~1.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.0.x-dev" } }, "autoload": { "psr-0": { "phpDocumentor": [ "src/" ] } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Mike van Riel", "email": "mike.vanriel@naenius.com" } ], "time": "2016-01-25T08:17:30+00:00" }, { "name": "phpspec/prophecy", "version": "1.7.3", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", "reference": "e4ed002c67da8eceb0eb8ddb8b3847bb53c5c2bf" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/phpspec/prophecy/zipball/e4ed002c67da8eceb0eb8ddb8b3847bb53c5c2bf", "reference": "e4ed002c67da8eceb0eb8ddb8b3847bb53c5c2bf", "shasum": "" }, "require": { "doctrine/instantiator": "^1.0.2", "php": "^5.3|^7.0", "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0", "sebastian/comparator": "^1.1|^2.0", "sebastian/recursion-context": "^1.0|^2.0|^3.0" }, "require-dev": { "phpspec/phpspec": "^2.5|^3.2", "phpunit/phpunit": "^4.8.35 || ^5.7" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.7.x-dev" } }, "autoload": { "psr-0": { "Prophecy\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Konstantin Kudryashov", "email": "ever.zet@gmail.com", "homepage": "http://everzet.com" }, { "name": "Marcello Duarte", "email": "marcello.duarte@gmail.com" } ], "description": "Highly opinionated mocking framework for PHP 5.3+", "homepage": "https://github.com/phpspec/prophecy", "keywords": [ "Double", "Dummy", "fake", "mock", "spy", "stub" ], "time": "2017-11-24T13:59:53+00:00" }, { "name": "phpunit/php-code-coverage", "version": "2.2.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/eabf68b476ac7d0f73793aada060f1c1a9bf8979", "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979", "shasum": "" }, "require": { "php": ">=5.3.3", "phpunit/php-file-iterator": "~1.3", "phpunit/php-text-template": "~1.2", "phpunit/php-token-stream": "~1.3", "sebastian/environment": "^1.3.2", "sebastian/version": "~1.0" }, "require-dev": { "ext-xdebug": ">=2.1.4", "phpunit/phpunit": "~4" }, "suggest": { "ext-dom": "*", "ext-xdebug": ">=2.2.1", "ext-xmlwriter": "*" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.2.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sb@sebastian-bergmann.de", "role": "lead" } ], "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", "homepage": "https://github.com/sebastianbergmann/php-code-coverage", "keywords": [ "coverage", "testing", "xunit" ], "time": "2015-10-06T15:47:00+00:00" }, { "name": "phpunit/php-file-iterator", "version": "1.4.5", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git", "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/730b01bc3e867237eaac355e06a36b85dd93a8b4", "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4", "shasum": "" }, "require": { "php": ">=5.3.3" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.4.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sb@sebastian-bergmann.de", "role": "lead" } ], "description": "FilterIterator implementation that filters files based on a list of suffixes.", "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", "keywords": [ "filesystem", "iterator" ], "time": "2017-11-27T13:52:08+00:00" }, { "name": "phpunit/php-text-template", "version": "1.2.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-text-template.git", "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686", "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686", "shasum": "" }, "require": { "php": ">=5.3.3" }, "type": "library", "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de", "role": "lead" } ], "description": "Simple template engine.", "homepage": "https://github.com/sebastianbergmann/php-text-template/", "keywords": [ "template" ], "time": "2015-06-21T13:50:34+00:00" }, { "name": "phpunit/php-timer", "version": "1.0.9", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-timer.git", "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", "shasum": "" }, "require": { "php": "^5.3.3 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sb@sebastian-bergmann.de", "role": "lead" } ], "description": "Utility class for timing", "homepage": "https://github.com/sebastianbergmann/php-timer/", "keywords": [ "timer" ], "time": "2017-02-26T11:10:40+00:00" }, { "name": "phpunit/php-token-stream", "version": "1.4.12", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-token-stream.git", "reference": "1ce90ba27c42e4e44e6d8458241466380b51fa16" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/1ce90ba27c42e4e44e6d8458241466380b51fa16", "reference": "1ce90ba27c42e4e44e6d8458241466380b51fa16", "shasum": "" }, "require": { "ext-tokenizer": "*", "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "~4.2" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.4-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" } ], "description": "Wrapper around PHP's tokenizer extension.", "homepage": "https://github.com/sebastianbergmann/php-token-stream/", "keywords": [ "tokenizer" ], "time": "2017-12-04T08:55:13+00:00" }, { "name": "phpunit/phpunit", "version": "4.8.36", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", "reference": "46023de9a91eec7dfb06cc56cb4e260017298517" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/46023de9a91eec7dfb06cc56cb4e260017298517", "reference": "46023de9a91eec7dfb06cc56cb4e260017298517", "shasum": "" }, "require": { "ext-dom": "*", "ext-json": "*", "ext-pcre": "*", "ext-reflection": "*", "ext-spl": "*", "php": ">=5.3.3", "phpspec/prophecy": "^1.3.1", "phpunit/php-code-coverage": "~2.1", "phpunit/php-file-iterator": "~1.4", "phpunit/php-text-template": "~1.2", "phpunit/php-timer": "^1.0.6", "phpunit/phpunit-mock-objects": "~2.3", "sebastian/comparator": "~1.2.2", "sebastian/diff": "~1.2", "sebastian/environment": "~1.3", "sebastian/exporter": "~1.2", "sebastian/global-state": "~1.0", "sebastian/version": "~1.0", "symfony/yaml": "~2.1|~3.0" }, "suggest": { "phpunit/php-invoker": "~1.1" }, "bin": [ "phpunit" ], "type": "library", "extra": { "branch-alias": { "dev-master": "4.8.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de", "role": "lead" } ], "description": "The PHP Unit Testing framework.", "homepage": "https://phpunit.de/", "keywords": [ "phpunit", "testing", "xunit" ], "time": "2017-06-21T08:07:12+00:00" }, { "name": "phpunit/phpunit-mock-objects", "version": "2.3.8", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/ac8e7a3db35738d56ee9a76e78a4e03d97628983", "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983", "shasum": "" }, "require": { "doctrine/instantiator": "^1.0.2", "php": ">=5.3.3", "phpunit/php-text-template": "~1.2", "sebastian/exporter": "~1.2" }, "require-dev": { "phpunit/phpunit": "~4.4" }, "suggest": { "ext-soap": "*" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.3.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sb@sebastian-bergmann.de", "role": "lead" } ], "description": "Mock Object library for PHPUnit", "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", "keywords": [ "mock", "xunit" ], "time": "2015-10-02T06:51:40+00:00" }, { "name": "sebastian/comparator", "version": "1.2.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/comparator.git", "reference": "2b7424b55f5047b47ac6e5ccb20b2aea4011d9be" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2b7424b55f5047b47ac6e5ccb20b2aea4011d9be", "reference": "2b7424b55f5047b47ac6e5ccb20b2aea4011d9be", "shasum": "" }, "require": { "php": ">=5.3.3", "sebastian/diff": "~1.2", "sebastian/exporter": "~1.2 || ~2.0" }, "require-dev": { "phpunit/phpunit": "~4.4" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.2.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" }, { "name": "Volker Dusch", "email": "github@wallbash.com" }, { "name": "Bernhard Schussek", "email": "bschussek@2bepublished.at" }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" } ], "description": "Provides the functionality to compare PHP values for equality", "homepage": "http://www.github.com/sebastianbergmann/comparator", "keywords": [ "comparator", "compare", "equality" ], "time": "2017-01-29T09:50:25+00:00" }, { "name": "sebastian/diff", "version": "1.4.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", "reference": "7f066a26a962dbe58ddea9f72a4e82874a3975a4" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/7f066a26a962dbe58ddea9f72a4e82874a3975a4", "reference": "7f066a26a962dbe58ddea9f72a4e82874a3975a4", "shasum": "" }, "require": { "php": "^5.3.3 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.4-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Kore Nordmann", "email": "mail@kore-nordmann.de" }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" } ], "description": "Diff implementation", "homepage": "https://github.com/sebastianbergmann/diff", "keywords": [ "diff" ], "time": "2017-05-22T07:24:03+00:00" }, { "name": "sebastian/environment", "version": "1.3.8", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", "reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/be2c607e43ce4c89ecd60e75c6a85c126e754aea", "reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea", "shasum": "" }, "require": { "php": "^5.3.3 || ^7.0" }, "require-dev": { "phpunit/phpunit": "^4.8 || ^5.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.3.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" } ], "description": "Provides functionality to handle HHVM/PHP environments", "homepage": "http://www.github.com/sebastianbergmann/environment", "keywords": [ "Xdebug", "environment", "hhvm" ], "time": "2016-08-18T05:49:44+00:00" }, { "name": "sebastian/exporter", "version": "1.2.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/exporter.git", "reference": "42c4c2eec485ee3e159ec9884f95b431287edde4" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/42c4c2eec485ee3e159ec9884f95b431287edde4", "reference": "42c4c2eec485ee3e159ec9884f95b431287edde4", "shasum": "" }, "require": { "php": ">=5.3.3", "sebastian/recursion-context": "~1.0" }, "require-dev": { "ext-mbstring": "*", "phpunit/phpunit": "~4.4" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.3.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" }, { "name": "Volker Dusch", "email": "github@wallbash.com" }, { "name": "Bernhard Schussek", "email": "bschussek@2bepublished.at" }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" }, { "name": "Adam Harvey", "email": "aharvey@php.net" } ], "description": "Provides the functionality to export PHP variables for visualization", "homepage": "http://www.github.com/sebastianbergmann/exporter", "keywords": [ "export", "exporter" ], "time": "2016-06-17T09:04:28+00:00" }, { "name": "sebastian/global-state", "version": "1.1.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bc37d50fea7d017d3d340f230811c9f1d7280af4", "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "~4.2" }, "suggest": { "ext-uopz": "*" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" } ], "description": "Snapshotting of global state", "homepage": "http://www.github.com/sebastianbergmann/global-state", "keywords": [ "global state" ], "time": "2015-10-12T03:26:01+00:00" }, { "name": "sebastian/recursion-context", "version": "1.0.5", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", "reference": "b19cc3298482a335a95f3016d2f8a6950f0fbcd7" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/b19cc3298482a335a95f3016d2f8a6950f0fbcd7", "reference": "b19cc3298482a335a95f3016d2f8a6950f0fbcd7", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "~4.4" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" }, { "name": "Adam Harvey", "email": "aharvey@php.net" } ], "description": "Provides functionality to recursively process PHP variables", "homepage": "http://www.github.com/sebastianbergmann/recursion-context", "time": "2016-10-03T07:41:43+00:00" }, { "name": "sebastian/version", "version": "1.0.6", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/version.git", "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/58b3a85e7999757d6ad81c787a1fbf5ff6c628c6", "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6", "shasum": "" }, "type": "library", "autoload": { "classmap": [ "src/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de", "role": "lead" } ], "description": "Library that helps with managing the version number of Git-hosted PHP projects", "homepage": "https://github.com/sebastianbergmann/version", "time": "2015-06-21T13:59:46+00:00" }, { "name": "symfony/yaml", "version": "v2.8.32", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", "reference": "968ef42161e4bc04200119da473077f9e7015128" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/yaml/zipball/968ef42161e4bc04200119da473077f9e7015128", "reference": "968ef42161e4bc04200119da473077f9e7015128", "shasum": "" }, "require": { "php": ">=5.3.9" }, "type": "library", "extra": { "branch-alias": { "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Yaml\\": "" }, "exclude-from-classmap": [ "/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", "time": "2017-11-29T09:33:18+00:00" } ], "aliases": [], "minimum-stability": "stable", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, "platform": { "php": "^5.3.2 || ^7.0" }, "platform-dev": [], "platform-overrides": { "php": "5.3.9" } } composer-1.6.3/doc/000077500000000000000000000000001323436022200141125ustar00rootroot00000000000000composer-1.6.3/doc/00-intro.md000066400000000000000000000127501323436022200160110ustar00rootroot00000000000000# Introduction Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. ## Dependency management Composer is **not** a package manager in the same sense as Yum or Apt are. Yes, it deals with "packages" or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. `vendor`) inside your project. By default it does not install anything globally. Thus, it is a dependency manager. It does however support a "global" project for convenience via the [global](03-cli.md#global) command. This idea is not new and Composer is strongly inspired by node's [npm](https://www.npmjs.com/) and ruby's [bundler](https://bundler.io/). Suppose: 1. You have a project that depends on a number of libraries. 1. Some of those libraries depend on other libraries. Composer: 1. Enables you to declare the libraries you depend on. 1. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project). See the [Basic usage](01-basic-usage.md) chapter for more details on declaring dependencies. ## System Requirements Composer requires PHP 5.3.2+ to run. A few sensitive php settings and compile flags are also required, but when using the installer you will be warned about any incompatibilities. To install packages from sources instead of simple zip archives, you will need git, svn, fossil or hg depending on how the package is version-controlled. Composer is multi-platform and we strive to make it run equally well on Windows, Linux and OSX. ## Installation - Linux / Unix / OSX ### Downloading the Composer Executable Composer offers a convenient installer that you can execute directly from the commandline. Feel free to [download this file](https://getcomposer.org/installer) or review it on [GitHub](https://github.com/composer/getcomposer.org/blob/master/web/installer) if you wish to know more about the inner workings of the installer. The source is plain PHP. There are in short, two ways to install Composer. Locally as part of your project, or globally as a system wide executable. #### Locally Installing Composer locally is a matter of just running the installer in your project directory. See [the Download page](https://getcomposer.org/download/) for instructions. The installer will just check a few PHP settings and then download `composer.phar` to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP which can be run on the command line, amongst other things. Now just run `php composer.phar` in order to run Composer. You can install Composer to a specific directory by using the `--install-dir` option and additionally (re)name it as well using the `--filename` option. When running the installer when following [the Download page instructions](https://getcomposer.org/download/) add the following parameters: ```sh php composer-setup.php --install-dir=bin --filename=composer ``` Now just run `php bin/composer` in order to run Composer. #### Globally You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your `PATH`, you can access it globally. On unixy systems you can even make it executable and invoke it without directly using the `php` interpreter. After running the installer following [the Download page instructions](https://getcomposer.org/download/) you can run this to move composer.phar to a directory that is in your path: ```sh mv composer.phar /usr/local/bin/composer ``` > **Note:** If the above fails due to permissions, you may need to run it again > with sudo. > **Note:** On some versions of OSX the `/usr` directory does not exist by > default. If you receive the error "/usr/local/bin/composer: No such file or > directory" then you must create the directory manually before proceeding: > `mkdir -p /usr/local/bin`. > **Note:** For information on changing your PATH, please read the > [Wikipedia article](https://en.wikipedia.org/wiki/PATH_(variable)) and/or use Google. Now just run `composer` in order to run Composer instead of `php composer.phar`. ## Installation - Windows ### Using the Installer This is the easiest way to get Composer set up on your machine. Download and run [Composer-Setup.exe](https://getcomposer.org/Composer-Setup.exe). It will install the latest Composer version and set up your PATH so that you can just call `composer` from any directory in your command line. > **Note:** Close your current terminal. Test usage with a new terminal: This is > important since the PATH only gets loaded when the terminal starts. ### Manual Installation Change to a directory on your `PATH` and run the installer following [the Download page instructions](https://getcomposer.org/download/) to download `composer.phar`. Create a new `composer.bat` file alongside `composer.phar`: ```sh C:\bin>echo @php "%~dp0composer.phar" %*>composer.bat ``` Add the directory to your PATH environment variable if it isn't already. For information on changing your PATH variable, please see [this article](https://www.computerhope.com/issues/ch000549.htm) and/or use Google. Close your current terminal. Test usage with a new terminal: ```sh C:\Users\username>composer -V Composer version 1.0.0 2016-01-10 20:34:53 ``` ## Using Composer Now that you've installed Composer, you are ready to use it! Head on over to the next chapter for a short and simple demonstration. [Basic usage](01-basic-usage.md) → composer-1.6.3/doc/01-basic-usage.md000066400000000000000000000271441323436022200170450ustar00rootroot00000000000000# Basic usage ## Introduction For our basic usage introduction, we will be installing `monolog/monolog`, a logging library. If you have not yet installed Composer, refer to the [Intro](00-intro.md) chapter. > **Note:** for the sake of simplicity, this introduction will assume you > have performed a [local](00-intro.md#locally) install of Composer. ## `composer.json`: Project Setup To start using Composer in your project, all you need is a `composer.json` file. This file describes the dependencies of your project and may contain other metadata as well. ### The `require` Key The first (and often only) thing you specify in `composer.json` is the [`require`](04-schema.md#require) key. You are simply telling Composer which packages your project depends on. ```json { "require": { "monolog/monolog": "1.0.*" } } ``` As you can see, [`require`](04-schema.md#require) takes an object that maps **package names** (e.g. `monolog/monolog`) to **version constraints** (e.g. `1.0.*`). Composer uses this information to search for the right set of files in package "repositories" that you register using the [`repositories`](04-schema.md#repositories) key, or in Packagist, the default package repository. In the above example, since no other repository has been registered in the `composer.json` file, it is assumed that the `monolog/monolog` package is registered on Packagist. (See more about Packagist [below](#packagist), or read more about repositories [here](05-repositories.md)). ### Package Names The package name consists of a vendor name and the project's name. Often these will be identical - the vendor name just exists to prevent naming clashes. For example, it would allow two different people to create a library named `json`. One might be named `igorw/json` while the other might be `seldaek/json`. Read more about publishing packages and package naming [here](02-libraries.md). (Note that you can also specify "platform packages" as dependencies, allowing you to require certain versions of server software. See [platform packages](#platform-packages) below.) ### Package Version Constraints In our example, we are requesting the Monolog package with the version constraint [`1.0.*`](https://semver.mwl.be/#?package=monolog%2Fmonolog&version=1.0.*). This means any version in the `1.0` development branch, or any version that is greater than or equal to 1.0 and less than 1.1 (`>=1.0 <1.1`). Please read [versions](articles/versions.md) for more in-depth information on versions, how versions relate to each other, and on version constraints. > **How does Composer download the right files?** When you specify a dependency in > `composer.json`, Composer first takes the name of the package that you have requested > and searches for it in any repositories that you have registered using the > [`repositories`](04-schema.md#repositories) key. If you have not registered > any extra repositories, or it does not find a package with that name in the > repositories you have specified, it falls back to Packagist (more [below](#packagist)). > > When Composer finds the right package, either in Packagist or in a repo you have specified, > it then uses the versioning features of the package's VCS (i.e., branches and tags) > to attempt to find the best match for the version constraint you have specified. Be sure to read > about versions and package resolution in the [versions article](articles/versions.md). > **Note:** If you are trying to require a package but Composer throws an error > regarding package stability, the version you have specified may not meet your > default minimum stability requirements. By default only stable releases are taken > into consideration when searching for valid package versions in your VCS. > > You might run into this if you are trying to require dev, alpha, beta, or RC > versions of a package. Read more about stability flags and the `minimum-stability` > key on the [schema page](04-schema.md). ## Installing Dependencies To install the defined dependencies for your project, just run the [`install`](03-cli.md#install) command. ```sh php composer.phar install ``` When you run this command, one of two things may happen: ### Installing Without `composer.lock` If you have never run the command before and there is also no `composer.lock` file present, Composer simply resolves all dependencies listed in your `composer.json` file and downloads the latest version of their files into the `vendor` directory in your project. (The `vendor` directory is the conventional location for all third-party code in a project). In our example from above, you would end up with the Monolog source files in `vendor/monolog/monolog/`. If Monolog listed any dependencies, those would also be in folders under `vendor/`. > **Tip:** If you are using git for your project, you probably want to add > `vendor` in your `.gitignore`. You really don't want to add all of that > third-party code to your versioned repository. When Composer has finished installing, it writes all of the packages and the exact versions of them that it downloaded to the `composer.lock` file, locking the project to those specific versions. You should commit the `composer.lock` file to your project repo so that all people working on the project are locked to the same versions of dependencies (more below). ### Installing With `composer.lock` This brings us to the second scenario. If there is already a `composer.lock` file as well as a `composer.json` file when you run `composer install`, it means either you ran the `install` command before, or someone else on the project ran the `install` command and committed the `composer.lock` file to the project (which is good). Either way, running `install` when a `composer.lock` file is present resolves and installs all dependencies that you listed in `composer.json`, but Composer uses the exact versions listed in `composer.lock` to ensure that the package versions are consistent for everyone working on your project. As a result you will have all dependencies requested by your `composer.json` file, but they may not all be at the very latest available versions (some of the dependencies listed in the `composer.lock` file may have released newer versions since the file was created). This is by design, it ensures that your project does not break because of unexpected changes in dependencies. ### Commit Your `composer.lock` File to Version Control Committing this file to VC is important because it will cause anyone who sets up the project to use the exact same versions of the dependencies that you are using. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then. (See note below about using the `update` command.) ## Updating Dependencies to their Latest Versions As mentioned above, the `composer.lock` file prevents you from automatically getting the latest versions of your dependencies. To update to the latest versions, use the [`update`](03-cli.md#update) command. This will fetch the latest matching versions (according to your `composer.json` file) and update the lock file with the new versions. (This is equivalent to deleting the `composer.lock` file and running `install` again.) ```sh php composer.phar update ``` > **Note:** Composer will display a Warning when executing an `install` command > if `composer.lock` and `composer.json` are not synchronized. If you only want to install or update one dependency, you can whitelist them: ```sh php composer.phar update monolog/monolog [...] ``` > **Note:** For libraries it is not necessary to commit the lock > file, see also: [Libraries - Lock file](02-libraries.md#lock-file). ## Packagist [Packagist](https://packagist.org/) is the main Composer repository. A Composer repository is basically a package source: a place where you can get packages from. Packagist aims to be the central repository that everybody uses. This means that you can automatically `require` any package that is available there, without further specifying where Composer should look for the package. If you go to the [Packagist website](https://packagist.org/) (packagist.org), you can browse and search for packages. Any open source project using Composer is recommended to publish their packages on Packagist. A library does not need to be on Packagist to be used by Composer, but it enables discovery and adoption by other developers more quickly. ## Platform packages Composer has platform packages, which are virtual packages for things that are installed on the system but are not actually installable by Composer. This includes PHP itself, PHP extensions and some system libraries. * `php` represents the PHP version of the user, allowing you to apply constraints, e.g. `>=5.4.0`. To require a 64bit version of php, you can require the `php-64bit` package. * `hhvm` represents the version of the HHVM runtime and allows you to apply a constraint, e.g., `>=2.3.3`. * `ext-` allows you to require PHP extensions (includes core extensions). Versioning can be quite inconsistent here, so it's often a good idea to just set the constraint to `*`. An example of an extension package name is `ext-gd`. * `lib-` allows constraints to be made on versions of libraries used by PHP. The following are available: `curl`, `iconv`, `icu`, `libxml`, `openssl`, `pcre`, `uuid`, `xsl`. You can use [`show --platform`](03-cli.md#show) to get a list of your locally available platform packages. ## Autoloading For libraries that specify autoload information, Composer generates a `vendor/autoload.php` file. You can simply include this file and start using the classes that those libraries provide without any extra work: ```php require __DIR__ . '/vendor/autoload.php'; $log = new Monolog\Logger('name'); $log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING)); $log->addWarning('Foo'); ``` You can even add your own code to the autoloader by adding an [`autoload`](04-schema.md#autoload) field to `composer.json`. ```json { "autoload": { "psr-4": {"Acme\\": "src/"} } } ``` Composer will register a [PSR-4](http://www.php-fig.org/psr/psr-4/) autoloader for the `Acme` namespace. You define a mapping from namespaces to directories. The `src` directory would be in your project root, on the same level as `vendor` directory is. An example filename would be `src/Foo.php` containing an `Acme\Foo` class. After adding the [`autoload`](04-schema.md#autoload) field, you have to re-run [`dump-autoload`](03-cli.md#dump-autoload) to re-generate the `vendor/autoload.php` file. Including that file will also return the autoloader instance, so you can store the return value of the include call in a variable and add more namespaces. This can be useful for autoloading classes in a test suite, for example. ```php $loader = require __DIR__ . '/vendor/autoload.php'; $loader->addPsr4('Acme\\Test\\', __DIR__); ``` In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap and files autoloading. See the [`autoload`](04-schema.md#autoload) reference for more information. See also the docs on [optimizing the autoloader](articles/autoloader-optimization.md). > **Note:** Composer provides its own autoloader. If you don't want to use that > one, you can just include `vendor/composer/autoload_*.php` files, which return > associative arrays allowing you to configure your own autoloader. ← [Intro](00-intro.md) | [Libraries](02-libraries.md) → composer-1.6.3/doc/02-libraries.md000066400000000000000000000130701323436022200166300ustar00rootroot00000000000000# Libraries This chapter will tell you how to make your library installable through Composer. ## Every project is a package As soon as you have a `composer.json` in a directory, that directory is a package. When you add a [`require`](04-schema.md#require) to a project, you are making a package that depends on other packages. The only difference between your project and a library is that your project is a package without a name. In order to make that package installable you need to give it a name. You do this by adding the [`name`](04-schema.md#name) property in `composer.json`: ```json { "name": "acme/hello-world", "require": { "monolog/monolog": "1.0.*" } } ``` In this case the project name is `acme/hello-world`, where `acme` is the vendor name. Supplying a vendor name is mandatory. > **Note:** If you don't know what to use as a vendor name, your GitHub > username is usually a good bet. While package names are case insensitive, the > convention is all lowercase and dashes for word separation. ## Library Versioning In the vast majority of cases, you will be maintaining your library using some sort of version control system like git, svn, hg or fossil. In these cases, Composer infers versions from your VCS and you **should not** specify a version in your `composer.json` file. (See the [Versions article](articles/versions.md) to learn about how Composer uses VCS branches and tags to resolve version constraints.) If you are maintaining packages by hand (i.e., without a VCS), you'll need to specify the version explicitly by adding a `version` value in your `composer.json` file: ```json { "version": "1.0.0" } ``` > **Note:** When you add a hardcoded version to a VCS, the version will conflict > with tag names. Composer will not be able to determine the version number. ### VCS Versioning Composer uses your VCS's branch and tag features to resolve the version constraints you specify in your `require` field to specific sets of files. When determining valid available versions, Composer looks at all of your tags and branches and translates their names into an internal list of options that it then matches against the version constraint you provided. For more on how Composer treats tags and branches and how it resolves package version constraints, read the [versions](articles/versions.md) article. ## Lock file For your library you may commit the `composer.lock` file if you want to. This can help your team to always test against the same dependency versions. However, this lock file will not have any effect on other projects that depend on it. It only has an effect on the main project. If you do not want to commit the lock file and you are using git, add it to the `.gitignore`. ## Publishing to a VCS Once you have a VCS repository (version control system, e.g. git) containing a `composer.json` file, your library is already composer-installable. In this example we will publish the `acme/hello-world` library on GitHub under `github.com/username/hello-world`. Now, to test installing the `acme/hello-world` package, we create a new project locally. We will call it `acme/blog`. This blog will depend on `acme/hello-world`, which in turn depends on `monolog/monolog`. We can accomplish this by creating a new `blog` directory somewhere, containing a `composer.json`: ```json { "name": "acme/blog", "require": { "acme/hello-world": "dev-master" } } ``` The name is not needed in this case, since we don't want to publish the blog as a library. It is added here to clarify which `composer.json` is being described. Now we need to tell the blog app where to find the `hello-world` dependency. We do this by adding a package repository specification to the blog's `composer.json`: ```json { "name": "acme/blog", "repositories": [ { "type": "vcs", "url": "https://github.com/username/hello-world" } ], "require": { "acme/hello-world": "dev-master" } } ``` For more details on how package repositories work and what other types are available, see [Repositories](05-repositories.md). That's all. You can now install the dependencies by running Composer's [`install`](03-cli.md#install) command! **Recap:** Any git/svn/hg/fossil repository containing a `composer.json` can be added to your project by specifying the package repository and declaring the dependency in the [`require`](04-schema.md#require) field. ## Publishing to packagist Alright, so now you can publish packages. But specifying the VCS repository every time is cumbersome. You don't want to force all your users to do that. The other thing that you may have noticed is that we did not specify a package repository for `monolog/monolog`. How did that work? The answer is Packagist. [Packagist](https://packagist.org/) is the main package repository for Composer, and it is enabled by default. Anything that is published on Packagist is available automatically through Composer. Since [Monolog is on Packagist](https://packagist.org/packages/monolog/monolog), we can depend on it without having to specify any additional repositories. If we wanted to share `hello-world` with the world, we would publish it on Packagist as well. Doing so is really easy. You simply visit [Packagist](https://packagist.org) and hit the "Submit" button. This will prompt you to sign up if you haven't already, and then allows you to submit the URL to your VCS repository, at which point Packagist will start crawling it. Once it is done, your package will be available to anyone! ← [Basic usage](01-basic-usage.md) | [Command-line interface](03-cli.md) → composer-1.6.3/doc/03-cli.md000066400000000000000000001063741323436022200154360ustar00rootroot00000000000000# Command-line interface / Commands You've already learned how to use the command-line interface to do some things. This chapter documents all the available commands. To get help from the command-line, simply call `composer` or `composer list` to see the complete list of commands, then `--help` combined with any of those can give you more information. As Composer uses [symfony/console](https://github.com/symfony/console) you can call commands by short name if it's not ambiguous. ```sh composer dump ``` calls `composer dump-autoload`. ## Global Options The following options are available with every command: * **--verbose (-v):** Increase verbosity of messages. * **--help (-h):** Display help information. * **--quiet (-q):** Do not output any message. * **--no-interaction (-n):** Do not ask any interactive question. * **--no-plugins:** Disables plugins. * **--working-dir (-d):** If specified, use the given directory as working directory. * **--profile:** Display timing and memory usage information * **--ansi:** Force ANSI output. * **--no-ansi:** Disable ANSI output. * **--version (-V):** Display this application version. ## Process Exit Codes * **0:** OK * **1:** Generic/unknown error code * **2:** Dependency solving error code ## init In the [Libraries](02-libraries.md) chapter we looked at how to create a `composer.json` by hand. There is also an `init` command available that makes it a bit easier to do this. When you run the command it will interactively ask you to fill in the fields, while using some smart defaults. ```sh php composer.phar init ``` ### Options * **--name:** Name of the package. * **--description:** Description of the package. * **--author:** Author name of the package. * **--type:** Type of package. * **--homepage:** Homepage of the package. * **--require:** Package to require with a version constraint. Should be in format `foo/bar:1.0.0`. * **--require-dev:** Development requirements, see **--require**. * **--stability (-s):** Value for the `minimum-stability` field. * **--license (-l):** License of package. * **--repository:** Provide one (or more) custom repositories. They will be stored in the generated composer.json, and used for auto-completion when prompting for the list of requires. Every repository can be either an HTTP URL pointing to a `composer` repository or a JSON string which similar to what the [repositories](04-schema.md#repositories) key accepts. ## install The `install` command reads the `composer.json` file from the current directory, resolves the dependencies, and installs them into `vendor`. ```sh php composer.phar install ``` If there is a `composer.lock` file in the current directory, it will use the exact versions from there instead of resolving them. This ensures that everyone using the library will get the same versions of the dependencies. If there is no `composer.lock` file, Composer will create one after dependency resolution. ### Options * **--prefer-source:** There are two ways of downloading a package: `source` and `dist`. For stable versions Composer will use the `dist` by default. The `source` is a version control repository. If `--prefer-source` is enabled, Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. * **--prefer-dist:** Reverse of `--prefer-source`, Composer will install from `dist` if possible. This can speed up installs substantially on build servers and other use cases where you typically do not run updates of the vendors. It is also a way to circumvent problems with git if you do not have a proper setup. * **--dry-run:** If you want to run through an installation without actually installing a package, you can use `--dry-run`. This will simulate the installation and show you what would happen. * **--dev:** Install packages listed in `require-dev` (this is the default behavior). * **--no-dev:** Skip installing packages listed in `require-dev`. The autoloader generation skips the `autoload-dev` rules. * **--no-autoloader:** Skips autoloader generation. * **--no-scripts:** Skips execution of scripts defined in `composer.json`. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-suggest:** Skips suggested packages in the output. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--ignore-platform-reqs:** ignore `php`, `hhvm`, `lib-*` and `ext-*` requirements and force the installation even if the local machine does not fulfill these. See also the [`platform`](06-config.md#platform) config option. ## update In order to get the latest versions of the dependencies and to update the `composer.lock` file, you should use the `update` command. This command is also aliased as `upgrade` as it does the same as `upgrade` does if you are thinking of `apt-get` or similar package managers. ```sh php composer.phar update ``` This will resolve all dependencies of the project and write the exact versions into `composer.lock`. If you just want to update a few packages and not all, you can list them as such: ```sh php composer.phar update vendor/package vendor/package2 ``` You can also use wildcards to update a bunch of packages at once: ```sh php composer.phar update vendor/* ``` ### Options * **--prefer-source:** Install packages from `source` when available. * **--prefer-dist:** Install packages from `dist` when available. * **--dry-run:** Simulate the command without actually doing anything. * **--dev:** Install packages listed in `require-dev` (this is the default behavior). * **--no-dev:** Skip installing packages listed in `require-dev`. The autoloader generation skips the `autoload-dev` rules. * **--lock:** Only updates the lock file hash to suppress warning about the lock file being out of date. * **--no-autoloader:** Skips autoloader generation. * **--no-scripts:** Skips execution of scripts defined in `composer.json`. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-suggest:** Skips suggested packages in the output. * **--with-dependencies:** Add also dependencies of whitelisted packages to the whitelist, except those that are root requirements. * **--with-all-dependencies:** Add also all dependencies of whitelisted packages to the whitelist, including those that are root requirements. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--ignore-platform-reqs:** ignore `php`, `hhvm`, `lib-*` and `ext-*` requirements and force the installation even if the local machine does not fulfill these. See also the [`platform`](06-config.md#platform) config option. * **--prefer-stable:** Prefer stable versions of dependencies. * **--prefer-lowest:** Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with `--prefer-stable`. * **--interactive:** Interactive interface with autocompletion to select the packages to update. * **--root-reqs:** Restricts the update to your first degree dependencies. ## require The `require` command adds new packages to the `composer.json` file from the current directory. If no file exists one will be created on the fly. ```sh php composer.phar require ``` After adding/changing the requirements, the modified requirements will be installed or updated. If you do not want to choose requirements interactively, you can just pass them to the command. ```sh php composer.phar require vendor/package:2.* vendor/package2:dev-master ``` If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of matches to require. ### Options * **--dev:** Add packages to `require-dev`. * **--prefer-source:** Install packages from `source` when available. * **--prefer-dist:** Install packages from `dist` when available. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-suggest:** Skips suggested packages in the output. * **--no-update:** Disables the automatic update of the dependencies. * **--no-scripts:** Skips execution of scripts defined in `composer.json`. * **--update-no-dev:** Run the dependency update with the `--no-dev` option. * **--update-with-dependencies:** Also update dependencies of the newly required packages, except those that are root requirements. * **--update-with-all-dependencies:** Also update dependencies of the newly required packages, including those that are root requirements. * **--ignore-platform-reqs:** ignore `php`, `hhvm`, `lib-*` and `ext-*` requirements and force the installation even if the local machine does not fulfill these. See also the [`platform`](06-config.md#platform) config option. * **--prefer-stable:** Prefer stable versions of dependencies. * **--prefer-lowest:** Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with `--prefer-stable`. * **--sort-packages:** Keep packages sorted in `composer.json`. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. ## remove The `remove` command removes packages from the `composer.json` file from the current directory. ```sh php composer.phar remove vendor/package vendor/package2 ``` After removing the requirements, the modified requirements will be uninstalled. ### Options * **--dev:** Remove packages from `require-dev`. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-update:** Disables the automatic update of the dependencies. * **--no-scripts:** Skips execution of scripts defined in `composer.json`. * **--update-no-dev:** Run the dependency update with the --no-dev option. * **--update-with-dependencies:** Also update dependencies of the removed packages. * **--ignore-platform-reqs:** ignore `php`, `hhvm`, `lib-*` and `ext-*` requirements and force the installation even if the local machine does not fulfill these. See also the [`platform`](06-config.md#platform) config option. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. ## check-platform-reqs The check-platform-reqs command checks that your PHP and extensions versions match the platform requirements of the installed packages. This can be used to verify that a production server has all the extensions needed to run a project after installing it for example. ## global The global command allows you to run other commands like `install`, `remove`, `require` or `update` as if you were running them from the [COMPOSER_HOME](#composer-home) directory. This is merely a helper to manage a project stored in a central location that can hold CLI tools or Composer plugins that you want to have available everywhere. This can be used to install CLI utilities globally. Here is an example: ```sh php composer.phar global require friendsofphp/php-cs-fixer ``` Now the `php-cs-fixer` binary is available globally. Just make sure your global [vendor binaries](articles/vendor-binaries.md) directory is in your `$PATH` environment variable, you can get its location with the following command : ```sh php composer.phar global config bin-dir --absolute ``` If you wish to update the binary later on you can just run a global update: ```sh php composer.phar global update ``` ## search The search command allows you to search through the current project's package repositories. Usually this will be just packagist. You simply pass it the terms you want to search for. ```sh php composer.phar search monolog ``` You can also search for more than one term by passing multiple arguments. ### Options * **--only-name (-N):** Search only in name. * **--type (-t):** Search for a specific package type. ## show To list all of the available packages, you can use the `show` command. ```sh php composer.phar show ``` To filter the list you can pass a package mask using wildcards. ```sh php composer.phar show monolog/* monolog/monolog 1.19.0 Sends your logs to files, sockets, inboxes, databases and various web services ``` If you want to see the details of a certain package, you can pass the package name. ```sh php composer.phar show monolog/monolog name : monolog/monolog versions : master-dev, 1.0.2, 1.0.1, 1.0.0, 1.0.0-RC1 type : library names : monolog/monolog source : [git] https://github.com/Seldaek/monolog.git 3d4e60d0cbc4b888fe5ad223d77964428b1978da dist : [zip] https://github.com/Seldaek/monolog/zipball/3d4e60d0cbc4b888fe5ad223d77964428b1978da 3d4e60d0cbc4b888fe5ad223d77964428b1978da license : MIT autoload psr-0 Monolog : src/ requires php >=5.3.0 ``` You can even pass the package version, which will tell you the details of that specific version. ```sh php composer.phar show monolog/monolog 1.0.2 ``` ### Options * **--all :** List all packages available in all your repositories. * **--installed (-i):** List the packages that are installed (this is enabled by default, and deprecated). * **--platform (-p):** List only platform packages (php & extensions). * **--available (-a):** List available packages only. * **--self (-s):** List the root package info. * **--name-only (-N):** List package names only. * **--path (-P):** List package paths. * **--tree (-t):** List your dependencies as a tree. If you pass a package name it will show the dependency tree for that package. * **--latest (-l):** List all installed packages including their latest version. * **--outdated (-o):** Implies --latest, but this lists *only* packages that have a newer version available. * **--minor-only (-m):** Use with --latest. Only shows packages that have minor SemVer-compatible updates. * **--direct (-D):** Restricts the list of packages to your direct dependencies. * **--strict:** Return a non-zero exit code when there are outdated packages. * **--format (-f):** Lets you pick between text (default) or json output format. ## outdated The `outdated` command shows a list of installed packages that have updates available, including their current and latest versions. This is basically an alias for `composer show -lo`. The color coding is as such: - **green (=)**: Dependency is in the latest version and is up to date. - **yellow (~)**: Dependency has a new version available that includes backwards compatibility breaks according to semver, so upgrade when you can but it may involve work. - **red (!)**: Dependency has a new version that is semver-compatible and you should upgrade it. ### Options * **--all (-a):** Show all packages, not just outdated (alias for `composer show -l`). * **--direct (-D):** Restricts the list of packages to your direct dependencies. * **--strict:** Returns non-zero exit code if any package is outdated. * **--minor-only (-m):** Only shows packages that have minor SemVer-compatible updates. * **--format (-f):** Lets you pick between text (default) or json output format. ## browse / home The `browse` (aliased to `home`) opens a package's repository URL or homepage in your browser. ### Options * **--homepage (-H):** Open the homepage instead of the repository URL. * **--show (-s):** Only show the homepage or repository URL. ## suggests Lists all packages suggested by currently installed set of packages. You can optionally pass one or multiple package names in the format of `vendor/package` to limit output to suggestions made by those packages only. Use the `--by-package` or `--by-suggestion` flags to group the output by the package offering the suggestions or the suggested packages respectively. Use the `--verbose (-v)` flag to display the suggesting package and the suggestion reason. This implies `--by-package --by-suggestion`, showing both lists. ### Options * **--by-package:** Groups output by suggesting package. * **--by-suggestion:** Groups output by suggested package. * **--no-dev:** Excludes suggestions from `require-dev` packages. ## depends (why) The `depends` command tells you which other packages depend on a certain package. As with installation `require-dev` relationships are only considered for the root package. ```sh php composer.phar depends doctrine/lexer doctrine/annotations v1.2.7 requires doctrine/lexer (1.*) doctrine/common v2.6.1 requires doctrine/lexer (1.*) ``` You can optionally specify a version constraint after the package to limit the search. Add the `--tree` or `-t` flag to show a recursive tree of why the package is depended upon, for example: ```sh php composer.phar depends psr/log -t psr/log 1.0.0 Common interface for logging libraries |- aboutyou/app-sdk 2.6.11 (requires psr/log 1.0.*) | `- __root__ (requires aboutyou/app-sdk ^2.6) |- monolog/monolog 1.17.2 (requires psr/log ~1.0) | `- laravel/framework v5.2.16 (requires monolog/monolog ~1.11) | `- __root__ (requires laravel/framework ^5.2) `- symfony/symfony v3.0.2 (requires psr/log ~1.0) `- __root__ (requires symfony/symfony ^3.0) ``` ### Options * **--recursive (-r):** Recursively resolves up to the root package. * **--tree (-t):** Prints the results as a nested tree, implies -r. ## prohibits (why-not) The `prohibits` command tells you which packages are blocking a given package from being installed. Specify a version constraint to verify whether upgrades can be performed in your project, and if not why not. See the following example: ```sh php composer.phar prohibits symfony/symfony 3.1 laravel/framework v5.2.16 requires symfony/var-dumper (2.8.*|3.0.*) ``` Note that you can also specify platform requirements, for example to check whether you can upgrade your server to PHP 8.0: ```sh php composer.phar prohibits php:8 doctrine/cache v1.6.0 requires php (~5.5|~7.0) doctrine/common v2.6.1 requires php (~5.5|~7.0) doctrine/instantiator 1.0.5 requires php (>=5.3,<8.0-DEV) ``` As with `depends` you can request a recursive lookup, which will list all packages depending on the packages that cause the conflict. ### Options * **--recursive (-r):** Recursively resolves up to the root package. * **--tree (-t):** Prints the results as a nested tree, implies -r. ## validate You should always run the `validate` command before you commit your `composer.json` file, and before you tag a release. It will check if your `composer.json` is valid. ```sh php composer.phar validate ``` ### Options * **--no-check-all:** Do not emit a warning if requirements in `composer.json` use unbound version constraints. * **--no-check-lock:** Do not emit an error if `composer.lock` exists and is not up to date. * **--no-check-publish:** Do not emit an error if `composer.json` is unsuitable for publishing as a package on Packagist but is otherwise valid. * **--with-dependencies:** Also validate the composer.json of all installed dependencies. * **--strict:** Return a non-zero exit code for warnings as well as errors. ## status If you often need to modify the code of your dependencies and they are installed from source, the `status` command allows you to check if you have local changes in any of them. ```sh php composer.phar status ``` With the `--verbose` option you get some more information about what was changed: ```sh php composer.phar status -v You have changes in the following dependencies: vendor/seld/jsonlint: M README.mdown ``` ## self-update (selfupdate) To update Composer itself to the latest version, just run the `self-update` command. It will replace your `composer.phar` with the latest version. ```sh php composer.phar self-update ``` If you would like to instead update to a specific release simply specify it: ```sh php composer.phar self-update 1.0.0-alpha7 ``` If you have installed Composer for your entire system (see [global installation](00-intro.md#globally)), you may have to run the command with `root` privileges ```sh sudo -H composer self-update ``` ### Options * **--rollback (-r):** Rollback to the last version you had installed. * **--clean-backups:** Delete old backups during an update. This makes the current version of Composer the only backup available after the update. * **--no-progress:** Do not output download progress. * **--update-keys:** Prompt user for a key update. * **--stable:** Force an update to the stable channel. * **--preview:** Force an update to the preview channel. * **--snapshot:** Force an update to the snapshot channel. ## config The `config` command allows you to edit composer config settings and repositories in either the local `composer.json` file or the global `config.json` file. Additionally it lets you edit most properties in the local `composer.json`. ```sh php composer.phar config --list ``` ### Usage `config [options] [setting-key] [setting-value1] ... [setting-valueN]` `setting-key` is a configuration option name and `setting-value1` is a configuration value. For settings that can take an array of values (like `github-protocols`), more than one setting-value arguments are allowed. You can also edit the values of the following properties: `description`, `homepage`, `keywords`, `license`, `minimum-stability`, `name`, `prefer-stable`, `type` and `version`. See the [Config](06-config.md) chapter for valid configuration options. ### Options * **--global (-g):** Operate on the global config file located at `$COMPOSER_HOME/config.json` by default. Without this option, this command affects the local composer.json file or a file specified by `--file`. * **--editor (-e):** Open the local composer.json file using in a text editor as defined by the `EDITOR` env variable. With the `--global` option, this opens the global config file. * **--auth (-a):** Affect auth config file (only used for --editor). * **--unset:** Remove the configuration element named by `setting-key`. * **--list (-l):** Show the list of current config variables. With the `--global` option this lists the global configuration only. * **--file="..." (-f):** Operate on a specific file instead of composer.json. Note that this cannot be used in conjunction with the `--global` option. * **--absolute:** Returns absolute paths when fetching *-dir config values instead of relative. ### Modifying Repositories In addition to modifying the config section, the `config` command also supports making changes to the repositories section by using it the following way: ```sh php composer.phar config repositories.foo vcs https://github.com/foo/bar ``` If your repository requires more configuration options, you can instead pass its JSON representation : ```sh php composer.phar config repositories.foo '{"type": "vcs", "url": "http://svn.example.org/my-project/", "trunk-path": "master"}' ``` ### Modifying Extra Values In addition to modifying the config section, the `config` command also supports making changes to the extra section by using it the following way: ```sh php composer.phar config extra.foo.bar value ``` The dots indicate array nesting, a max depth of 3 levels is allowed though. The above would set `"extra": { "foo": { "bar": "value" } }`. ## create-project You can use Composer to create new projects from an existing package. This is the equivalent of doing a git clone/svn checkout followed by a `composer install` of the vendors. There are several applications for this: 1. You can deploy application packages. 2. You can check out any package and start developing on patches for example. 3. Projects with multiple developers can use this feature to bootstrap the initial application for development. To create a new project using Composer you can use the `create-project` command. Pass it a package name, and the directory to create the project in. You can also provide a version as third argument, otherwise the latest version is used. If the directory does not currently exist, it will be created during installation. ```sh php composer.phar create-project doctrine/orm path 2.2.* ``` It is also possible to run the command without params in a directory with an existing `composer.json` file to bootstrap a project. By default the command checks for the packages on packagist.org. ### Options * **--stability (-s):** Minimum stability of package. Defaults to `stable`. * **--prefer-source:** Install packages from `source` when available. * **--prefer-dist:** Install packages from `dist` when available. * **--repository:** Provide a custom repository to search for the package, which will be used instead of packagist. Can be either an HTTP URL pointing to a `composer` repository, a path to a local `packages.json` file, or a JSON string which similar to what the [repositories](04-schema.md#repositories) key accepts. * **--dev:** Install packages listed in `require-dev`. * **--no-dev:** Disables installation of require-dev packages. * **--no-scripts:** Disables the execution of the scripts defined in the root package. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--keep-vcs:** Skip the deletion of the VCS metadata for the created project. This is mostly useful if you run the command in non-interactive mode. * **--remove-vcs:** Force-remove the VCS metadata without prompting. * **--no-install:** Disables installation of the vendors. * **--ignore-platform-reqs:** ignore `php`, `hhvm`, `lib-*` and `ext-*` requirements and force the installation even if the local machine does not fulfill these. ## dump-autoload (dumpautoload) If you need to update the autoloader because of new classes in a classmap package for example, you can use `dump-autoload` to do that without having to go through an install or update. Additionally, it can dump an optimized autoloader that converts PSR-0/4 packages into classmap ones for performance reasons. In large applications with many classes, the autoloader can take up a substantial portion of every request's time. Using classmaps for everything is less convenient in development, but using this option you can still use PSR-0/4 for convenience and classmaps for performance. ### Options * **--no-scripts:** Skips the execution of all scripts defined in `composer.json` file. * **--optimize (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize`. * **--apcu:** Use APCu to cache found/not-found classes. * **--no-dev:** Disables autoload-dev rules. ## clear-cache (clearcache) Deletes all content from Composer's cache directories. ## licenses Lists the name, version and license of every package installed. Use `--format=json` to get machine readable output. ### Options * **--format:** Format of the output: text or json (default: "text") * **--no-dev:** Remove dev dependencies from the output ## run-script ### Options * **--timeout:** Set the script timeout in seconds, or 0 for no timeout. * **--dev:** Sets the dev mode. * **--no-dev:** Disable dev mode. * **--list (-l):** List user defined scripts. To run [scripts](articles/scripts.md) manually you can use this command, just give it the script name and optionally any required arguments. ## exec Executes a vendored binary/script. You can execute any command and this will ensure that the Composer bin-dir is pushed on your PATH before the command runs. ### Options * **--list (-l):** List the available composer binaries. ## diagnose If you think you found a bug, or something is behaving strangely, you might want to run the `diagnose` command to perform automated checks for many common problems. ```sh php composer.phar diagnose ``` ## archive This command is used to generate a zip/tar archive for a given package in a given version. It can also be used to archive your entire project without excluded/ignored files. ```sh php composer.phar archive vendor/package 2.0.21 --format=zip ``` ### Options * **--format (-f):** Format of the resulting archive: tar or zip (default: "tar") * **--dir:** Write the archive to this directory (default: ".") * **--file:** Write the archive with the given file name. ## help To get more information about a certain command, just use `help`. ```sh php composer.phar help install ``` ## Command-line completion Command-line completion can be enabled by following instructions [on this page](https://github.com/bamarni/symfony-console-autocomplete). ## Environment variables You can set a number of environment variables that override certain settings. Whenever possible it is recommended to specify these settings in the `config` section of `composer.json` instead. It is worth noting that the env vars will always take precedence over the values specified in `composer.json`. ### COMPOSER By setting the `COMPOSER` env variable it is possible to set the filename of `composer.json` to something else. For example: ```sh COMPOSER=composer-other.json php composer.phar install ``` The generated lock file will use the same name: `composer-other.lock` in this example. ### COMPOSER_ROOT_VERSION By setting this var you can specify the version of the root package, if it can not be guessed from VCS info and is not present in `composer.json`. ### COMPOSER_VENDOR_DIR By setting this var you can make Composer install the dependencies into a directory other than `vendor`. ### COMPOSER_BIN_DIR By setting this option you can change the `bin` ([Vendor Binaries](articles/vendor-binaries.md)) directory to something other than `vendor/bin`. ### http_proxy or HTTP_PROXY If you are using Composer from behind an HTTP proxy, you can use the standard `http_proxy` or `HTTP_PROXY` env vars. Simply set it to the URL of your proxy. Many operating systems already set this variable for you. Using `http_proxy` (lowercased) or even defining both might be preferable since some tools like git or curl will only use the lower-cased `http_proxy` version. Alternatively you can also define the git proxy using `git config --global http.proxy `. If you are using Composer in a non-CLI context (i.e. integration into a CMS or similar use case), and need to support proxies, please provide the `CGI_HTTP_PROXY` environment variable instead. See [httpoxy.org](https://httpoxy.org/) for further details. ### no_proxy or NO_PROXY If you are behind a proxy and would like to disable it for certain domains, you can use the `no_proxy` or `NO_PROXY` env var. Simply set it to a comma separated list of domains the proxy should *not* be used for. The env var accepts domains, IP addresses, and IP address blocks in CIDR notation. You can restrict the filter to a particular port (e.g. `:80`). You can also set it to `*` to ignore the proxy for all HTTP requests. ### HTTP_PROXY_REQUEST_FULLURI If you use a proxy but it does not support the request_fulluri flag, then you should set this env var to `false` or `0` to prevent Composer from setting the request_fulluri option. ### HTTPS_PROXY_REQUEST_FULLURI If you use a proxy but it does not support the request_fulluri flag for HTTPS requests, then you should set this env var to `false` or `0` to prevent Composer from setting the request_fulluri option. ### COMPOSER_HOME The `COMPOSER_HOME` var allows you to change the Composer home directory. This is a hidden, global (per-user on the machine) directory that is shared between all projects. By default it points to `C:\Users\\AppData\Roaming\Composer` on Windows and `/Users//.composer` on OSX. On *nix systems that follow the [XDG Base Directory Specifications](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html), it points to `$XDG_CONFIG_HOME/composer`. On other *nix systems, it points to `/home//.composer`. #### COMPOSER_HOME/config.json You may put a `config.json` file into the location which `COMPOSER_HOME` points to. Composer will merge this configuration with your project's `composer.json` when you run the `install` and `update` commands. This file allows you to set [repositories](05-repositories.md) and [configuration](06-config.md) for the user's projects. In case global configuration matches _local_ configuration, the _local_ configuration in the project's `composer.json` always wins. ### COMPOSER_CACHE_DIR The `COMPOSER_CACHE_DIR` var allows you to change the Composer cache directory, which is also configurable via the [`cache-dir`](06-config.md#cache-dir) option. By default it points to `$COMPOSER_HOME/cache` on \*nix and OSX, and `C:\Users\\AppData\Local\Composer` (or `%LOCALAPPDATA%/Composer`) on Windows. ### COMPOSER_PROCESS_TIMEOUT This env var controls the time Composer waits for commands (such as git commands) to finish executing. The default value is 300 seconds (5 minutes). ### COMPOSER_CAFILE By setting this environmental value, you can set a path to a certificate bundle file to be used during SSL/TLS peer verification. ### COMPOSER_AUTH The `COMPOSER_AUTH` var allows you to set up authentication as an environment variable. The contents of the variable should be a JSON formatted object containing http-basic, github-oauth, bitbucket-oauth, ... objects as needed, and following the [spec from the config](06-config.md#gitlab-oauth). ### COMPOSER_DISCARD_CHANGES This env var controls the [`discard-changes`](06-config.md#discard-changes) config option. ### COMPOSER_NO_INTERACTION If set to 1, this env var will make Composer behave as if you passed the `--no-interaction` flag to every command. This can be set on build boxes/CI. ### COMPOSER_ALLOW_SUPERUSER If set to 1, this env disables the warning about running commands as root/super user. It also disables automatic clearing of sudo sessions, so you should really only set this if you use Composer as super user at all times like in docker containers. ### COMPOSER_MEMORY_LIMIT If set, the value is used as php's memory_limit. ### COMPOSER_MIRROR_PATH_REPOS If set to 1, this env changes the default path repository strategy to `mirror` instead of `symlink`. As it is the default strategy being set it can still be overwritten by repository options. ### COMPOSER_HTACCESS_PROTECT Defaults to `1`. If set to `0`, Composer will not create `.htaccess` files in the composer home, cache, and data directories. ← [Libraries](02-libraries.md) | [Schema](04-schema.md) → composer-1.6.3/doc/04-schema.md000066400000000000000000000656271323436022200161350ustar00rootroot00000000000000# The composer.json Schema This chapter will explain all of the fields available in `composer.json`. ## JSON schema We have a [JSON schema](http://json-schema.org) that documents the format and can also be used to validate your `composer.json`. In fact, it is used by the `validate` command. You can find it at: https://getcomposer.org/schema.json ## Root Package The root package is the package defined by the `composer.json` at the root of your project. It is the main `composer.json` that defines your project requirements. Certain fields only apply when in the root package context. One example of this is the `config` field. Only the root package can define configuration. The config of dependencies is ignored. This makes the `config` field `root-only`. > **Note:** A package can be the root package or not, depending on the context. > For example, if your project depends on the `monolog` library, your project > is the root package. However, if you clone `monolog` from GitHub in order to > fix a bug in it, then `monolog` is the root package. ## Properties ### name The name of the package. It consists of vendor name and project name, separated by `/`. Examples: * monolog/monolog * igorw/event-source The name can contain any character, including white spaces, and it's case insensitive (`foo/bar` and `Foo/Bar` are considered the same package). In order to simplify its installation, it's recommended to define a short and lowercase name that doesn't include non-alphanumeric characters or white spaces. Required for published packages (libraries). ### description A short description of the package. Usually this is just one line long. Required for published packages (libraries). ### version The version of the package. In most cases this is not required and should be omitted (see below). This must follow the format of `X.Y.Z` or `vX.Y.Z` with an optional suffix of `-dev`, `-patch` (`-p`), `-alpha` (`-a`), `-beta` (`-b`) or `-RC`. The patch, alpha, beta and RC suffixes can also be followed by a number. Examples: - 1.0.0 - 1.0.2 - 1.1.0 - 0.2.5 - 1.0.0-dev - 1.0.0-alpha3 - 1.0.0-beta2 - 1.0.0-RC5 - v2.0.4-p1 Optional if the package repository can infer the version from somewhere, such as the VCS tag name in the VCS repository. In that case it is also recommended to omit it. > **Note:** Packagist uses VCS repositories, so the statement above is very > much true for Packagist as well. Specifying the version yourself will > most likely end up creating problems at some point due to human error. ### type The type of the package. It defaults to `library`. Package types are used for custom installation logic. If you have a package that needs some special logic, you can define a custom type. This could be a `symfony-bundle`, a `wordpress-plugin` or a `typo3-cms-extension`. These types will all be specific to certain projects, and they will need to provide an installer capable of installing packages of that type. Out of the box, Composer supports four types: - **library:** This is the default. It will simply copy the files to `vendor`. - **project:** This denotes a project rather than a library. For example application shells like the [Symfony standard edition](https://github.com/symfony/symfony-standard), CMSs like the [SilverStripe installer](https://github.com/silverstripe/silverstripe-installer) or full fledged applications distributed as packages. This can for example be used by IDEs to provide listings of projects to initialize when creating a new workspace. - **metapackage:** An empty package that contains requirements and will trigger their installation, but contains no files and will not write anything to the filesystem. As such, it does not require a dist or source key to be installable. - **composer-plugin:** A package of type `composer-plugin` may provide an installer for other packages that have a custom type. Read more in the [dedicated article](articles/custom-installers.md). Only use a custom type if you need custom logic during installation. It is recommended to omit this field and have it just default to `library`. ### keywords An array of keywords that the package is related to. These can be used for searching and filtering. Examples: - logging - events - database - redis - templating Optional. ### homepage An URL to the website of the project. Optional. ### time Release date of the version. Must be in `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` format. Optional. ### license The license of the package. This can be either a string or an array of strings. The recommended notation for the most common licenses is (alphabetical): - Apache-2.0 - BSD-2-Clause - BSD-3-Clause - BSD-4-Clause - GPL-2.0 - GPL-3.0 - LGPL-2.1 - LGPL-3.0 - MIT Optional, but it is highly recommended to supply this. More identifiers are listed at the [SPDX Open Source License Registry](https://spdx.org/licenses/). For closed-source software, you may use `"proprietary"` as the license identifier. An Example: ```json { "license": "MIT" } ``` For a package, when there is a choice between licenses ("disjunctive license"), multiple can be specified as array. An Example for disjunctive licenses: ```json { "license": [ "LGPL-2.1", "GPL-3.0+" ] } ``` Alternatively they can be separated with "or" and enclosed in parenthesis; ```json { "license": "(LGPL-2.1 or GPL-3.0+)" } ``` Similarly when multiple licenses need to be applied ("conjunctive license"), they should be separated with "and" and enclosed in parenthesis. ### authors The authors of the package. This is an array of objects. Each author object can have following properties: * **name:** The author's name. Usually their real name. * **email:** The author's email address. * **homepage:** An URL to the author's website. * **role:** The author's role in the project (e.g. developer or translator) An example: ```json { "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "http://www.naderman.de", "role": "Developer" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "https://seld.be", "role": "Developer" } ] } ``` Optional, but highly recommended. ### support Various information to get support about the project. Support information includes the following: * **email:** Email address for support. * **issues:** URL to the issue tracker. * **forum:** URL to the forum. * **wiki:** URL to the wiki. * **irc:** IRC channel for support, as irc://server/channel. * **source:** URL to browse or download the sources. * **docs:** URL to the documentation. * **rss:** URL to the RSS feed. An example: ```json { "support": { "email": "support@example.org", "irc": "irc://irc.freenode.org/composer" } } ``` Optional. ### Package links All of the following take an object which maps package names to versions of the package via version constraints. Read more about versions [here](articles/versions.md). Example: ```json { "require": { "monolog/monolog": "1.0.*" } } ``` All links are optional fields. `require` and `require-dev` additionally support stability flags ([root-only](04-schema.md#root-package)). These allow you to further restrict or expand the stability of a package beyond the scope of the [minimum-stability](#minimum-stability) setting. You can apply them to a constraint, or just apply them to an empty constraint if you want to allow unstable packages of a dependency for example. Example: ```json { "require": { "monolog/monolog": "1.0.*@beta", "acme/foo": "@dev" } } ``` If one of your dependencies has a dependency on an unstable package you need to explicitly require it as well, along with its sufficient stability flag. Example: Assuming `doctrine/doctrine-fixtures-bundle` requires `"doctrine/data-fixtures": "dev-master"` then inside the root composer.json you need to add the second line below to allow dev releases for the `doctrine/data-fixtures` package : ```json { "require": { "doctrine/doctrine-fixtures-bundle": "dev-master", "doctrine/data-fixtures": "@dev" } } ``` `require` and `require-dev` additionally support explicit references (i.e. commit) for dev versions to make sure they are locked to a given state, even when you run update. These only work if you explicitly require a dev version and append the reference with `#`. Example: ```json { "require": { "monolog/monolog": "dev-master#2eb0c0978d290a1c45346a1955188929cb4e5db7", "acme/foo": "1.0.x-dev#abc123" } } ``` > **Note:** This feature has severe technical limitations, as the > composer.json metadata will still be read from the branch name you specify > before the hash. You should therefore only use this as a temporary solution > during development to remediate transient issues, until you can switch to > tagged releases. The Composer team does not actively support this feature > and will not accept bug reports related to it. It is also possible to inline-alias a package constraint so that it matches a constraint that it otherwise would not. For more information [see the aliases article](articles/aliases.md). `require` and `require-dev` also support references to specific PHP versions and PHP extensions your project needs to run successfully. Example: ```json { "require" : { "php" : "^5.5 || ^7.0", "ext-mbstring": "*" } } ``` > **Note:** It is important to list PHP extensions your project requires. > Not all PHP installations are created equal: some may miss extensions you > may consider as standard (such as `ext-mysqli` which is not installed by > default in Fedora/CentOS minimal installation systems). Failure to list > required PHP extensions may lead to a bad user experience: Composer will > install your package without any errors but it will then fail at run-time. > The `composer show --platform` command lists all PHP extensions available on > your system. You may use it to help you compile the list of extensions you > use and require. Alternatively you may use third party tools to analyze > your project for the list of extensions used. #### require Lists packages required by this package. The package will not be installed unless those requirements can be met. #### require-dev ([root-only](04-schema.md#root-package)) Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both `install` or `update` support the `--no-dev` option that prevents dev dependencies from being installed. #### conflict Lists packages that conflict with this version of this package. They will not be allowed to be installed together with your package. Note that when specifying ranges like `<1.0 >=1.1` in a `conflict` link, this will state a conflict with all versions that are less than 1.0 *and* equal or newer than 1.1 at the same time, which is probably not what you want. You probably want to go for `<1.0 || >=1.1` in this case. #### replace Lists packages that are replaced by this package. This allows you to fork a package, publish it under a different name with its own version numbers, while packages requiring the original package continue to work with your fork because it replaces the original package. This is also useful for packages that contain sub-packages, for example the main symfony/symfony package contains all the Symfony Components which are also available as individual packages. If you require the main package it will automatically fulfill any requirement of one of the individual components, since it replaces them. Caution is advised when using replace for the sub-package purpose explained above. You should then typically only replace using `self.version` as a version constraint, to make sure the main package only replaces the sub-packages of that exact version, and not any other version, which would be incorrect. #### provide List of other packages that are provided by this package. This is mostly useful for common interfaces. A package could depend on some virtual `logger` package, any library that implements this logger interface would simply list it in `provide`. #### suggest Suggested packages that can enhance or work well with this package. These are just informational and are displayed after the package is installed, to give your users a hint that they could add more packages, even though they are not strictly required. The format is like package links above, except that the values are free text and not version constraints. Example: ```json { "suggest": { "monolog/monolog": "Allows more advanced logging of the application flow", "ext-xml": "Needed to support XML format in class Foo" } } ``` ### autoload Autoload mapping for a PHP autoloader. [`PSR-4`](http://www.php-fig.org/psr/psr-4/) and [`PSR-0`](http://www.php-fig.org/psr/psr-0/) autoloading, `classmap` generation and `files` includes are supported. PSR-4 is the recommended way since it offers greater ease of use (no need to regenerate the autoloader when you add classes). #### PSR-4 Under the `psr-4` key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like `Foo\\Bar\\Baz` a namespace prefix `Foo\\` pointing to a directory `src/` means that the autoloader will look for a file named `src/Bar/Baz.php` and include it if present. Note that as opposed to the older PSR-0 style, the prefix (`Foo\\`) is **not** present in the file path. Namespace prefixes must end in `\\` to avoid conflicts between similar prefixes. For example `Foo` would match classes in the `FooBar` namespace so the trailing backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct. The PSR-4 references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_psr4.php`. Example: ```json { "autoload": { "psr-4": { "Monolog\\": "src/", "Vendor\\Namespace\\": "" } } } ``` If you need to search for a same prefix in multiple directories, you can specify them as an array as such: ```json { "autoload": { "psr-4": { "Monolog\\": ["src/", "lib/"] } } } ``` If you want to have a fallback directory where any namespace will be looked for, you can use an empty prefix like: ```json { "autoload": { "psr-4": { "": "src/" } } } ``` #### PSR-0 Under the `psr-0` key you define a mapping from namespaces to paths, relative to the package root. Note that this also supports the PEAR-style non-namespaced convention. Please note namespace declarations should end in `\\` to make sure the autoloader responds exactly. For example `Foo` would match in `FooBar` so the trailing backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct. The PSR-0 references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_namespaces.php`. Example: ```json { "autoload": { "psr-0": { "Monolog\\": "src/", "Vendor\\Namespace\\": "src/", "Vendor_Namespace_": "src/" } } } ``` If you need to search for a same prefix in multiple directories, you can specify them as an array as such: ```json { "autoload": { "psr-0": { "Monolog\\": ["src/", "lib/"] } } } ``` The PSR-0 style is not limited to namespace declarations only but may be specified right down to the class level. This can be useful for libraries with only one class in the global namespace. If the php source file is also located in the root of the package, for example, it may be declared like this: ```json { "autoload": { "psr-0": { "UniqueGlobalClass": "" } } } ``` If you want to have a fallback directory where any namespace can be, you can use an empty prefix like: ```json { "autoload": { "psr-0": { "": "src/" } } } ``` #### Classmap The `classmap` references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_classmap.php`. This map is built by scanning for classes in all `.php` and `.inc` files in the given directories/files. You can use the classmap generation support to define autoloading for all libraries that do not follow PSR-0/4. To configure this you specify all directories or files to search for classes. Example: ```json { "autoload": { "classmap": ["src/", "lib/", "Something.php"] } } ``` #### Files If you want to require certain files explicitly on every request then you can use the `files` autoloading mechanism. This is useful if your package includes PHP functions that cannot be autoloaded by PHP. Example: ```json { "autoload": { "files": ["src/MyLibrary/functions.php"] } } ``` #### Exclude files from classmaps If you want to exclude some files or folders from the classmap you can use the `exclude-from-classmap` property. This might be useful to exclude test classes in your live environment, for example, as those will be skipped from the classmap even when building an optimized autoloader. The classmap generator will ignore all files in the paths configured here. The paths are absolute from the package root directory (i.e. composer.json location), and support `*` to match anything but a slash, and `**` to match anything. `**` is implicitly added to the end of the paths. Example: ```json { "autoload": { "exclude-from-classmap": ["/Tests/", "/test/", "/tests/"] } } ``` #### Optimizing the autoloader The autoloader can have quite a substantial impact on your request time (50-100ms per request in large frameworks using a lot of classes). See the [article about optimizing the autoloader](articles/autoloader-optimization.md) for more details on how to reduce this impact. ### autoload-dev ([root-only](04-schema.md#root-package)) This section allows to define autoload rules for development purposes. Classes needed to run the test suite should not be included in the main autoload rules to avoid polluting the autoloader in production and when other people use your package as a dependency. Therefore, it is a good idea to rely on a dedicated path for your unit tests and to add it within the autoload-dev section. Example: ```json { "autoload": { "psr-4": { "MyLibrary\\": "src/" } }, "autoload-dev": { "psr-4": { "MyLibrary\\Tests\\": "tests/" } } } ``` ### include-path > **DEPRECATED**: This is only present to support legacy projects, and all new code > should preferably use autoloading. As such it is a deprecated practice, but the > feature itself will not likely disappear from Composer. A list of paths which should get appended to PHP's `include_path`. Example: ```json { "include-path": ["lib/"] } ``` Optional. ### target-dir > **DEPRECATED**: This is only present to support legacy PSR-0 style autoloading, > and all new code should preferably use PSR-4 without target-dir and projects > using PSR-0 with PHP namespaces are encouraged to migrate to PSR-4 instead. Defines the installation target. In case the package root is below the namespace declaration you cannot autoload properly. `target-dir` solves this problem. An example is Symfony. There are individual packages for the components. The Yaml component is under `Symfony\Component\Yaml`. The package root is that `Yaml` directory. To make autoloading possible, we need to make sure that it is not installed into `vendor/symfony/yaml`, but instead into `vendor/symfony/yaml/Symfony/Component/Yaml`, so that the autoloader can load it from `vendor/symfony/yaml`. To do that, `autoload` and `target-dir` are defined as follows: ```json { "autoload": { "psr-0": { "Symfony\\Component\\Yaml\\": "" } }, "target-dir": "Symfony/Component/Yaml" } ``` Optional. ### minimum-stability ([root-only](04-schema.md#root-package)) This defines the default behavior for filtering packages by stability. This defaults to `stable`, so if you rely on a `dev` package, you should specify it in your file to avoid surprises. All versions of each package are checked for stability, and those that are less stable than the `minimum-stability` setting will be ignored when resolving your project dependencies. (Note that you can also specify stability requirements on a per-package basis using stability flags in the version constraints that you specify in a `require` block (see [package links](#package-links) for more details). Available options (in order of stability) are `dev`, `alpha`, `beta`, `RC`, and `stable`. ### prefer-stable ([root-only](04-schema.md#root-package)) When this is enabled, Composer will prefer more stable packages over unstable ones when finding compatible stable packages is possible. If you require a dev version or only alphas are available for a package, those will still be selected granted that the minimum-stability allows for it. Use `"prefer-stable": true` to enable. ### repositories ([root-only](04-schema.md#root-package)) Custom package repositories to use. By default Composer just uses the packagist repository. By specifying repositories you can get packages from elsewhere. Repositories are not resolved recursively. You can only add them to your main `composer.json`. Repository declarations of dependencies' `composer.json`s are ignored. The following repository types are supported: * **composer:** A Composer repository is simply a `packages.json` file served via the network (HTTP, FTP, SSH), that contains a list of `composer.json` objects with additional `dist` and/or `source` information. The `packages.json` file is loaded using a PHP stream. You can set extra options on that stream using the `options` parameter. * **vcs:** The version control system repository can fetch packages from git, svn, fossil and hg repositories. * **pear:** With this you can import any pear repository into your Composer project. * **package:** If you depend on a project that does not have any support for composer whatsoever you can define the package inline using a `package` repository. You basically just inline the `composer.json` object. For more information on any of these, see [Repositories](05-repositories.md). Example: ```json { "repositories": [ { "type": "composer", "url": "http://packages.example.com" }, { "type": "composer", "url": "https://packages.example.com", "options": { "ssl": { "verify_peer": "true" } } }, { "type": "vcs", "url": "https://github.com/Seldaek/monolog" }, { "type": "pear", "url": "https://pear2.php.net" }, { "type": "package", "package": { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" }, "source": { "url": "https://smarty-php.googlecode.com/svn/", "type": "svn", "reference": "tags/Smarty_3_1_7/distribution/" } } } ] } ``` > **Note:** Order is significant here. When looking for a package, Composer will look from the first to the last repository, and pick the first match. By default Packagist is added last which means that custom repositories can override packages from it. Using JSON object notation is also possible. However, JSON key/value pairs are to be considered unordered so consistent behaviour cannot be guaranteed. ```json { "repositories": { "foo": { "type": "composer", "url": "http://packages.foo.com" } } } ``` ### config ([root-only](04-schema.md#root-package)) A set of configuration options. It is only used for projects. See [Config](06-config.md) for a description of each individual option. ### scripts ([root-only](04-schema.md#root-package)) Composer allows you to hook into various parts of the installation process through the use of scripts. See [Scripts](articles/scripts.md) for events details and examples. ### extra Arbitrary extra data for consumption by `scripts`. This can be virtually anything. To access it from within a script event handler, you can do: ```php $extra = $event->getComposer()->getPackage()->getExtra(); ``` Optional. ### bin A set of files that should be treated as binaries and symlinked into the `bin-dir` (from config). See [Vendor Binaries](articles/vendor-binaries.md) for more details. Optional. ### archive A set of options for creating package archives. The following options are supported: * **exclude:** Allows configuring a list of patterns for excluded paths. The pattern syntax matches .gitignore files. A leading exclamation mark (!) will result in any matching files to be included even if a previous pattern excluded them. A leading slash will only match at the beginning of the project relative path. An asterisk will not expand to a directory separator. Example: ```json { "archive": { "exclude": ["/foo/bar", "baz", "/*.test", "!/foo/bar/baz"] } } ``` The example will include `/dir/foo/bar/file`, `/foo/bar/baz`, `/file.php`, `/foo/my.test` but it will exclude `/foo/bar/any`, `/foo/baz`, and `/my.test`. Optional. ### non-feature-branches A list of regex patterns of branch names that are non-numeric (e.g. "latest" or something), that will NOT be handled as feature branches. This is an array of strings. If you have non-numeric branch names, for example like "latest", "current", "latest-stable" or something, that do not look like a version number, then Composer handles such branches as feature branches. This means it searches for parent branches, that look like a version or ends at special branches (like master) and the root package version number becomes the version of the parent branch or at least master or something. To handle non-numeric named branches as versions instead of searching for a parent branch with a valid version or special branch name like master, you can set patterns for branch names, that should be handled as dev version branches. This is really helpful when you have dependencies using "self.version", so that not dev-master, but the same branch is installed (in the example: latest-testing). An example: If you have a testing branch, that is heavily maintained during a testing phase and is deployed to your staging environment, normally `composer show -s` will give you `versions : * dev-master`. If you configure `latest-.*` as a pattern for non-feature-branches like this: ```json { "non-feature-branches": ["latest-.*"] } ``` Then `composer show -s` will give you `versions : * dev-latest-testing`. Optional. ← [Command-line interface](03-cli.md) | [Repositories](05-repositories.md) → composer-1.6.3/doc/05-repositories.md000066400000000000000000000562271323436022200174210ustar00rootroot00000000000000# Repositories This chapter will explain the concept of packages and repositories, what kinds of repositories are available, and how they work. ## Concepts Before we look at the different types of repositories that exist, we need to understand some of the basic concepts that Composer is built on. ### Package Composer is a dependency manager. It installs packages locally. A package is essentially just a directory containing something. In this case it is PHP code, but in theory it could be anything. And it contains a package description which has a name and a version. The name and the version are used to identify the package. In fact, internally Composer sees every version as a separate package. While this distinction does not matter when you are using Composer, it's quite important when you want to change it. In addition to the name and the version, there is useful metadata. The information most relevant for installation is the source definition, which describes where to get the package contents. The package data points to the contents of the package. And there are two options here: dist and source. **Dist:** The dist is a packaged version of the package data. Usually a released version, usually a stable release. **Source:** The source is used for development. This will usually originate from a source code repository, such as git. You can fetch this when you want to modify the downloaded package. Packages can supply either of these, or even both. Depending on certain factors, such as user-supplied options and stability of the package, one will be preferred. ### Repository A repository is a package source. It's a list of packages/versions. Composer will look in all your repositories to find the packages your project requires. By default only the Packagist repository is registered in Composer. You can add more repositories to your project by declaring them in `composer.json`. Repositories are only available to the root package and the repositories defined in your dependencies will not be loaded. Read the [FAQ entry](faqs/why-can't-composer-load-repositories-recursively.md) if you want to learn why. ## Types ### Composer The main repository type is the `composer` repository. It uses a single `packages.json` file that contains all of the package metadata. This is also the repository type that packagist uses. To reference a `composer` repository, just supply the path before the `packages.json` file. In the case of packagist, that file is located at `/packages.json`, so the URL of the repository would be `packagist.org`. For `example.org/packages.json` the repository URL would be `example.org`. #### packages The only required field is `packages`. The JSON structure is as follows: ```json { "packages": { "vendor/package-name": { "dev-master": { @composer.json }, "1.0.x-dev": { @composer.json }, "0.0.1": { @composer.json }, "1.0.0": { @composer.json } } } } ``` The `@composer.json` marker would be the contents of the `composer.json` from that package version including as a minimum: * name * version * dist or source Here is a minimal package definition: ```json { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" } } ``` It may include any of the other fields specified in the [schema](04-schema.md). #### notify-batch The `notify-batch` field allows you to specify a URL that will be called every time a user installs a package. The URL can be either an absolute path (that will use the same domain as the repository) or a fully qualified URL. An example value: ```json { "notify-batch": "/downloads/" } ``` For `example.org/packages.json` containing a `monolog/monolog` package, this would send a `POST` request to `example.org/downloads/` with following JSON request body: ```json { "downloads": [ {"name": "monolog/monolog", "version": "1.2.1.0"} ] } ``` The version field will contain the normalized representation of the version number. This field is optional. #### provider-includes and providers-url The `provider-includes` field allows you to list a set of files that list package names provided by this repository. The hash should be a sha256 of the files in this case. The `providers-url` describes how provider files are found on the server. It is an absolute path from the repository root. It must contain the placeholders `%package%` and `%hash%`. An example: ```json { "provider-includes": { "providers-a.json": { "sha256": "f5b4bc0b354108ef08614e569c1ed01a2782e67641744864a74e788982886f4c" }, "providers-b.json": { "sha256": "b38372163fac0573053536f5b8ef11b86f804ea8b016d239e706191203f6efac" } }, "providers-url": "/p/%package%$%hash%.json" } ``` Those files contain lists of package names and hashes to verify the file integrity, for example: ```json { "providers": { "acme/foo": { "sha256": "38968de1305c2e17f4de33aea164515bc787c42c7e2d6e25948539a14268bb82" }, "acme/bar": { "sha256": "4dd24c930bd6e1103251306d6336ac813b563a220d9ca14f4743c032fb047233" } } } ``` The file above declares that acme/foo and acme/bar can be found in this repository, by loading the file referenced by `providers-url`, replacing `%package%` by the vendor namespaced package name and `%hash%` by the sha256 field. Those files themselves just contain package definitions as described [above](#packages). These fields are optional. You probably don't need them for your own custom repository. #### stream options The `packages.json` file is loaded using a PHP stream. You can set extra options on that stream using the `options` parameter. You can set any valid PHP stream context option. See [Context options and parameters](https://php.net/manual/en/context.php) for more information. ### VCS VCS stands for version control system. This includes versioning systems like git, svn, fossil or hg. Composer has a repository type for installing packages from these systems. #### Loading a package from a VCS repository There are a few use cases for this. The most common one is maintaining your own fork of a third party library. If you are using a certain library for your project and you decide to change something in the library, you will want your project to use the patched version. If the library is on GitHub (this is the case most of the time), you can simply fork it there and push your changes to your fork. After that you update the project's `composer.json`. All you have to do is add your fork as a repository and update the version constraint to point to your custom branch. In `composer.json`, you should prefix your custom branch name with `"dev-"`. For version constraint naming conventions see [Libraries](02-libraries.md) for more information. Example assuming you patched monolog to fix a bug in the `bugfix` branch: ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/igorw/monolog" } ], "require": { "monolog/monolog": "dev-bugfix" } } ``` When you run `php composer.phar update`, you should get your modified version of `monolog/monolog` instead of the one from packagist. Note that you should not rename the package unless you really intend to fork it in the long term, and completely move away from the original package. Composer will correctly pick your package over the original one since the custom repository has priority over packagist. If you want to rename the package, you should do so in the default (often master) branch and not in a feature branch, since the package name is taken from the default branch. Also note that the override will not work if you change the `name` property in your forked repository's `composer.json` file as this needs to match the original for the override to work. If other dependencies rely on the package you forked, it is possible to inline-alias it so that it matches a constraint that it otherwise would not. For more information [see the aliases article](articles/aliases.md). #### Using private repositories Exactly the same solution allows you to work with your private repositories at GitHub and BitBucket: ```json { "require": { "vendor/my-private-repo": "dev-master" }, "repositories": [ { "type": "vcs", "url": "git@bitbucket.org:vendor/my-private-repo.git" } ] } ``` The only requirement is the installation of SSH keys for a git client. #### Git alternatives Git is not the only version control system supported by the VCS repository. The following are supported: * **Git:** [git-scm.com](https://git-scm.com) * **Subversion:** [subversion.apache.org](https://subversion.apache.org) * **Mercurial:** [mercurial-scm.org](https://www.mercurial-scm.org) * **Fossil**: [fossil-scm.org](https://www.fossil-scm.org/) To get packages from these systems you need to have their respective clients installed. That can be inconvenient. And for this reason there is special support for GitHub and BitBucket that use the APIs provided by these sites, to fetch the packages without having to install the version control system. The VCS repository provides `dist`s for them that fetch the packages as zips. * **GitHub:** [github.com](https://github.com) (Git) * **BitBucket:** [bitbucket.org](https://bitbucket.org) (Git and Mercurial) The VCS driver to be used is detected automatically based on the URL. However, should you need to specify one for whatever reason, you can use `git-bitbucket`, `hg-bitbucket`, `github`, `gitlab`, `perforce`, `fossil`, `git`, `svn` or `hg` as the repository type instead of `vcs`. If you set the `no-api` key to `true` on a github repository it will clone the repository as it would with any other git repository instead of using the GitHub API. But unlike using the `git` driver directly, Composer will still attempt to use github's zip files. Please note: * **To let Composer choose which driver to use** the repository type needs to be defined as "vcs" * **If you already used a private repository**, this means Composer should have cloned it in cache. If you want to install the same package with drivers, remember to launch the command `composer clearcache` followed by the command `composer update` to update composer cache and install the package from dist. #### BitBucket Driver Configuration The BitBucket driver uses OAuth to access your private repositories via the BitBucket REST APIs and you will need to create an OAuth consumer to use the driver, please refer to [Atlassian's Documentation](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html). You will need to fill the callback url with something to satisfy BitBucket, but the address does not need to go anywhere and is not used by Composer. After creating an OAuth consumer in the BitBucket control panel, you need to setup your auth.json file with the credentials like this (more info [here](https://getcomposer.org/doc/06-config.md#bitbucket-oauth)): ```json { "config": { "bitbucket-oauth": { "bitbucket.org": { "consumer-key": "myKey", "consumer-secret": "mySecret" } } } } ``` **Note that the repository endpoint needs to be https rather than git.** Alternatively if you prefer not to have your OAuth credentials on your filesystem you may export the ```bitbucket-oauth``` block above to the [COMPOSER_AUTH](https://getcomposer.org/doc/03-cli.md#composer-auth) environment variable instead. #### Subversion Options Since Subversion has no native concept of branches and tags, Composer assumes by default that code is located in `$url/trunk`, `$url/branches` and `$url/tags`. If your repository has a different layout you can change those values. For example if you used capitalized names you could configure the repository like this: ```json { "repositories": [ { "type": "vcs", "url": "http://svn.example.org/projectA/", "trunk-path": "Trunk", "branches-path": "Branches", "tags-path": "Tags" } ] } ``` If you have no branches or tags directory you can disable them entirely by setting the `branches-path` or `tags-path` to `false`. If the package is in a sub-directory, e.g. `/trunk/foo/bar/composer.json` and `/tags/1.0/foo/bar/composer.json`, then you can make Composer access it by setting the `"package-path"` option to the sub-directory, in this example it would be `"package-path": "foo/bar/"`. If you have a private Subversion repository you can save credentials in the http-basic section of your config (See [Schema](04-schema.md)): ```json { "http-basic": { "svn.example.org": { "username": "username", "password": "password" } } } ``` If your Subversion client is configured to store credentials by default these credentials will be saved for the current user and existing saved credentials for this server will be overwritten. To change this behavior by setting the `"svn-cache-credentials"` option in your repository configuration: ```json { "repositories": [ { "type": "vcs", "url": "http://svn.example.org/projectA/", "svn-cache-credentials": false } ] } ``` ### PEAR It is possible to install packages from any PEAR channel by using the `pear` repository. Composer will prefix all package names with `pear-{channelName}/` to avoid conflicts. All packages are also aliased with prefix `pear-{channelAlias}/`. Example using `pear2.php.net`: ```json { "repositories": [ { "type": "pear", "url": "https://pear2.php.net" } ], "require": { "pear-pear2.php.net/PEAR2_Text_Markdown": "*", "pear-pear2/PEAR2_HTTP_Request": "*" } } ``` In this case the short name of the channel is `pear2`, so the `PEAR2_HTTP_Request` package name becomes `pear-pear2/PEAR2_HTTP_Request`. > **Note:** The `pear` repository requires doing quite a few requests per > package, so this may considerably slow down the installation process. #### Custom vendor alias It is possible to alias PEAR channel packages with a custom vendor name. Example: Suppose you have a private PEAR repository and wish to use Composer to incorporate dependencies from a VCS. Your PEAR repository contains the following packages: * `BasePackage` * `IntermediatePackage`, which depends on `BasePackage` * `TopLevelPackage1` and `TopLevelPackage2` which both depend on `IntermediatePackage` Without a vendor alias, Composer will use the PEAR channel name as the vendor portion of the package name: * `pear-pear.foobar.repo/BasePackage` * `pear-pear.foobar.repo/IntermediatePackage` * `pear-pear.foobar.repo/TopLevelPackage1` * `pear-pear.foobar.repo/TopLevelPackage2` Suppose at a later time you wish to migrate your PEAR packages to a Composer repository and naming scheme, and adopt the vendor name of `foobar`. Projects using your PEAR packages would not see the updated packages, since they have a different vendor name (`foobar/IntermediatePackage` vs `pear-pear.foobar.repo/IntermediatePackage`). By specifying `vendor-alias` for the PEAR repository from the start, you can avoid this scenario and future-proof your package names. To illustrate, the following example would get the `BasePackage`, `TopLevelPackage1`, and `TopLevelPackage2` packages from your PEAR repository and `IntermediatePackage` from a Github repository: ```json { "repositories": [ { "type": "git", "url": "https://github.com/foobar/intermediate.git" }, { "type": "pear", "url": "http://pear.foobar.repo", "vendor-alias": "foobar" } ], "require": { "foobar/TopLevelPackage1": "*", "foobar/TopLevelPackage2": "*" } } ``` ### Package If you want to use a project that does not support Composer through any of the means above, you still can define the package yourself by using a `package` repository. Basically, you define the same information that is included in the `composer` repository's `packages.json`, but only for a single package. Again, the minimum required fields are `name`, `version`, and either of `dist` or `source`. Here is an example for the smarty template engine: ```json { "repositories": [ { "type": "package", "package": { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" }, "source": { "url": "http://smarty-php.googlecode.com/svn/", "type": "svn", "reference": "tags/Smarty_3_1_7/distribution/" }, "autoload": { "classmap": ["libs/"] } } } ], "require": { "smarty/smarty": "3.1.*" } } ``` Typically you would leave the source part off, as you don't really need it. > **Note**: This repository type has a few limitations and should be avoided > whenever possible: > > - Composer will not update the package unless you change the `version` field. > - Composer will not update the commit references, so if you use `master` as > reference you will have to delete the package to force an update, and will > have to deal with an unstable lock file. The `"package"` key in a `package` repository may be set to an array to define multiple versions of a package: ```json { "repositories": [ { "type": "package", "package": [ { "name": "foo/bar", "version": "1.0.0", ... }, { "name": "foo/bar", "version": "2.0.0", ... } ] } ] } ``` ## Hosting your own While you will probably want to put your packages on packagist most of the time, there are some use cases for hosting your own repository. * **Private company packages:** If you are part of a company that uses Composer for their packages internally, you might want to keep those packages private. * **Separate ecosystem:** If you have a project which has its own ecosystem, and the packages aren't really reusable by the greater PHP community, you might want to keep them separate to packagist. An example of this would be wordpress plugins. For hosting your own packages, a native `composer` type of repository is recommended, which provides the best performance. There are a few tools that can help you create a `composer` repository. ### Private Packagist [Private Packagist](https://packagist.com/) is a hosted or self-hosted application providing private package hosting as well as mirroring of GitHub, Packagist.org and other package repositories. Check out [Packagist.com](https://packagist.com/) for more information. ### Satis Satis is a static `composer` repository generator. It is a bit like an ultra- lightweight, static file-based version of packagist. You give it a `composer.json` containing repositories, typically VCS and package repository definitions. It will fetch all the packages that are `require`d and dump a `packages.json` that is your `composer` repository. Check [the satis GitHub repository](https://github.com/composer/satis) and the [Satis article](articles/handling-private-packages-with-satis.md) for more information. ### Artifact There are some cases, when there is no ability to have one of the previously mentioned repository types online, even the VCS one. Typical example could be cross-organisation library exchange through built artifacts. Of course, most of the times they are private. To simplify maintenance, one can simply use a repository of type `artifact` with a folder containing ZIP archives of those private packages: ```json { "repositories": [ { "type": "artifact", "url": "path/to/directory/with/zips/" } ], "require": { "private-vendor-one/core": "15.6.2", "private-vendor-two/connectivity": "*", "acme-corp/parser": "10.3.5" } } ``` Each zip artifact is just a ZIP archive with `composer.json` in root folder: ```sh unzip -l acme-corp-parser-10.3.5.zip composer.json ... ``` If there are two archives with different versions of a package, they are both imported. When an archive with a newer version is added in the artifact folder and you run `update`, that version will be imported as well and Composer will update to the latest version. ### Path In addition to the artifact repository, you can use the path one, which allows you to depend on a local directory, either absolute or relative. This can be especially useful when dealing with monolithic repositories. For instance, if you have the following directory structure in your repository: ``` - apps \_ my-app \_ composer.json - packages \_ my-package \_ composer.json ``` Then, to add the package `my/package` as a dependency, in your `apps/my-app/composer.json` file, you can use the following configuration: ```json { "repositories": [ { "type": "path", "url": "../../packages/my-package" } ], "require": { "my/package": "*" } } ``` If the package is a local VCS repository, the version may be inferred by the branch or tag that is currently checked out. Otherwise, the version should be explicitly defined in the package's `composer.json` file. If the version cannot be resolved by these means, it is assumed to be `dev-master`. The local package will be symlinked if possible, in which case the output in the console will read `Symlinked from ../../packages/my-package`. If symlinking is _not_ possible the package will be copied. In that case, the console will output `Mirrored from ../../packages/my-package`. Instead of default fallback strategy you can force to use symlink with `"symlink": true` or mirroring with `"symlink": false` option. Forcing mirroring can be useful when deploying or generating package from a monolithic repository. ```json { "repositories": [ { "type": "path", "url": "../../packages/my-package", "options": { "symlink": false } } ] } ``` Leading tildes are expanded to the current user's home folder, and environment variables are parsed in both Windows and Linux/Mac notations. For example `~/git/mypackage` will automatically load the mypackage clone from `/home//git/mypackage`, equivalent to `$HOME/git/mypackage` or `%USERPROFILE%/git/mypackage`. > **Note:** Repository paths can also contain wildcards like ``*`` and ``?``. > For details, see the [PHP glob function](http://php.net/glob). ## Disabling Packagist.org You can disable the default Packagist.org repository by adding this to your `composer.json`: ```json { "repositories": [ { "packagist.org": false } ] } ``` You can disable Packagist.org globally by using the global config flag: ```bash composer config -g repo.packagist false ``` ← [Schema](04-schema.md) | [Config](06-config.md) → composer-1.6.3/doc/06-config.md000066400000000000000000000230071323436022200161260ustar00rootroot00000000000000# Config This chapter will describe the `config` section of the `composer.json` [schema](04-schema.md). ## process-timeout Defaults to `300`. The duration processes like git clones can run before Composer assumes they died out. You may need to make this higher if you have a slow connection or huge vendors. ## use-include-path Defaults to `false`. If `true`, the Composer autoloader will also look for classes in the PHP include path. ## preferred-install Defaults to `auto` and can be any of `source`, `dist` or `auto`. This option allows you to set the install method Composer will prefer to use. Can optionally be a hash of patterns for more granular install preferences. ```json { "config": { "preferred-install": { "my-organization/stable-package": "dist", "my-organization/*": "source", "partner-organization/*": "auto", "*": "dist" } } } ``` > **Note:** Order matters. More specific patterns should be earlier than > more relaxed patterns. When mixing the string notation with the hash > configuration in global and package configurations the string notation > is translated to a `*` package pattern. ## store-auths What to do after prompting for authentication, one of: `true` (always store), `false` (do not store) and `"prompt"` (ask every time), defaults to `"prompt"`. ## github-protocols Defaults to `["https", "ssh", "git"]`. A list of protocols to use when cloning from github.com, in priority order. By default `git` is present but only if [secure-http](#secure-http) is disabled, as the git protocol is not encrypted. If you want your origin remote push URLs to be using https and not ssh (`git@github.com:...`), then set the protocol list to be only `["https"]` and Composer will stop overwriting the push URL to an ssh URL. ## github-oauth A list of domain names and oauth keys. For example using `{"github.com": "oauthtoken"}` as the value of this option will use `oauthtoken` to access private repositories on github and to circumvent the low IP-based rate limiting of their API. [Read more](articles/troubleshooting.md#api-rate-limit-and-oauth-tokens) on how to get an OAuth token for GitHub. ## gitlab-oauth A list of domain names and oauth keys. For example using `{"gitlab.com": "oauthtoken"}` as the value of this option will use `oauthtoken` to access private repositories on gitlab. ## gitlab-token A list of domain names and private tokens. For example using `{"gitlab.com": "privatetoken"}` as the value of this option will use `privatetoken` to access private repositories on gitlab. ## disable-tls Defaults to `false`. If set to true all HTTPS URLs will be tried with HTTP instead and no network level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini. ## secure-http Defaults to `true`. If set to true only HTTPS URLs are allowed to be downloaded via Composer. If you really absolutely need HTTP access to something then you can disable it, but using [Let's Encrypt](https://letsencrypt.org/) to get a free SSL certificate is generally a better alternative. ## bitbucket-oauth A list of domain names and consumers. For example using `{"bitbucket.org": {"consumer-key": "myKey", "consumer-secret": "mySecret"}}`. [Read](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) how to set up a consumer on Bitbucket. ## cafile Location of Certificate Authority file on local filesystem. In PHP 5.6+ you should rather set this via openssl.cafile in php.ini, although PHP 5.6+ should be able to detect your system CA file automatically. ## capath If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory. ## http-basic A list of domain names and username/passwords to authenticate against them. For example using `{"example.org": {"username": "alice", "password": "foo"}}` as the value of this option will let Composer authenticate against example.org. > **Note:** Authentication-related config options like `http-basic` and > `github-oauth` can also be specified inside a `auth.json` file that goes > besides your `composer.json`. That way you can gitignore it and every > developer can place their own credentials in there. ## platform Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: `{"php": "5.4", "ext-something": "4.0"}`. ## vendor-dir Defaults to `vendor`. You can install dependencies into a different directory if you want to. `$HOME` and `~` will be replaced by your home directory's path in vendor-dir and all `*-dir` options below. ## bin-dir Defaults to `vendor/bin`. If a project includes binaries, they will be symlinked into this directory. ## data-dir Defaults to `C:\Users\\AppData\Roaming\Composer` on Windows, `$XDG_DATA_HOME/composer` on unix systems that follow the XDG Base Directory Specifications, and `$home` on other unix systems. Right now it is only used for storing past composer.phar files to be able to rollback to older versions. See also [COMPOSER_HOME](03-cli.md#composer-home). ## cache-dir Defaults to `C:\Users\\AppData\Local\Composer` on Windows, `$XDG_CACHE_HOME/composer` on unix systems that follow the XDG Base Directory Specifications, and `$home/cache` on other unix systems. Stores all the caches used by Composer. See also [COMPOSER_HOME](03-cli.md#composer-home). ## cache-files-dir Defaults to `$cache-dir/files`. Stores the zip archives of packages. ## cache-repo-dir Defaults to `$cache-dir/repo`. Stores repository metadata for the `composer` type and the VCS repos of type `svn`, `fossil`, `github` and `bitbucket`. ## cache-vcs-dir Defaults to `$cache-dir/vcs`. Stores VCS clones for loading VCS repository metadata for the `git`/`hg` types and to speed up installs. ## cache-files-ttl Defaults to `15552000` (6 months). Composer caches all dist (zip, tar, ..) packages that it downloads. Those are purged after six months of being unused by default. This option allows you to tweak this duration (in seconds) or disable it completely by setting it to 0. ## cache-files-maxsize Defaults to `300MiB`. Composer caches all dist (zip, tar, ..) packages that it downloads. When the garbage collection is periodically ran, this is the maximum size the cache will be able to use. Older (less used) files will be removed first until the cache fits. ## bin-compat Defaults to `auto`. Determines the compatibility of the binaries to be installed. If it is `auto` then Composer only installs .bat proxy files when on Windows. If set to `full` then both .bat files for Windows and scripts for Unix-based operating systems will be installed for each binary. This is mainly useful if you run Composer inside a linux VM but still want the .bat proxies available for use in the Windows host OS. ## prepend-autoloader Defaults to `true`. If `false`, the Composer autoloader will not be prepended to existing autoloaders. This is sometimes required to fix interoperability issues with other autoloaders. ## autoloader-suffix Defaults to `null`. String to be used as a suffix for the generated Composer autoloader. When null a random one will be generated. ## optimize-autoloader Defaults to `false`. If `true`, always optimize when dumping the autoloader. ## sort-packages Defaults to `false`. If `true`, the `require` command keeps packages sorted by name in `composer.json` when adding a new package. ## classmap-authoritative Defaults to `false`. If `true`, the Composer autoloader will only load classes from the classmap. Implies `optimize-autoloader`. ## apcu-autoloader Defaults to `false`. If `true`, the Composer autoloader will check for APCu and use it to cache found/not-found classes when the extension is enabled. ## github-domains Defaults to `["github.com"]`. A list of domains to use in github mode. This is used for GitHub Enterprise setups. ## github-expose-hostname Defaults to `true`. If `false`, the OAuth tokens created to access the github API will have a date instead of the machine hostname. ## gitlab-domains Defaults to `["gitlab.com"]`. A list of domains of GitLab servers. This is used if you use the `gitlab` repository type. ## notify-on-install Defaults to `true`. Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour. ## discard-changes Defaults to `false` and can be any of `true`, `false` or `"stash"`. This option allows you to set the default style of handling dirty updates when in non-interactive mode. `true` will always discard changes in vendors, while `"stash"` will try to stash and reapply. Use this for CI servers or deploy scripts if you tend to have modified vendors. ## archive-format Defaults to `tar`. Composer allows you to add a default archive format when the workflow needs to create a dedicated archiving format. ## archive-dir Defaults to `.`. Composer allows you to add a default archive directory when the workflow needs to create a dedicated archiving format. Or for easier development between modules. Example: ```json { "config": { "archive-dir": "/home/user/.composer/repo" } } ``` ## htaccess-protect Defaults to `true`. If set to `false`, Composer will not create `.htaccess` files in the composer home, cache, and data directories. ← [Repositories](05-repositories.md) | [Community](07-community.md) → composer-1.6.3/doc/07-community.md000066400000000000000000000024511323436022200167060ustar00rootroot00000000000000# Community There are many people using Composer already, and quite a few of them are contributing. ## Contributing If you would like to contribute to Composer, please read the [README](https://github.com/composer/composer) and [CONTRIBUTING](https://github.com/composer/composer/blob/master/.github/CONTRIBUTING.md) documents. The most important guidelines are described as follows: > All code contributions - including those of people having commit access - must > go through a pull request and approved by a core developer before being > merged. This is to ensure proper review of all the code. > > Fork the project, create a feature branch, and send us a pull request. > > To ensure a consistent code base, you should make sure the code follows > the [PSR-2 Coding Standards](http://www.php-fig.org/psr/psr-2/). ## IRC / mailing list Mailing lists for [user support](https://groups.google.com/group/composer-users) and [development](https://groups.google.com/group/composer-dev). IRC channels are on irc.freenode.org: [#composer](irc://irc.freenode.org/composer) for users and [#composer-dev](irc://irc.freenode.org/composer-dev) for development. Stack Overflow has a growing collection of [Composer related questions](https://stackoverflow.com/questions/tagged/composer-php). ← [Config](06-config.md) composer-1.6.3/doc/articles/000077500000000000000000000000001323436022200157205ustar00rootroot00000000000000composer-1.6.3/doc/articles/aliases.md000066400000000000000000000073751323436022200176770ustar00rootroot00000000000000 # Aliases ## Why aliases? When you are using a VCS repository, you will only get comparable versions for branches that look like versions, such as `2.0` or `2.0.x`. For your `master` branch, you will get a `dev-master` version. For your `bugfix` branch, you will get a `dev-bugfix` version. If your `master` branch is used to tag releases of the `1.0` development line, i.e. `1.0.1`, `1.0.2`, `1.0.3`, etc., any package depending on it will probably require version `1.0.*`. If anyone wants to require the latest `dev-master`, they have a problem: Other packages may require `1.0.*`, so requiring that dev version will lead to conflicts, since `dev-master` does not match the `1.0.*` constraint. Enter aliases. ## Branch alias The `dev-master` branch is one in your main VCS repo. It is rather common that someone will want the latest master dev version. Thus, Composer allows you to alias your `dev-master` branch to a `1.0.x-dev` version. It is done by specifying a `branch-alias` field under `extra` in `composer.json`: ```json { "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } } } ``` If you alias a non-comparable version (such as dev-develop) `dev-` must prefix the branch name. You may also alias a comparable version (i.e. start with numbers, and end with `.x-dev`), but only as a more specific version. For example, 1.x-dev could be aliased as 1.2.x-dev. The alias must be a comparable dev version, and the `branch-alias` must be present on the branch that it references. For `dev-master`, you need to commit it on the `master` branch. As a result, anyone can now require `1.0.*` and it will happily install `dev-master`. In order to use branch aliasing, you must own the repository of the package being aliased. If you want to alias a third party package without maintaining a fork of it, use inline aliases as described below. ## Require inline alias Branch aliases are great for aliasing main development lines. But in order to use them you need to have control over the source repository, and you need to commit changes to version control. This is not really fun when you just want to try a bugfix of some library that is a dependency of your local project. For this reason, you can alias packages in your `require` and `require-dev` fields. Let's say you found a bug in the `monolog/monolog` package. You cloned [Monolog](https://github.com/Seldaek/monolog) on GitHub and fixed the issue in a branch named `bugfix`. Now you want to install that version of monolog in your local project. You are using `symfony/monolog-bundle` which requires `monolog/monolog` version `1.*`. So you need your `dev-bugfix` to match that constraint. Just add this to your project's root `composer.json`: ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/you/monolog" } ], "require": { "symfony/monolog-bundle": "2.0", "monolog/monolog": "dev-bugfix as 1.0.x-dev" } } ``` That will fetch the `dev-bugfix` version of `monolog/monolog` from your GitHub and alias it to `1.0.x-dev`. > **Note:** If a package with inline aliases is required, the alias (right of > the `as`) is used as the version constraint. The part left of the `as` is > discarded. As a consequence, if A requires B and B requires `monolog/monolog` > version `dev-bugfix as 1.0.x-dev`, installing A will make B require > `1.0.x-dev`, which may exist as a branch alias or an actual `1.0` branch. If > it does not, it must be re-inline-aliased in A's `composer.json`. > **Note:** Inline aliasing should be avoided, especially for published > packages. If you found a bug, try and get your fix merged upstream. This > helps to avoid issues for users of your package. composer-1.6.3/doc/articles/autoloader-optimization.md000066400000000000000000000105531323436022200231310ustar00rootroot00000000000000 # Autoloader Optimization By default, the Composer autoloader runs relatively fast. However, due to the way PSR-4 and PSR-0 autoloading rules are set up, it needs to check the filesystem before resolving a classname conclusively. This slows things down quite a bit, but it is convenient in development environments because when you add a new class it can immediately be discovered/used without having to rebuild the autoloader configuration. The problem however is in production you generally want things to happen as fast as possible, as you can simply rebuild the configuration every time you deploy and new classes do not appear at random between deploys. For this reason, Composer offers a few strategies to optimize the autoloader. > **Note:** You **should not** enable any of these optimizations in **development** as > they all will cause various problems when adding/removing classes. The performance > gains are not worth the trouble in a development setting. ## Optimization Level 1: Class map generation ### How to run it? There are a few options to enable this: - Set `"optimize-autoloader": true` inside the config key of composer.json - Call `install` or `update` with `-o` / `--optimize-autoloader` - Call `dump-autoload` with `-o` / `--optimize` ### What does it do? Class map generation essentially converts PSR-4/PSR-0 rules into classmap rules. This makes everything quite a bit faster as for known classes the class map returns instantly the path, and Composer can guarantee the class is in there so there is no filesystem check needed. On PHP 5.6+, the class map is also cached in opcache which improves the initialization time greatly. If you make sure opcache is enabled, then the class map should load almost instantly and then class loading is fast. ### Trade-offs There are no real trade-offs with this method. It should always be enabled in production. The only issue is it does not keep track of autoload misses (i.e. when it can not find a given class), so those fallback to PSR-4 rules and can still result in slow filesystem checks. To solve this issue two Level 2 optimization options exist, and you can decide to enable either if you have a lot of class_exists checks that are done for classes that do not exist in your project. ## Optimization Level 2/A: Authoritative class maps ### How to run it? There are a few options to enable this: - Set `"classmap-authoritative": true` inside the config key of composer.json - Call `install` or `update` with `-a` / `--classmap-authoritative` - Call `dump-autoload` with `-a` / `--classmap-authoritative` ### What does it do? Enabling this automatically enables Level 1 class map optimizations. This option is very simple, it says that if something is not found in the classmap, then it does not exist and the autoloader should not attempt to look on the filesystem according to PSR-4 rules. ### Trade-offs This option makes the autoloader always return very quickly. On the flipside it also means that in case a class is generated at runtime for some reason, it will not be allowed to be autoloaded. If your project or any of your dependencies does that then you might experience "class not found" issues in production. Enable this with care. > Note: This can not be combined with Level 2/B optimizations. You have to choose one as > they address the same issue in different ways. ## Optimization Level 2/B: APCu cache ### How to run it? There are a few options to enable this: - Set `"apcu-autoloader": true` inside the config key of composer.json - Call `install` or `update` with `--apcu-autoloader` - Call `dump-autoload` with `--apcu` ### What does it do? This option adds an APCu cache as a fallback for the class map. It will not automatically generate the class map though, so you should still enable Level 1 optimizations manually if you so desire. Whether a class is found or not, that fact is always cached in APCu so it can be returned quickly on the next request. ### Trade-offs This option requires APCu which may or may not be available to you. It also uses APCu memory for autoloading purposes, but it is safe to use and can not result in classes not being found like the authoritative class map optimization above. > Note: This can not be combined with Level 2/A optimizations. You have to choose one as > they address the same issue in different ways. composer-1.6.3/doc/articles/custom-installers.md000066400000000000000000000151571323436022200217430ustar00rootroot00000000000000 # Setting up and using custom installers ## Synopsis At times it may be necessary for a package to require additional actions during installation, such as installing packages outside of the default `vendor` library. In these cases you could consider creating a Custom Installer to handle your specific logic. ## Calling a Custom Installer Suppose that your project already has a Custom Installer for specific modules then invoking that installer is a matter of defining the correct [type][1] in your package file. > _See the next chapter for an instruction how to create Custom Installers._ Every Custom Installer defines which [type][1] string it will recognize. Once recognized it will completely override the default installer and only apply its own logic. An example use-case would be: > phpDocumentor features Templates that need to be installed outside of the > default /vendor folder structure. As such they have chosen to adopt the > `phpdocumentor-template` [type][1] and create a plugin providing the Custom > Installer to send these templates to the correct folder. An example composer.json of such a template package would be: ```json { "name": "phpdocumentor/template-responsive", "type": "phpdocumentor-template", "require": { "phpdocumentor/template-installer-plugin": "*" } } ``` > **IMPORTANT**: to make sure that the template installer is present at the > time the template package is installed, template packages should require > the plugin package. ## Creating an Installer A Custom Installer is defined as a class that implements the [`Composer\Installer\InstallerInterface`][4] and is usually distributed in a Composer Plugin. A basic Installer Plugin would thus compose of three files: 1. the package file: composer.json 2. The Plugin class, e.g.: `My\Project\Composer\Plugin.php`, containing a class that implements `Composer\Plugin\PluginInterface`. 3. The Installer class, e.g.: `My\Project\Composer\Installer.php`, containing a class that implements `Composer\Installer\InstallerInterface`. ### composer.json The package file is the same as any other package file but with the following requirements: 1. the [type][1] attribute must be `composer-plugin`. 2. the [extra][2] attribute must contain an element `class` defining the class name of the plugin (including namespace). If a package contains multiple plugins this can be array of class names. Example: ```json { "name": "phpdocumentor/template-installer-plugin", "type": "composer-plugin", "license": "MIT", "autoload": { "psr-0": {"phpDocumentor\\Composer": "src/"} }, "extra": { "class": "phpDocumentor\\Composer\\TemplateInstallerPlugin" }, "require": { "composer-plugin-api": "^1.0" }, "require-dev": { "composer/composer": "^1.3" } } ``` The example above has Composer itself in its require-dev, which allows you to use the Composer classes in your test suite for example. ### The Plugin class The class defining the Composer plugin must implement the [`Composer\Plugin\PluginInterface`][3]. It can then register the Custom Installer in its `activate()` method. The class may be placed in any location and have any name, as long as it is autoloadable and matches the `extra.class` element in the package definition. Example: ```php getInstallationManager()->addInstaller($installer); } } ``` ### The Custom Installer class The class that executes the custom installation should implement the [`Composer\Installer\InstallerInterface`][4] (or extend another installer that implements that interface). It defines the [type][1] string as it will be recognized by packages that will use this installer in the `supports()` method. > **NOTE**: _choose your [type][1] name carefully, it is recommended to follow > the format: `vendor-type`_. For example: `phpdocumentor-template`. The InstallerInterface class defines the following methods (please see the source for the exact signature): * **supports()**, here you test whether the passed [type][1] matches the name that you declared for this installer (see the example). * **isInstalled()**, determines whether a supported package is installed or not. * **install()**, here you can determine the actions that need to be executed upon installation. * **update()**, here you define the behavior that is required when Composer is invoked with the update argument. * **uninstall()**, here you can determine the actions that need to be executed when the package needs to be removed. * **getInstallPath()**, this method should return the location where the package is to be installed, _relative from the location of composer.json._ Example: ```php getPrettyName(), 0, 23); if ('phpdocumentor/template-' !== $prefix) { throw new \InvalidArgumentException( 'Unable to install template, phpdocumentor templates ' .'should always start their package name with ' .'"phpdocumentor/template-"' ); } return 'data/templates/'.substr($package->getPrettyName(), 23); } /** * {@inheritDoc} */ public function supports($packageType) { return 'phpdocumentor-template' === $packageType; } } ``` The example demonstrates that it is quite simple to extend the [`Composer\Installer\LibraryInstaller`][5] class to strip a prefix (`phpdocumentor/template-`) and use the remaining part to assemble a completely different installation path. > _Instead of being installed in `/vendor` any package installed using this > Installer will be put in the `/data/templates/` folder._ [1]: ../04-schema.md#type [2]: ../04-schema.md#extra [3]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/PluginInterface.php [4]: https://github.com/composer/composer/blob/master/src/Composer/Installer/InstallerInterface.php [5]: https://github.com/composer/composer/blob/master/src/Composer/Installer/LibraryInstaller.php composer-1.6.3/doc/articles/handling-private-packages-with-satis.md000066400000000000000000000303161323436022200253470ustar00rootroot00000000000000 # Handling private packages # Private Packagist [Private Packagist](https://packagist.com) is a commercial package hosting product offering professional support and web based management of private and public packages, and granular access permissions. Private Packagist provides mirroring for packages' zip files which makes installs faster and independent from third party systems - e.g. you can deploy even if GitHub is down because your zip files are mirrored. Private Packagist is available as a hosted SaaS solution or as an on-premise self-hosted package, providing an easy interactive set up experience. Some of Private Packagist's revenue is used to pay for Composer and Packagist.org development and hosting so using it is a good way to support the maintenance of these open source projects financially. You can find more information about how to set up your own package archive on [Packagist.com](https://packagist.com). # Satis Satis on the other hand is open source but only a static `composer` repository generator. It is a bit like an ultra-lightweight, static file-based version of packagist and can be used to host the metadata of your company's private packages, or your own. You can get it from [GitHub](https://github.com/composer/satis) or install via CLI: php composer.phar create-project composer/satis --stability=dev --keep-vcs ## Setup For example let's assume you have a few packages you want to reuse across your company but don't really want to open-source. You would first define a Satis configuration: a json file with an arbitrary name that lists your curated [repositories](../05-repositories.md). Here is an example configuration, you see that it holds a few VCS repositories, but those could be any types of [repositories](../05-repositories.md). Then it uses `"require-all": true` which selects all versions of all packages in the repositories you defined. The default file Satis looks for is `satis.json` in the root of the repository. ```json { "name": "My Repository", "homepage": "http://packages.example.org", "repositories": [ { "type": "vcs", "url": "https://github.com/mycompany/privaterepo" }, { "type": "vcs", "url": "http://svn.example.org/private/repo" }, { "type": "vcs", "url": "https://github.com/mycompany/privaterepo2" } ], "require-all": true } ``` If you want to cherry pick which packages you want, you can list all the packages you want to have in your satis repository inside the classic composer `require` key, using a `"*"` constraint to make sure all versions are selected, or another constraint if you want really specific versions. ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/mycompany/privaterepo" }, { "type": "vcs", "url": "http://svn.example.org/private/repo" }, { "type": "vcs", "url": "https://github.com/mycompany/privaterepo2" } ], "require": { "company/package": "*", "company/package2": "*", "company/package3": "2.0.0" } } ``` Once you've done this, you just run: php bin/satis build When you ironed out that process, what you would typically do is run this command as a cron job on a server. It would then update all your package info much like Packagist does. Note that if your private packages are hosted on GitHub, your server should have an ssh key that gives it access to those packages, and then you should add the `--no-interaction` (or `-n`) flag to the command to make sure it falls back to ssh key authentication instead of prompting for a password. This is also a good trick for continuous integration servers. Set up a virtual-host that points to that `web/` directory, let's say it is `packages.example.org`. Alternatively, with PHP >= 5.4.0, you can use the built-in CLI server `php -S localhost:port -t satis-output-dir/` for a temporary solution. ### Partial Updates You can tell Satis to selectively update only particular packages or process only a repository with a given URL. This cuts down the time it takes to rebuild the `package.json` file and is helpful if you use (custom) webhooks to trigger rebuilds whenever code is pushed into one of your repositories. To rebuild only particular packages, pass the package names on the command line like so: php bin/satis build satis.json web/ this/package that/other-package Note that this will still need to pull and scan all of your VCS repositories because any VCS repository might contain (on any branch) one of the selected packages. If you want to scan only a single repository and update all packages found in it, pass the VCS repository URL as an optional argument: php bin/satis build --repository-url https://only.my/repo.git satis.json web/ ## Usage In your projects all you need to add now is your own composer repository using the `packages.example.org` as URL, then you can require your private packages and everything should work smoothly. You don't need to copy all your repositories in every project anymore. Only that one unique repository that will update itself. ```json { "repositories": [ { "type": "composer", "url": "http://packages.example.org/" } ], "require": { "company/package": "1.2.0", "company/package2": "1.5.2", "company/package3": "dev-master" } } ``` ### Security To secure your private repository you can host it over SSH or SSL using a client certificate. In your project you can use the `options` parameter to specify the connection options for the server. Example using a custom repository using SSH (requires the SSH2 PECL extension): ```json { "repositories": [{ "type": "composer", "url": "ssh2.sftp://example.org", "options": { "ssh2": { "username": "composer", "pubkey_file": "/home/composer/.ssh/id_rsa.pub", "privkey_file": "/home/composer/.ssh/id_rsa" } } }] } ``` > **Tip:** See [ssh2 context options] for more information. Example using SSL/TLS (HTTPS) using a client certificate: ```json { "repositories": [{ "type": "composer", "url": "https://example.org", "options": { "ssl": { "local_cert": "/home/composer/.ssl/composer.pem" } } }] } ``` > **Tip:** See [ssl context options] for more information. Example using a custom HTTP Header field for token authentication: ```json { "repositories": [{ "type": "composer", "url": "https://example.org", "options": { "http": { "header": [ "API-TOKEN: YOUR-API-TOKEN" ] } } }] } ``` ### Authentication When your private repositories are password protected, you can store the authentication details permanently. The first time Composer needs to authenticate against some domain it will prompt you for a username/password and then you will be asked whether you want to store it. The storage can be done either globally in the `COMPOSER_HOME/auth.json` file (`COMPOSER_HOME` defaults to `~/.composer` or `%APPDATA%/Composer` on Windows) or also in the project directory directly sitting besides your composer.json. You can also configure these by hand using the config command if you need to configure a production machine to be able to run non-interactive installs. For example to enter credentials for example.org one could type: composer config http-basic.example.org username password That will store it in the current directory's auth.json, but if you want it available globally you can use the `--global` (`-g`) flag. ### Downloads When GitHub, GitLab or BitBucket repositories are mirrored on your local satis, the build process will include the location of the downloads these platforms make available. This means that the repository and your setup depend on the availability of these services. At the same time, this implies that all code which is hosted somewhere else (on another service or for example in Subversion) will not have downloads available and thus installations usually take a lot longer. To enable your satis installation to create downloads for all (Git, Mercurial and Subversion) your packages, add the following to your `satis.json`: ``` json { "archive": { "directory": "dist", "format": "tar", "prefix-url": "https://amazing.cdn.example.org", "skip-dev": true } } ``` #### Options explained * `directory`: required, the location of the dist files (inside the `output-dir`) * `format`: optional, `zip` (default) or `tar` * `prefix-url`: optional, location of the downloads, homepage (from `satis.json`) followed by `directory` by default * `skip-dev`: optional, `false` by default, when enabled (`true`) satis will not create downloads for branches * `absolute-directory`: optional, a _local_ directory where the dist files are dumped instead of `output-dir`/`directory` * `whitelist`: optional, if set as a list of package names, satis will only dump the dist files of these packages * `blacklist`: optional, if set as a list of package names, satis will not dump the dist files of these packages * `checksum`: optional, `true` by default, when disabled (`false`) satis will not provide the sha1 checksum for the dist files Once enabled, all downloads (include those from GitHub and BitBucket) will be replaced with a _local_ version. #### prefix-url Prefixing the URL with another host is especially helpful if the downloads end up in a private Amazon S3 bucket or on a CDN host. A CDN would drastically improve download times and therefore package installation. Example: A `prefix-url` of `https://my-bucket.s3.amazonaws.com` (and `directory` set to `dist`) creates download URLs which look like the following: `https://my-bucket.s3.amazonaws.com/dist/vendor-package-version-ref.zip`. ### Web outputs * `output-html`: optional, `true` by default, when disabled (`false`) satis will not generate the `output-dir`/index.html page. * `twig-template`: optional, a path to a personalized [Twig] template for the `output-dir`/index.html page. ### Abandoned packages To enable your satis installation to indicate that some packages are abandoned, add the following to your `satis.json`: ```json { "abandoned": { "company/package": true, "company/package2": "company/newpackage" } } ``` The `true` value indicates that the package is truly abandoned while the `"company/newpackage"` value specifies that the package is replaced by the `company/newpackage` package. Note that all packages set as abandoned in their own `composer.json` file will be marked abandoned as well. ### Resolving dependencies It is possible to make satis automatically resolve and add all dependencies for your projects. This can be used with the Downloads functionality to have a complete local mirror of packages. Just add the following to your `satis.json`: ```json { "require-dependencies": true, "require-dev-dependencies": true } ``` When searching for packages, satis will attempt to resolve all the required packages from the listed repositories. Therefore, if you are requiring a package from Packagist, you will need to define it in your `satis.json`. Dev dependencies are packaged only if the `require-dev-dependencies` parameter is set to true. ### Other options * `providers`: optional, `false` by default, when enabled (`true`) each package will be dumped into a separate include file which will be only loaded by composer when the package is really required. Speeds up composer handling for repositories with huge number of packages like f.i. packagist. * `output-dir`: optional, defines where to output the repository files if not provided as an argument when calling the `build` command. * `config`: optional, lets you define all config options from composer, except `archive-format` and `archive-dir` as the configuration is done through [archive](#downloads) instead. See docs on [config schema] for more details. * `notify-batch`: optional, specify a URL that will be called every time a user installs a package. See [notify-batch]. [ssh2 context options]: https://secure.php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-options [ssl context options]: https://secure.php.net/manual/en/context.ssl.php [Twig]: https://twig.sensiolabs.org/ [config schema]: https://getcomposer.org/doc/04-schema.md#config [notify-batch]: https://getcomposer.org/doc/05-repositories.md#notify-batch composer-1.6.3/doc/articles/http-basic-authentication.md000066400000000000000000000035231323436022200233200ustar00rootroot00000000000000 # HTTP basic authentication Your [Satis or Toran Proxy](handling-private-packages-with-satis.md) server could be secured with http basic authentication. In order to allow your project to have access to these packages you will have to tell composer how to authenticate with your credentials. The simplest way to provide your credentials is providing your set of credentials inline with the repository specification such as: ```json { "repositories": [ { "type": "composer", "url": "https://extremely:secret@repo.example.org" } ] } ``` This will basically teach composer how to authenticate automatically when reading packages from the provided composer repository. This does not work for everybody especially when you don't want to hard code your credentials into your composer.json. There is a second way to provide these details and it is via interaction. If you don't provide the authentication credentials composer will prompt you upon connection to enter the username and password. The third way if you want to pre-configure it is via an `auth.json` file located in your `COMPOSER_HOME` or besides your `composer.json`. The file should contain a set of hostnames followed each with their own username/password pairs, for example: ```json { "http-basic": { "repo.example1.org": { "username": "my-username1", "password": "my-secret-password1" }, "repo.example2.org": { "username": "my-username2", "password": "my-secret-password2" } } } ``` The main advantage of the auth.json file is that it can be gitignored so that every developer in your team can place their own credentials in there, which makes revocation of credentials much easier than if you all share the same. composer-1.6.3/doc/articles/plugins.md000066400000000000000000000207721323436022200177330ustar00rootroot00000000000000 # Setting up and using plugins ## Synopsis You may wish to alter or expand Composer's functionality with your own. For example if your environment poses special requirements on the behaviour of Composer which do not apply to the majority of its users or if you wish to accomplish something with composer in a way that is not desired by most users. In these cases you could consider creating a plugin to handle your specific logic. ## Creating a Plugin A plugin is a regular Composer package which ships its code as part of the package and may also depend on further packages. ### Plugin Package The package file is the same as any other package file but with the following requirements: 1. The [type][1] attribute must be `composer-plugin`. 2. The [extra][2] attribute must contain an element `class` defining the class name of the plugin (including namespace). If a package contains multiple plugins, this can be array of class names. 3. You must require the special package called `composer-plugin-api` to define which Plugin API versions your plugin is compatible with. The required version of the `composer-plugin-api` follows the same [rules][7] as a normal package's. The current composer plugin API version is 1.1.0. An example of a valid plugin `composer.json` file (with the autoloading part omitted): ```json { "name": "my/plugin-package", "type": "composer-plugin", "require": { "composer-plugin-api": "^1.1" }, "extra": { "class": "My\\Plugin" } } ``` ### Plugin Class Every plugin has to supply a class which implements the [`Composer\Plugin\PluginInterface`][3]. The `activate()` method of the plugin is called after the plugin is loaded and receives an instance of [`Composer\Composer`][4] as well as an instance of [`Composer\IO\IOInterface`][5]. Using these two objects all configuration can be read and all internal objects and state can be manipulated as desired. Example: ```php getInstallationManager()->addInstaller($installer); } } ``` ## Event Handler Furthermore plugins may implement the [`Composer\EventDispatcher\EventSubscriberInterface`][6] in order to have its event handlers automatically registered with the `EventDispatcher` when the plugin is loaded. To register a method to an event, implement the method `getSubscribedEvents()` and have it return an array. The array key must be the [event name](https://getcomposer.org/doc/articles/scripts.md#event-names) and the value is the name of the method in this class to be called. ```php public static function getSubscribedEvents() { return array( 'post-autoload-dump' => 'methodToBeCalled', // ^ event name ^ ^ method name ^ ); } ``` By default, the priority of an event handler is set to 0. The priority can be changed by attaching a tuple where the first value is the method name, as before, and the second value is an integer representing the priority. Higher integers represent higher priorities. Priority 2 is called before priority 1, etc. ```php public static function getSubscribedEvents() { return array( // Will be called before events with priority 0 'post-autoload-dump' => array('methodToBeCalled', 1) ); } ``` If multiple methods should be called, then an array of tuples can be attached to each event. The tuples do not need to include the priority. If it is omitted, it will default to 0. ```php public static function getSubscribedEvents() { return array( 'post-autoload-dump' => array( array('methodToBeCalled' ), // Priority defaults to 0 array('someOtherMethodName', 1), // This fires first ) ); } ``` Here's a complete example: ```php composer = $composer; $this->io = $io; } public static function getSubscribedEvents() { return array( PluginEvents::PRE_FILE_DOWNLOAD => array( array('onPreFileDownload', 0) ), ); } public function onPreFileDownload(PreFileDownloadEvent $event) { $protocol = parse_url($event->getProcessedUrl(), PHP_URL_SCHEME); if ($protocol === 's3') { $awsClient = new AwsClient($this->io, $this->composer->getConfig()); $s3RemoteFilesystem = new S3RemoteFilesystem($this->io, $event->getRemoteFilesystem()->getOptions(), $awsClient); $event->setRemoteFilesystem($s3RemoteFilesystem); } } } ``` ## Plugin capabilities Composer defines a standard set of capabilities which may be implemented by plugins. Their goal is to make the plugin ecosystem more stable as it reduces the need to mess with [`Composer\Composer`][4]'s internal state, by providing explicit extension points for common plugin requirements. Capable Plugins classes must implement the [`Composer\Plugin\Capable`][8] interface and declare their capabilities in the `getCapabilities()` method. This method must return an array, with the _key_ as a Composer Capability class name, and the _value_ as the Plugin's own implementation class name of said Capability: ```php 'My\Composer\CommandProvider', ); } } ``` ### Command provider The [`Composer\Plugin\Capability\CommandProvider`][9] capability allows to register additional commands for Composer : ```php setName('custom-plugin-command'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Executing'); } } ``` Now the `custom-plugin-command` is available alongside Composer commands. > _Composer commands are based on the [Symfony Console Component][10]._ ## Using Plugins Plugin packages are automatically loaded as soon as they are installed and will be loaded when composer starts up if they are found in the current project's list of installed packages. Additionally all plugin packages installed in the `COMPOSER_HOME` directory using the composer global command are loaded before local project plugins are loaded. > You may pass the `--no-plugins` option to composer commands to disable all > installed plugins. This may be particularly helpful if any of the plugins > causes errors and you wish to update or uninstall it. [1]: ../04-schema.md#type [2]: ../04-schema.md#extra [3]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/PluginInterface.php [4]: https://github.com/composer/composer/blob/master/src/Composer/Composer.php [5]: https://github.com/composer/composer/blob/master/src/Composer/IO/IOInterface.php [6]: https://github.com/composer/composer/blob/master/src/Composer/EventDispatcher/EventSubscriberInterface.php [7]: ../01-basic-usage.md#package-versions [8]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/Capable.php [9]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/Capability/CommandProvider.php [10]: https://symfony.com/doc/current/components/console.html composer-1.6.3/doc/articles/scripts.md000066400000000000000000000236161323436022200177410ustar00rootroot00000000000000 # Scripts ## What is a script? A script, in Composer's terms, can either be a PHP callback (defined as a static method) or any command-line executable command. Scripts are useful for executing a package's custom code or package-specific commands during the Composer execution process. > **Note:** Only scripts defined in the root package's `composer.json` are > executed. If a dependency of the root package specifies its own scripts, > Composer does not execute those additional scripts. ## Event names Composer fires the following named events during its execution process: ### Command Events - **pre-install-cmd**: occurs before the `install` command is executed with a lock file present. - **post-install-cmd**: occurs after the `install` command has been executed with a lock file present. - **pre-update-cmd**: occurs before the `update` command is executed, or before the `install` command is executed without a lock file present. - **post-update-cmd**: occurs after the `update` command has been executed, or after the `install` command has been executed without a lock file present. - **post-status-cmd**: occurs after the `status` command has been executed. - **pre-archive-cmd**: occurs before the `archive` command is executed. - **post-archive-cmd**: occurs after the `archive` command has been executed. - **pre-autoload-dump**: occurs before the autoloader is dumped, either during `install`/`update`, or via the `dump-autoload` command. - **post-autoload-dump**: occurs after the autoloader has been dumped, either during `install`/`update`, or via the `dump-autoload` command. - **post-root-package-install**: occurs after the root package has been installed, during the `create-project` command. - **post-create-project-cmd**: occurs after the `create-project` command has been executed. ### Installer Events - **pre-dependencies-solving**: occurs before the dependencies are resolved. - **post-dependencies-solving**: occurs after the dependencies have been resolved. ### Package Events - **pre-package-install**: occurs before a package is installed. - **post-package-install**: occurs after a package has been installed. - **pre-package-update**: occurs before a package is updated. - **post-package-update**: occurs after a package has been updated. - **pre-package-uninstall**: occurs before a package is uninstalled. - **post-package-uninstall**: occurs after a package has been uninstalled. ### Plugin Events - **init**: occurs after a Composer instance is done being initialized. - **command**: occurs before any Composer Command is executed on the CLI. It provides you with access to the input and output objects of the program. - **pre-file-download**: occurs before files are downloaded and allows you to manipulate the `RemoteFilesystem` object prior to downloading files based on the URL to be downloaded. > **Note:** Composer makes no assumptions about the state of your dependencies > prior to `install` or `update`. Therefore, you should not specify scripts > that require Composer-managed dependencies in the `pre-update-cmd` or > `pre-install-cmd` event hooks. If you need to execute scripts prior to > `install` or `update` please make sure they are self-contained within your > root package. ## Defining scripts The root JSON object in `composer.json` should have a property called `"scripts"`, which contains pairs of named events and each event's corresponding scripts. An event's scripts can be defined as either a string (only for a single script) or an array (for single or multiple scripts.) For any given event: - Scripts execute in the order defined when their corresponding event is fired. - An array of scripts wired to a single event can contain both PHP callbacks and command-line executable commands. - PHP classes containing defined callbacks must be autoloadable via Composer's autoload functionality. - Callbacks can only autoload classes from psr-0, psr-4 and classmap definitions. If a defined callback relies on functions defined outside of a class, the callback itself is responsible for loading the file containing these functions. Script definition example: ```json { "scripts": { "post-update-cmd": "MyVendor\\MyClass::postUpdate", "post-package-install": [ "MyVendor\\MyClass::postPackageInstall" ], "post-install-cmd": [ "MyVendor\\MyClass::warmCache", "phpunit -c app/" ], "post-autoload-dump": [ "MyVendor\\MyClass::postAutoloadDump" ], "post-create-project-cmd": [ "php -r \"copy('config/local-example.php', 'config/local.php');\"" ] } } ``` Using the previous definition example, here's the class `MyVendor\MyClass` that might be used to execute the PHP callbacks: ```php getComposer(); // do stuff } public static function postAutoloadDump(Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); require $vendorDir . '/autoload.php'; some_function_from_an_autoloaded_file(); } public static function postPackageInstall(PackageEvent $event) { $installedPackage = $event->getOperation()->getPackage(); // do stuff } public static function warmCache(Event $event) { // make cache toasty } } ``` **Note:** During a composer install or update process, a variable named `COMPOSER_DEV_MODE` will be added to the environment. If the command was run with the `--no-dev` flag, this variable will be set to 0, otherwise it will be set to 1. ## Event classes When an event is fired, your PHP callback receives as first argument a `Composer\EventDispatcher\Event` object. This object has a `getName()` method that lets you retrieve the event name. Depending on the [script types](#event-names) you will get various event subclasses containing various getters with relevant data and associated objects: - Base class: [`Composer\EventDispatcher\Event`](https://getcomposer.org/apidoc/master/Composer/EventDispatcher/Event.html) - Command Events: [`Composer\Script\Event`](https://getcomposer.org/apidoc/master/Composer/Script/Event.html) - Installer Events: [`Composer\Installer\InstallerEvent`](https://getcomposer.org/apidoc/master/Composer/Installer/InstallerEvent.html) - Package Events: [`Composer\Installer\PackageEvent`](https://getcomposer.org/apidoc/master/Composer/Installer/PackageEvent.html) - Plugin Events: - init: [`Composer\EventDispatcher\Event`](https://getcomposer.org/apidoc/master/Composer/EventDispatcher/Event.html) - command: [`Composer\Plugin\CommandEvent`](https://getcomposer.org/apidoc/master/Composer/Plugin/CommandEvent.html) - pre-file-download: [`Composer\Plugin\PreFileDownloadEvent`](https://getcomposer.org/apidoc/master/Composer/Plugin/PreFileDownloadEvent.html) ## Running scripts manually If you would like to run the scripts for an event manually, the syntax is: ```sh composer run-script [--dev] [--no-dev] script ``` For example `composer run-script post-install-cmd` will run any **post-install-cmd** scripts that have been defined. You can also give additional arguments to the script handler by appending `--` followed by the handler arguments. e.g. `composer run-script post-install-cmd -- --check` will pass`--check` along to the script handler. Those arguments are received as CLI arg by CLI handlers, and can be retrieved as an array via `$event->getArguments()` by PHP handlers. ## Writing custom commands If you add custom scripts that do not fit one of the predefined event name above, you can either run them with run-script or also run them as native Composer commands. For example the handler defined below is executable by simply running `composer test`: ```json { "scripts": { "test": "phpunit" } } ``` Similar to the `run-script` command you can give additional arguments to scripts, e.g. `composer test -- --filter ` will pass `--filter ` along to the `phpunit` script. > **Note:** Before executing scripts, Composer's bin-dir is temporarily pushed > on top of the PATH environment variable so that binaries of dependencies > are easily accessible. In this example no matter if the `phpunit` binary is > actually in `vendor/bin/phpunit` or `bin/phpunit` it will be found and executed. ## Referencing scripts To enable script re-use and avoid duplicates, you can call a script from another one by prefixing the command name with `@`: ```json { "scripts": { "test": [ "@clearCache", "phpunit" ], "clearCache": "rm -rf cache/*" } } ``` ## Calling Composer commands To call Composer commands, you can use `@composer` which will automatically resolve to whatever composer.phar is currently being used: ```json { "scripts": { "test": [ "@composer install", "phpunit" ] } } ``` One limitation of this is that you can not call multiple composer commands in a row like `@composer install && @composer foo`. You must split them up in a JSON array of commands. ## Executing PHP scripts To execute PHP scripts, you can use `@php` which will automatically resolve to whatever php process is currently being used: ```json { "scripts": { "test": [ "@php script.php", "phpunit" ] } } ``` One limitation of this is that you can not call multiple commands in a row like `@php install && @php foo`. You must split them up in a JSON array of commands. ## Custom descriptions. You can set custom script descriptions with the following in your `composer.json`: ```json { "scripts-descriptions": { "test": "Run all tests!" } } ``` > **Note:** You can only set custom descriptions of custom commands. composer-1.6.3/doc/articles/troubleshooting.md000066400000000000000000000274101323436022200214750ustar00rootroot00000000000000 # Troubleshooting This is a list of common pitfalls on using Composer, and how to avoid them. ## General 1. Before asking anyone, run [`composer diagnose`](../03-cli.md#diagnose) to check for common problems. If it all checks out, proceed to the next steps. 2. When facing any kind of problems using Composer, be sure to **work with the latest version**. See [self-update](../03-cli.md#self-update) for details. 3. Make sure you have no problems with your setup by running the installer's checks via `curl -sS https://getcomposer.org/installer | php -- --check`. 4. Ensure you're **installing vendors straight from your `composer.json`** via `rm -rf vendor && composer update -v` when troubleshooting, excluding any possible interferences with existing vendor installations or `composer.lock` entries. 5. Try clearing Composer's cache by running `composer clear-cache`. ## Package not found 1. Double-check you **don't have typos** in your `composer.json` or repository branches and tag names. 2. Be sure to **set the right [minimum-stability](../04-schema.md#minimum-stability)**. To get started or be sure this is no issue, set `minimum-stability` to "dev". 3. Packages **not coming from [Packagist](https://packagist.org/)** should always be **defined in the root package** (the package depending on all vendors). 4. Use the **same vendor and package name** throughout all branches and tags of your repository, especially when maintaining a third party fork and using `replace`. 5. If you are updating to a recently published version of a package, be aware that Packagist has a delay of up to 1 minute before new packages are visible to Composer. 6. If you are updating a single package, it may depend on newer versions itself. In this case add the `--with-dependencies` argument **or** add all dependencies which need an update to the command. ## Package not found on travis-ci.org 1. Check the ["Package not found"](#package-not-found) item above. 2. If the package tested is a dependency of one of its dependencies (cyclic dependency), the problem might be that Composer is not able to detect the version of the package properly. If it is a git clone it is generally alright and Composer will detect the version of the current branch, but travis does shallow clones so that process can fail when testing pull requests and feature branches in general. The best solution is to define the version you are on via an environment variable called COMPOSER_ROOT_VERSION. You set it to `dev-master` for example to define the root package's version as `dev-master`. Use: `before_script: COMPOSER_ROOT_VERSION=dev-master composer install` to export the variable for the call to composer. ## Package not found in a Jenkins-build 1. Check the ["Package not found"](#package-not-found) item above. 2. Reason for failing is similar to the problem which can occur on travis-ci.org: The git-clone / checkout within Jenkins leaves the branch in a "detached HEAD"-state. As a result, Composer is not able to identify the version of the current checked out branch and may not be able to resolve a cyclic dependency. To solve this problem, you can use the "Additional Behaviours" -> "Check out to specific local branch" in your Git-settings for your Jenkins-job, where your "local branch" shall be the same branch as you are checking out. Using this, the checkout will not be in detached state any more and cyclic dependency is recognized correctly. ## I have a dependency which contains a "repositories" definition in its composer.json, but it seems to be ignored. The [`repositories`](../04-schema.md#repositories) configuration property is defined as [root-only](../04-schema.md#root-package). It is not inherited. You can read more about the reasons behind this in the "[why can't composer load repositories recursively?](../faqs/why-can't-composer-load-repositories-recursively.md)" article. The simplest work-around to this limitation, is moving or duplicating the `repositories` definition into your root composer.json. ## I have locked a dependency to a specific commit but get unexpected results. While Composer supports locking dependencies to a specific commit using the `#commit-ref` syntax, there are certain caveats that one should take into account. The most important one is [documented](../04-schema.md#package-links), but frequently overlooked: > **Note:** While this is convenient at times, it should not be how you use > packages in the long term because it comes with a technical limitation. The > composer.json metadata will still be read from the branch name you specify > before the hash. Because of that in some cases it will not be a practical > workaround, and you should always try to switch to tagged releases as soon > as you can. There is no simple work-around to this limitation. It is therefore strongly recommended that you do not use it. ## Need to override a package version Let's say your project depends on package A, which in turn depends on a specific version of package B (say 0.1). But you need a different version of said package B (say 0.11). You can fix this by aliasing version 0.11 to 0.1: composer.json: ```json { "require": { "A": "0.2", "B": "0.11 as 0.1" } } ``` See [aliases](aliases.md) for more information. ## Memory limit errors Composer may sometimes fail on some commands with this message: `PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>` In this case, the PHP `memory_limit` should be increased. > **Note:** Composer internally increases the `memory_limit` to `1.5G`. To get the current `memory_limit` value, run: ```sh php -r "echo ini_get('memory_limit').PHP_EOL;" ``` Try increasing the limit in your `php.ini` file (ex. `/etc/php5/cli/php.ini` for Debian-like systems): ```ini ; Use -1 for unlimited or define an explicit value like 2G memory_limit = -1 ``` Or, you can increase the limit with a command-line argument: ```sh php -d memory_limit=-1 composer.phar <...> ``` This issue can also happen on cPanel instances, when the shell fork bomb protection is activated. For more information, see the [documentation](https://documentation.cpanel.net/display/68Docs/Shell+Fork+Bomb+Protection) of the fork bomb feature on the cPanel site. ## Xdebug impact on Composer To improve performance when the xdebug extension is enabled, Composer automatically restarts PHP without it. You can override this behavior by using an environment variable: `COMPOSER_ALLOW_XDEBUG=1`. Composer will always show a warning if xdebug is being used, but you can override this with an environment variable: `COMPOSER_DISABLE_XDEBUG_WARN=1`. If you see this warning unexpectedly, then the restart process has failed: please report this [issue](https://github.com/composer/composer/issues). ## "The system cannot find the path specified" (Windows) 1. Open regedit. 2. Search for an `AutoRun` key inside `HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor`, `HKEY_CURRENT_USER\Software\Microsoft\Command Processor` or `HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Command Processor`. 3. Check if it contains any path to non-existent file, if it's the case, just remove them. ## API rate limit and OAuth tokens Because of GitHub's rate limits on their API it can happen that Composer prompts for authentication asking your username and password so it can go ahead with its work. If you would prefer not to provide your GitHub credentials to Composer you can manually create a token using the following procedure: 1. [Create](https://github.com/settings/tokens) an OAuth token on GitHub. [Read more](https://github.com/blog/1509-personal-api-tokens) on this. 2. Add it to the configuration running `composer config -g github-oauth.github.com ` Now Composer should install/update without asking for authentication. ## proc_open(): fork failed errors If composer shows proc_open() fork failed on some commands: `PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar` This could be happening because the VPS runs out of memory and has no Swap space enabled. ```sh free -m total used free shared buffers cached Mem: 2048 357 1690 0 0 237 -/+ buffers/cache: 119 1928 Swap: 0 0 0 ``` To enable the swap you can use for example: ```sh /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024 /sbin/mkswap /var/swap.1 /sbin/swapon /var/swap.1 ``` You can make a permanent swap file following this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04). ## Degraded Mode Due to some intermittent issues on Travis and other systems, we introduced a degraded network mode which helps Composer finish successfully but disables a few optimizations. This is enabled automatically when an issue is first detected. If you see this issue sporadically you probably don't have to worry (a slow or overloaded network can also cause those time outs), but if it appears repeatedly you might want to look at the options below to identify and resolve it. If you have been pointed to this page, you want to check a few things: - If you are using ESET antivirus, go in "Advanced Settings" and disable "HTTP-scanner" under "web access protection" - If you are using IPv6, try disabling it. If that solves your issues, get in touch with your ISP or server host, the problem is not at the Packagist level but in the routing rules between you and Packagist (i.e. the internet at large). The best way to get these fixed is raise awareness to the network engineers that have the power to fix it. Take a look at the next section for IPv6 workarounds. - If none of the above helped, please report the error. ## Operation timed out (IPv6 issues) You may run into errors if IPv6 is not configured correctly. A common error is: ``` The "https://getcomposer.org/version" file could not be downloaded: failed to open stream: Operation timed out ``` We recommend you fix your IPv6 setup. If that is not possible, you can try the following workarounds: **Workaround Linux:** On linux, it seems that running this command helps to make ipv4 traffic have a higher prio than ipv6, which is a better alternative than disabling ipv6 entirely: ```bash sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf" ``` **Workaround Windows:** On windows the only way is to disable ipv6 entirely I am afraid (either in windows or in your home router). **Workaround Mac OS X:** Get name of your network device: ```bash networksetup -listallnetworkservices ``` Disable IPv6 on that device (in this case "Wi-Fi"): ```bash networksetup -setv6off Wi-Fi ``` Run composer ... You can enable IPv6 again with: ```bash networksetup -setv6automatic Wi-Fi ``` That said, if this fixes your problem, please talk to your ISP about it to try and resolve the routing errors. That's the best way to get things resolved for everyone. ## Composer hangs with SSH ControlMaster When you try to install packages from a Git repository and you use the `ControlMaster` setting for your SSH connection, Composer might just hang endlessly and you see a `sh` process in the `defunct` state in your process list. The reason for this is a SSH Bug: https://bugzilla.mindrot.org/show_bug.cgi?id=1988 As a workaround, open a SSH connection to your Git host before running Composer: ```bash ssh -t git@mygitserver.tld composer update ``` See also https://github.com/composer/composer/issues/4180 for more information. ## Zip archives are not unpacked correctly. Composer can unpack zipballs using either a system-provided `unzip` utility or PHP's native `ZipArchive` class. The `ZipArchive` class is preferred on Windows. On other OSes where ZIP files can contain permissions and symlinks, the `unzip` utility is preferred. You're advised to install it if you need these features. composer-1.6.3/doc/articles/vendor-binaries.md000066400000000000000000000065151323436022200213400ustar00rootroot00000000000000 # Vendor binaries and the `vendor/bin` directory ## What is a vendor binary? Any command line script that a Composer package would like to pass along to a user who installs the package should be listed as a vendor binary. If a package contains other scripts that are not needed by the package users (like build or compile scripts) that code should not be listed as a vendor binary. ## How is it defined? It is defined by adding the `bin` key to a project's `composer.json`. It is specified as an array of files so multiple binaries can be added for any given project. ```json { "bin": ["bin/my-script", "bin/my-other-script"] } ``` ## What does defining a vendor binary in composer.json do? It instructs Composer to install the package's binaries to `vendor/bin` for any project that **depends** on that project. This is a convenient way to expose useful scripts that would otherwise be hidden deep in the `vendor/` directory. ## What happens when Composer is run on a composer.json that defines vendor binaries? For the binaries that a package defines directly, nothing happens. ## What happens when Composer is run on a composer.json that has dependencies with vendor binaries listed? Composer looks for the binaries defined in all of the dependencies. A symlink is created from each dependency's binaries to `vendor/bin`. Say package `my-vendor/project-a` has binaries setup like this: ```json { "name": "my-vendor/project-a", "bin": ["bin/project-a-bin"] } ``` Running `composer install` for this `composer.json` will not do anything with `bin/project-a-bin`. Say project `my-vendor/project-b` has requirements setup like this: ```json { "name": "my-vendor/project-b", "require": { "my-vendor/project-a": "*" } } ``` Running `composer install` for this `composer.json` will look at all of project-b's dependencies and install them to `vendor/bin`. In this case, Composer will make `vendor/my-vendor/project-a/bin/project-a-bin` available as `vendor/bin/project-a-bin`. On a Unix-like platform this is accomplished by creating a symlink. ## What about Windows and .bat files? Packages managed entirely by Composer do not *need* to contain any `.bat` files for Windows compatibility. Composer handles installation of binaries in a special way when run in a Windows environment: * A `.bat` file is generated automatically to reference the binary * A Unix-style proxy file with the same name as the binary is generated automatically (useful for Cygwin or Git Bash) Packages that need to support workflows that may not include Composer are welcome to maintain custom `.bat` files. In this case, the package should **not** list the `.bat` file as a binary as it is not needed. ## Can vendor binaries be installed somewhere other than vendor/bin? Yes, there are two ways an alternate vendor binary location can be specified: 1. Setting the `bin-dir` configuration setting in `composer.json` 1. Setting the environment variable `COMPOSER_BIN_DIR` An example of the former looks like this: ```json { "config": { "bin-dir": "scripts" } } ``` Running `composer install` for this `composer.json` will result in all of the vendor binaries being installed in `scripts/` instead of `vendor/bin/`. You can set `bin-dir` to `./` to put binaries in your project root. composer-1.6.3/doc/articles/versions.md000066400000000000000000000243221323436022200201150ustar00rootroot00000000000000 # Versions and constraints ## Composer Versions vs VCS Versions Because Composer is heavily geared toward utilizing version control systems like git, the term "version" can be a little ambiguous. In the sense of a version control system, a "version" is a specific set of files that contain specific data. In git terminology, this is a "ref", or a specific commit, which may be represented by a branch HEAD or a tag. When you check out that version in your VCS -- for example, tag `v1.1` or commit `e35fa0d` --, you're asking for a single, known set of files, and you always get the same files back. In Composer, what's often referred to casually as a version -- that is, the string that follows the package name in a require line (e.g., `~1.1` or `1.2.*`) -- is actually more specifically a version constraint. Composer uses version constraints to figure out which refs in a VCS it should be checking out (or simply to verify that a given library is acceptable in the case of a statically-maintained library with a `version` specification in `composer.json`). ## VCS Tags and Branches *For the following discussion, let's assume the following sample library repository:* ```sh ~/my-library$ git branch v1 v2 my-feature nother-feature ~/my-library$ git tag v1.0 v1.0.1 v1.0.2 v1.1-BETA v1.1-RC1 v1.1-RC2 v1.1 v1.1.1 v2.0-BETA v2.0-RC1 v2.0 v2.0.1 v2.0.2 ``` ### Tags Normally, Composer deals with tags (as opposed to branches -- if you don't know what this means, read up on [version control systems](https://en.wikipedia.org/wiki/Version_control#Common_vocabulary)). When you write a version constraint, it may reference a specific tag (e.g., `1.1`) or it may reference a valid range of tags (e.g., `>=1.1 <2.0`, or `~4.0`). To resolve these constraints, Composer first asks the VCS to list all available tags, then creates an internal list of available versions based on these tags. In the above example, composer's internal list includes versions `1.0`, `1.0.1`, `1.0.2`, the beta release of `1.1`, the first and second release candidates of `1.1`, the final release version `1.1`, etc.... (Note that Composer automatically removes the 'v' prefix in the actual tagname to get a valid final version number.) When Composer has a complete list of available versions from your VCS, it then finds the highest version that matches all version constraints in your project (it's possible that other packages require more specific versions of the library than you do, so the version it chooses may not always be the highest available version) and it downloads a zip archive of that tag to unpack in the correct location in your `vendor` directory. ### Branches If you want Composer to check out a branch instead of a tag, you need to point it to the branch using the special `dev-*` prefix (or sometimes suffix; see below). If you're checking out a branch, it's assumed that you want to *work* on the branch and Composer actually clones the repo into the correct place in your `vendor` directory. For tags, it just copies the right files without actually cloning the repo. (You can modify this behavior with --prefer-source and --prefer-dist, see [install options](../03-cli.md#install).) In the above example, if you wanted to check out the `my-feature` branch, you would specify `dev-my-feature` as the version constraint in your `require` clause. This would result in Composer cloning the `my-library` repository into my `vendor` directory and checking out the `my-feature` branch. When branch names look like versions, we have to clarify for composer that we're trying to check out a branch and not a tag. In the above example, we have two version branches: `v1` and `v2`. To get Composer to check out one of these branches, you must specify a version constraint that looks like this: `v1.x-dev`. The `.x` is an arbitrary string that Composer requires to tell it that we're talking about the `v1` branch and not a `v1` tag (alternatively, you can just name the branch `v1.x` instead of `v1`). In the case of a branch with a version-like name (`v1`, in this case), you append `-dev` as a suffix, rather than using `dev-` as a prefix. ### Minimum Stability There's one more thing that will affect which files are checked out of a library's VCS and added to your project: Composer allows you to specify stability constraints to limit which tags are considered valid. In the above example, note that the library released a beta and two release candidates for version `1.1` before the final official release. To receive these versions when running `composer install` or `composer update`, we have to explicitly tell Composer that we are ok with release candidates and beta releases (and alpha releases, if we want those). This can be done using either a project-wide `minimum-stability` value in `composer.json` or using "stability flags" in version constraints. Read more on the [schema page](../04-schema.md#minimum-stability). ## Writing Version Constraints Now that you have an idea of how Composer sees versions, let's talk about how to specify version constraints for your project dependencies. ### Exact Version Constraint You can specify the exact version of a package. This will tell Composer to install this version and this version only. If other dependencies require a different version, the solver will ultimately fail and abort any install or update procedures. Example: `1.0.2` ### Version Range By using comparison operators you can specify ranges of valid versions. Valid operators are `>`, `>=`, `<`, `<=`, `!=`. You can define multiple ranges. Ranges separated by a space ( ) or comma (`,`) will be treated as a **logical AND**. A double pipe (`||`) will be treated as a **logical OR**. AND has higher precedence than OR. > **Note:** Be careful when using unbounded ranges as you might end up > unexpectedly installing versions that break backwards compatibility. > Consider using the [caret](#caret-version-range-) operator instead for safety. Examples: * `>=1.0` * `>=1.0 <2.0` * `>=1.0 <1.1 || >=1.2` ### Hyphenated Version Range ( - ) Inclusive set of versions. Partial versions on the right include are completed with a wildcard. For example `1.0 - 2.0` is equivalent to `>=1.0.0 <2.1` as the `2.0` becomes `2.0.*`. On the other hand `1.0.0 - 2.1.0` is equivalent to `>=1.0.0 <=2.1.0`. Example: `1.0 - 2.0` ### Wildcard Version Range (.*) You can specify a pattern with a `*` wildcard. `1.0.*` is the equivalent of `>=1.0 <1.1`. Example: `1.0.*` ## Next Significant Release Operators ### Tilde Version Range (~) The `~` operator is best explained by example: `~1.2` is equivalent to `>=1.2 <2.0.0`, while `~1.2.3` is equivalent to `>=1.2.3 <1.3.0`. As you can see it is mostly useful for projects respecting [semantic versioning](https://semver.org/). A common usage would be to mark the minimum minor version you depend on, like `~1.2` (which allows anything up to, but not including, 2.0). Since in theory there should be no backwards compatibility breaks until 2.0, that works well. Another way of looking at it is that using `~` specifies a minimum version, but allows the last digit specified to go up. Example: `~1.2` > **Note:** Although `2.0-beta.1` is strictly before `2.0`, a version constraint > like `~1.2` would not install it. As said above `~1.2` only means the `.2` > can change but the `1.` part is fixed. > **Note:** The `~` operator has an exception on its behavior for the major > release number. This means for example that `~1` is the same as `~1.0` as > it will not allow the major number to increase trying to keep backwards > compatibility. ### Caret Version Range (^) The `^` operator behaves very similarly but it sticks closer to semantic versioning, and will always allow non-breaking updates. For example `^1.2.3` is equivalent to `>=1.2.3 <2.0.0` as none of the releases until 2.0 should break backwards compatibility. For pre-1.0 versions it also acts with safety in mind and treats `^0.3` as `>=0.3.0 <0.4.0`. This is the recommended operator for maximum interoperability when writing library code. Example: `^1.2.3` ## Stability Constraints If you are using a constraint that does not explicitly define a stability, Composer will default internally to `-dev` or `-stable`, depending on the operator(s) used. This happens transparently. If you wish to explicitly consider only the stable release in the comparison, add the suffix `-stable`. Examples: Constraint | Internally ------------------- | ------------------------ `1.2.3` | `=1.2.3.0-stable` `>1.2` | `>1.2.0.0-stable` `>=1.2` | `>=1.2.0.0-dev` `>=1.2-stable` | `>=1.2.0.0-stable` `<1.3` | `<1.3.0.0-dev` `<=1.3` | `<=1.3.0.0-stable` `1 - 2` | `>=1.0.0.0-dev <3.0.0.0-dev` `~1.3` | `>=1.3.0.0-dev <2.0.0.0-dev` `1.4.*` | `>=1.4.0.0-dev <1.5.0.0-dev` To allow various stabilities without enforcing them at the constraint level however, you may use [stability-flags](../04-schema.md#package-links) like `@` (e.g. `@dev`) to let composer know that a given package can be installed in a different stability than your default minimum-stability setting. All available stability flags are listed on the minimum-stability section of the [schema page](../04-schema.md#minimum-stability). ## Summary ```json "require": { "vendor/package": "1.3.2", // exactly 1.3.2 // >, <, >=, <= | specify upper / lower bounds "vendor/package": ">=1.3.2", // anything above or equal to 1.3.2 "vendor/package": "<1.3.2", // anything below 1.3.2 // * | wildcard "vendor/package": "1.3.*", // >=1.3.0 <1.4.0 // ~ | allows last digit specified to go up "vendor/package": "~1.3.2", // >=1.3.2 <1.4.0 "vendor/package": "~1.3", // >=1.3.0 <2.0.0 // ^ | doesn't allow breaking changes (major version fixed - following semver) "vendor/package": "^1.3.2", // >=1.3.2 <2.0.0 "vendor/package": "^0.3.2", // >=0.3.2 <0.4.0 // except if major version is 0 } ``` ## Testing Version Constraints You can test version constraints using [semver.mwl.be](https://semver.mwl.be). Fill in a package name and it will autofill the default version constraint which Composer would add to your `composer.json` file. You can adjust the version constraint and the tool will highlight all releases that match. composer-1.6.3/doc/dev/000077500000000000000000000000001323436022200146705ustar00rootroot00000000000000composer-1.6.3/doc/dev/DefaultPolicy.md000066400000000000000000000024001323436022200177520ustar00rootroot00000000000000# Default Solver Policy A solver policy defines behaviour variables of the dependency solver. It decides which versions are considered newer than others, which packages should be preferred over others and whether operations like downgrades or uninstall are allowed. ## Selection of preferred Packages The following describe package pool situations with user requests and the resulting order in which the solver will try to install them. The rules are to be applied in the order of these descriptions. ### Repository priorities Packages Repo1.Av1, Repo2.Av1 * priority(Repo1) >= priority(Repo2) => (Repo1.Av1, Repo2.Av1) * priority(Repo1) < priority(Repo2) => (Repo2.Av1, Repo1.Av1) ### Package versions Packages: Av1, Av2, Av3 * Installed: Av2 Request: install A * (Av3) ### Virtual Packages (provides) Packages Av1, Bv1 * Av1 provides Xv1 * Bv1 provides Xv1 Request: install X * priority(Av1.repo) >= priority(Bv1.repo) => (Av1, Bv1) * priority(Av1.repo) < priority(Bv1.repo) => (Bv1, Av1) ### Package replacements Packages: Av1, Bv2 * Bv2 replaces Av1 Request: install A * priority(Av1.repo) >= priority(Bv2.repo) => (Av1, Bv2) * priority(Av1.repo) < priority(Bv2.repo) => (Bv2, Av1) Bv2 version is ignored, only the replacement version for A matters. composer-1.6.3/doc/faqs/000077500000000000000000000000001323436022200150445ustar00rootroot00000000000000composer-1.6.3/doc/faqs/how-do-i-install-a-package-to-a-custom-path-for-my-framework.md000066400000000000000000000034441323436022200305730ustar00rootroot00000000000000# How do I install a package to a custom path for my framework? Each framework may have one or many different required package installation paths. Composer can be configured to install packages to a folder other than the default `vendor` folder by using [composer/installers](https://github.com/composer/installers). If you are a **package author** and want your package installed to a custom directory, simply require `composer/installers` and set the appropriate `type`. This is common if your package is intended for a specific framework such as CakePHP, Drupal or WordPress. Here is an example composer.json file for a WordPress theme: ```json { "name": "you/themename", "type": "wordpress-theme", "require": { "composer/installers": "~1.0" } } ``` Now when your theme is installed with Composer it will be placed into `wp-content/themes/themename/` folder. Check the [current supported types](https://github.com/composer/installers#current-supported-types) for your package. As a **package consumer** you can set or override the install path for a package that requires composer/installers by configuring the `installer-paths` extra. A useful example would be for a Drupal multisite setup where the package should be installed into your sites subdirectory. Here we are overriding the install path for a module that uses composer/installers: ```json { "extra": { "installer-paths": { "sites/example.com/modules/{$name}": ["vendor/package"] } } } ``` Now the package would be installed to your folder location, rather than the default composer/installers determined location. > **Note:** You cannot use this to change the path of any package. This is only > applicable to packages that require `composer/installers` and use a custom type > that it handles. composer-1.6.3/doc/faqs/how-to-install-composer-programmatically.md000066400000000000000000000026001323436022200254370ustar00rootroot00000000000000# How do I install Composer programmatically? As noted on the download page, the installer script contains a signature which changes when the installer code changes and as such it should not be relied upon long term. An alternative is to use this script which only works with unix utils: ```bash #!/bin/sh EXPECTED_SIGNATURE=$(wget -q -O - https://composer.github.io/installer.sig) php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ACTUAL_SIGNATURE=$(php -r "echo hash_file('SHA384', 'composer-setup.php');") if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ] then >&2 echo 'ERROR: Invalid installer signature' rm composer-setup.php exit 1 fi php composer-setup.php --quiet RESULT=$? rm composer-setup.php exit $RESULT ``` The script will exit with 1 in case of failure, or 0 on success, and is quiet if no error occurs. Alternatively if you want to rely on an exact copy of the installer you can fetch a specific version from github's history. The commit hash should be enough to give it uniqueness and authenticity as long as you can trust the GitHub servers. For example: ```bash wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet ``` You may replace the commit hash by whatever the last commit hash is on https://github.com/composer/getcomposer.org/commits/master composer-1.6.3/doc/faqs/how-to-install-untrusted-packages-safely.md000066400000000000000000000016521323436022200253430ustar00rootroot00000000000000# How do I install untrusted packages safely? Is it safe to run Composer as superuser or root? Certain Composer commands, including `exec`, `install`, and `update` allow third party code to execute on your system. This is from its "plugins" and "scripts" features. Plugins and scripts have full access to the user account which runs Composer. For this reason, it is strongly advised to **avoid running Composer as super-user/root**. You can disable plugins and scripts during package installation or updates with the following syntax so only Composer's code, and no third party code, will execute: ```sh composer install --no-plugins --no-scripts ... composer update --no-plugins --no-scripts ... ``` The `exec` command will always run third party code as the user which runs `composer`. In some cases, like in CI systems or such where you want to install untrusted dependencies, the safest way to do it is to run the above command. composer-1.6.3/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md000066400000000000000000000032501323436022200301260ustar00rootroot00000000000000# Should I commit the dependencies in my vendor directory? The general recommendation is **no**. The vendor directory (or wherever your dependencies are installed) should be added to `.gitignore`/`svn:ignore`/etc. The best practice is to then have all the developers use Composer to install the dependencies. Similarly, the build server, CI, deployment tools etc should be adapted to run Composer as part of their project bootstrapping. While it can be tempting to commit it in some environment, it leads to a few problems: - Large VCS repository size and diffs when you update code. - Duplication of the history of all your dependencies in your own VCS. - Adding dependencies installed via git to a git repo will show them as submodules. This is problematic because they are not real submodules, and you will run into issues. If you really feel like you must do this, you have a few options: 1. Limit yourself to installing tagged releases (no dev versions), so that you only get zipped installs, and avoid problems with the git "submodules". 2. Use --prefer-dist or set `preferred-install` to `dist` in your [config](../04-schema.md#config). 3. Remove the `.git` directory of every dependency after the installation, then you can add them to your git repo. You can do that with `rm -rf vendor/**/.git` in ZSH or `find vendor/ -type d -name ".git" -exec rm -rf {} \;` in Bash. but this means you will have to delete those dependencies from disk before running composer update. 4. Add a .gitignore rule (`/vendor/**/.git`) to ignore all the vendor `.git` folders. This approach does not require that you delete dependencies from disk prior to running a composer update. composer-1.6.3/doc/faqs/why-are-unbound-version-constraints-a-bad-idea.md000066400000000000000000000020771323436022200263120ustar00rootroot00000000000000# Why are unbound version constraints a bad idea? A version constraint without an upper bound such as `*`, `>=3.4` or `dev-master` will allow updates to any future version of the dependency. This includes major versions breaking backward compatibility. Once a release of your package is tagged, you cannot tweak its dependencies anymore in case a dependency breaks BC - you have to do a new release but the previous one stays broken. The only good alternative is to define an upper bound on your constraints, which you can increase in a new release after testing that your package is compatible with the new major version of your dependency. For example instead of using `>=3.4` you should use `~3.4` which allows all versions up to `3.999` but does not include `4.0` and above. The `^` operator works very well with libraries following [semantic versioning](https://semver.org). **Note:** As a package maintainer, you can make the life of your users easier by providing an [alias version](../articles/aliases.md) for your development branch to allow it to match bound constraints. why-are-version-constraints-combining-comparisons-and-wildcards-a-bad-idea.md000066400000000000000000000017461323436022200335750ustar00rootroot00000000000000composer-1.6.3/doc/faqs# Why are version constraints combining comparisons and wildcards a bad idea? This is a fairly common mistake people make, defining version constraints in their package requires like `>=2.*` or `>=1.1.*`. If you think about it and what it really means though, you will quickly realize that it does not make much sense. If we decompose `>=2.*`, you have two parts: - `>=2` which says the package should be in version 2.0.0 or above. - `2.*` which says the package should be between version 2.0.0 (inclusive) and 3.0.0 (exclusive). As you see, both rules agree on the fact that the package must be >=2.0.0, but it is not possible to determine if when you wrote that you were thinking of a package in version 3.0.0 or not. Should it match because you asked for `>=2` or should it not match because you asked for a `2.*`? For this reason, Composer just throws an error and says that this is invalid. The easy way to fix it is to think about what you really mean, and use only one of those rules.composer-1.6.3/doc/faqs/why-can't-composer-load-repositories-recursively.md000066400000000000000000000040721323436022200270330ustar00rootroot00000000000000# Why can't Composer load repositories recursively? You may run into problems when using custom repositories because Composer does not load the repositories of your requirements, so you have to redefine those repositories in all your `composer.json` files. Before going into details as to why this is like that, you have to understand that the main use of custom VCS & package repositories is to temporarily try some things, or use a fork of a project until your pull request is merged, etc. You should not use them to keep track of private packages. For that you should rather look into [Private Packagist](https://packagist.com) which lets you configure all your private packages in one place, and avoids the slow-downs associated with inline VCS repositories. There are three ways the dependency solver could work with custom repositories: - Fetch the repositories of root package, get all the packages from the defined repositories, resolve requirements. This is the current state and it works well except for the limitation of not loading repositories recursively. - Fetch the repositories of root package, while initializing packages from the defined repos, initialize recursively all repos found in those packages, and their package's packages, etc, then resolve requirements. It could work, but it slows down the initialization a lot since VCS repos can each take a few seconds, and it could end up in a completely broken state since many versions of a package could define the same packages inside a package repository, but with different dist/source. There are many many ways this could go wrong. - Fetch the repositories of root package, then fetch the repositories of the first level dependencies, then fetch the repositories of their dependencies, etc, then resolve requirements. This sounds more efficient, but it suffers from the same problems as the second solution, because loading the repositories of the dependencies is not as easy as it sounds. You need to load all the repos of all the potential matches for a requirement, which again might have conflicting package definitions. composer-1.6.3/doc/fixtures/000077500000000000000000000000001323436022200157635ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/fixtures.md000066400000000000000000000017261323436022200201640ustar00rootroot00000000000000# `Composer` type repository fixtures This directory contains some examples of what `composer` type repositories can look like. They serve as illustrating examples accompanying the docs, but can also be used as (initial) fixtures for tests. * `repo-composer-plain` is a simple, plain `packages.json` file * `repo-composer-with-includes` uses the `includes` mechanism * `repo-composer-with-providers` uses the `providers` mechanism ## Sample Packages used in these fixtures All these repositories contain the following packages. * `foo/bar` versions 1.0.0, 1.0.1 and 1.1.0; dev-default and 1.0.x-dev branches. On dev-default and in 1.1.0, `bar/baz` ~1.0 is required. * `qux/quux` only has a dev-default branch. It `replace`s `gar/nix`. * `gar/nix` has a 1.0.0 version and a dev-default branch. It is being replaced by `qux/quux`. * `bar/baz` has a 1.0.0 version and 1.0.x-dev as well as dev-default branches. Additionally, 1.1.x-dev is a branch alias for dev-default. composer-1.6.3/doc/fixtures/repo-composer-plain/000077500000000000000000000000001323436022200216565ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-plain/packages.json000066400000000000000000000125171323436022200243350ustar00rootroot00000000000000{ "packages": { "bar/baz": { "1.0.0": { "name": "bar/baz", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "35810817c14d" }, "time": "2014-10-13 12:04:55", "type": "library" }, "1.0.x-dev": { "name": "bar/baz", "version": "1.0.x-dev", "version_normalized": "1.0.9999999.9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "ffff9aae6ed5" }, "time": "2014-10-13 12:05:37", "type": "library" }, "dev-default": { "name": "bar/baz", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "f317e556f2e2" }, "time": "2014-10-13 12:06:45", "type": "library", "extra": { "branch-alias": { "dev-default": "1.1.x-dev" } } } }, "foo/bar": { "1.0.0": { "name": "foo/bar", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "249dec95a52a" }, "time": "2014-10-11 15:42:00", "type": "library" }, "1.0.1": { "name": "foo/bar", "version": "1.0.1", "version_normalized": "1.0.1.0", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "21e3328295d4" }, "time": "2014-10-11 15:45:56", "type": "library" }, "1.0.x-dev": { "name": "foo/bar", "version": "1.0.x-dev", "version_normalized": "1.0.9999999.9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "14dc17c8e860" }, "time": "2014-10-11 15:45:59", "type": "library" }, "1.1.0": { "name": "foo/bar", "version": "1.1.0", "version_normalized": "1.1.0.0", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "d2fa3e69ad5b" }, "require": { "bar/baz": "~1.0" }, "time": "2014-10-11 15:43:16", "type": "library" }, "dev-default": { "name": "foo/bar", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "8e5a5c224336" }, "require": { "bar/baz": "~1.0" }, "time": "2014-10-11 15:43:18", "type": "library" } }, "gar/nix": { "1.0.0": { "name": "gar/nix", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "44977145d64e" }, "time": "2014-10-13 12:03:33", "type": "library" }, "dev-default": { "name": "gar/nix", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "51cca95a31c2" }, "time": "2014-10-13 12:03:35", "type": "library" } }, "qux/quux": { "dev-default": { "name": "qux/quux", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http://some.where/over/the/rainbow/", "reference": "4a10a567baa5" }, "replace": { "gar/nix": "1.0.*" }, "time": "2014-10-11 15:48:15", "type": "library" } } } } composer-1.6.3/doc/fixtures/repo-composer-with-providers/000077500000000000000000000000001323436022200235415ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/000077500000000000000000000000001323436022200240005ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/bar/000077500000000000000000000000001323436022200245445ustar00rootroot00000000000000baz$923363b3c22e73abb2e3fd891c8156dd4d0821a97fd3e428bc910833e3e46dbe.json000066400000000000000000000031701323436022200370030ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/bar{ "packages": { "bar\/baz": { "1.0.0": { "name": "bar\/baz", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "35810817c14d" }, "time": "2014-10-13 12:04:55", "type": "library", "uid": 0 }, "1.0.x-dev": { "name": "bar\/baz", "version": "1.0.x-dev", "version_normalized": "1.0.9999999.9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "ffff9aae6ed5" }, "time": "2014-10-13 12:05:37", "type": "library", "uid": 1 }, "dev-default": { "name": "bar\/baz", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "f317e556f2e2" }, "time": "2014-10-13 12:06:45", "type": "library", "extra": { "branch-alias": { "dev-default": "1.1.x-dev" } }, "uid": 2 } } } }composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/foo/000077500000000000000000000000001323436022200245635ustar00rootroot00000000000000bar$4baabb3303afa3e34a4d3af18fb138e5f3b79029c1f8d9ab5b477ea15776ba0a.json000066400000000000000000000050571323436022200373510ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/foo{ "packages": { "foo\/bar": { "1.0.0": { "name": "foo\/bar", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "249dec95a52a" }, "time": "2014-10-11 15:42:00", "type": "library", "uid": 3 }, "1.0.1": { "name": "foo\/bar", "version": "1.0.1", "version_normalized": "1.0.1.0", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "21e3328295d4" }, "time": "2014-10-11 15:45:56", "type": "library", "uid": 4 }, "1.0.x-dev": { "name": "foo\/bar", "version": "1.0.x-dev", "version_normalized": "1.0.9999999.9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "14dc17c8e860" }, "time": "2014-10-11 15:45:59", "type": "library", "uid": 5 }, "1.1.0": { "name": "foo\/bar", "version": "1.1.0", "version_normalized": "1.1.0.0", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "d2fa3e69ad5b" }, "require": { "bar\/baz": "~1.0" }, "time": "2014-10-11 15:43:16", "type": "library", "uid": 6 }, "dev-default": { "name": "foo\/bar", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "8e5a5c224336" }, "require": { "bar\/baz": "~1.0" }, "time": "2014-10-11 15:43:18", "type": "library", "uid": 7 } } } }composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/gar/000077500000000000000000000000001323436022200245515ustar00rootroot00000000000000nix$5d210670cb46c8364c8e3fb449967b9bea558b971e5b082f330ae4f1d484c321.json000066400000000000000000000031161323436022200366220ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/gar{ "packages": { "qux\/quux": { "dev-default": { "name": "qux\/quux", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "4a10a567baa5" }, "replace": { "gar\/nix": "1.0.*" }, "time": "2014-10-11 15:48:15", "type": "library", "uid": 10 } }, "gar\/nix": { "1.0.0": { "name": "gar\/nix", "version": "1.0.0", "version_normalized": "1.0.0.0", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "44977145d64e" }, "time": "2014-10-13 12:03:33", "type": "library", "uid": 8 }, "dev-default": { "name": "gar\/nix", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "51cca95a31c2" }, "time": "2014-10-13 12:03:35", "type": "library", "uid": 9 } } } }provider-active$1893a061e579543822389ecd12d791c612db0c05e22d90e9286e233cacd86ed8.json000066400000000000000000000010041323436022200402720ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p{ "providers": { "bar\/baz": { "sha256": "923363b3c22e73abb2e3fd891c8156dd4d0821a97fd3e428bc910833e3e46dbe" }, "foo\/bar": { "sha256": "4baabb3303afa3e34a4d3af18fb138e5f3b79029c1f8d9ab5b477ea15776ba0a" }, "gar\/nix": { "sha256": "5d210670cb46c8364c8e3fb449967b9bea558b971e5b082f330ae4f1d484c321" }, "qux\/quux": { "sha256": "c142d1a07ca354be46b613f59f1d601923a5a00ccc5fcce50a77ecdd461eb72d" } } }composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/qux/000077500000000000000000000000001323436022200246155ustar00rootroot00000000000000quux$c142d1a07ca354be46b613f59f1d601923a5a00ccc5fcce50a77ecdd461eb72d.json000066400000000000000000000011701323436022200375370ustar00rootroot00000000000000composer-1.6.3/doc/fixtures/repo-composer-with-providers/p/qux{ "packages": { "qux\/quux": { "dev-default": { "name": "qux\/quux", "version": "dev-default", "version_normalized": "9999999-dev", "source": { "type": "hg", "url": "http:\/\/some.where\/over\/the\/rainbow\/", "reference": "4a10a567baa5" }, "replace": { "gar\/nix": "1.0.*" }, "time": "2014-10-11 15:48:15", "type": "library", "uid": 10 } } } }composer-1.6.3/doc/fixtures/repo-composer-with-providers/packages.json000066400000000000000000000004641323436022200262160ustar00rootroot00000000000000{ "packages": [], "providers-url": "\/p\/%package%$%hash%.json", "provider-includes": { "p\/provider-active$1893a061e579543822389ecd12d791c612db0c05e22d90e9286e233cacd86ed8.json": { "sha256": "1893a061e579543822389ecd12d791c612db0c05e22d90e9286e233cacd86ed8" } } }composer-1.6.3/phpunit.xml.dist000066400000000000000000000016441323436022200165250ustar00rootroot00000000000000 ./tests/Composer/ slow legacy ./src/Composer/ ./src/Composer/Autoload/ClassLoader.php composer-1.6.3/res/000077500000000000000000000000001323436022200141365ustar00rootroot00000000000000composer-1.6.3/res/composer-repository-schema.json000066400000000000000000000077601323436022200223450ustar00rootroot00000000000000{ "$schema": "http://json-schema.org/draft-04/schema#", "description": "A representation of packages metadata.", "type": "object", "oneOf": [ { "required": [ "packages" ] }, { "required": [ "providers" ] }, { "required": [ "provider-includes", "providers-url" ] } ], "properties": { "packages": { "type": ["object", "array"], "description": "A hashmap of package names in the form of /.", "additionalProperties": { "$ref": "#/definitions/versions" } }, "providers-url": { "type": "string", "description": "Endpoint to retrieve provider data from, e.g. '/p/%package%$%hash%.json'." }, "provider-includes": { "type": "object", "description": "A hashmap of provider listings.", "additionalProperties": { "$ref": "#/definitions/provider" } }, "providers": { "type": "object", "description": "A hashmap of package names in the form of /.", "additionalProperties": { "$ref": "#/definitions/provider" } }, "notify-batch": { "type": "string", "description": "Endpoint to call after multiple packages have been installed, e.g. '/downloads/'." }, "search": { "type": "string", "description": "Endpoint that provides search capabilities, e.g. '/search.json?q=%query%&type=%type%'." }, "warning": { "type": "string", "description": "A message that will be output by Composer as a warning when this source is consulted." } }, "definitions": { "versions": { "type": "object", "description": "A hashmap of versions and their metadata.", "additionalProperties": { "$ref": "#/definitions/version" } }, "version": { "type": "object", "oneOf": [ { "$ref": "#/definitions/package" }, { "$ref": "#/definitions/metapackage" } ] }, "package-base": { "properties": { "name": { "type": "string" }, "type": { "type": "string" }, "version": { "type": "string" }, "version_normalized": { "type": "string", "description": "Normalized version, optional but can save computational time on client side." }, "autoload": { "type": "object" }, "require": { "type": "object" }, "replace": { "type": "object" }, "conflict": { "type": "object" }, "provide": { "type": "object" }, "time": { "type": "string" } }, "additionalProperties": true }, "package": { "allOf": [ { "$ref": "#/definitions/package-base" }, { "properties": { "dist": { "type": "object" }, "source": { "type": "object" } } }, { "oneOf": [ { "required": [ "name", "version", "source" ] }, { "required": [ "name", "version", "dist" ] } ] } ] }, "metapackage": { "allOf": [ { "$ref": "#/definitions/package-base" }, { "properties": { "type": { "type": "string", "enum": [ "metapackage" ] } }, "required": [ "name", "version", "type" ] } ] }, "provider": { "type": "object", "properties": { "sha256": { "type": "string", "description": "Hash value that can be used to validate the resource." } } } } } composer-1.6.3/res/composer-schema.json000066400000000000000000001125711323436022200201250ustar00rootroot00000000000000{ "$schema": "http://json-schema.org/draft-04/schema#", "name": "Package", "type": "object", "additionalProperties": false, "required": [ "name", "description" ], "properties": { "name": { "type": "string", "description": "Package name, including 'vendor-name/' prefix." }, "type": { "description": "Package type, either 'library' for common packages, 'composer-plugin' for plugins, 'metapackage' for empty packages, or a custom type ([a-z0-9-]+) defined by whatever project this package applies to.", "type": "string" }, "target-dir": { "description": "DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.", "type": "string" }, "description": { "type": "string", "description": "Short package description." }, "keywords": { "type": "array", "items": { "type": "string", "description": "A tag/keyword that this package relates to." } }, "homepage": { "type": "string", "description": "Homepage URL for the project.", "format": "uri" }, "version": { "type": "string", "description": "Package version, see https://getcomposer.org/doc/04-schema.md#version for more info on valid schemes." }, "time": { "type": "string", "description": "Package release date, in 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DDTHH:MM:SSZ' format." }, "license": { "type": ["string", "array"], "description": "License name. Or an array of license names." }, "authors": { "$ref": "#/definitions/authors" }, "require": { "type": "object", "description": "This is a hash of package name (keys) and version constraints (values) that are required to run this package.", "additionalProperties": { "type": "string" } }, "replace": { "type": "object", "description": "This is a hash of package name (keys) and version constraints (values) that can be replaced by this package.", "additionalProperties": { "type": "string" } }, "conflict": { "type": "object", "description": "This is a hash of package name (keys) and version constraints (values) that conflict with this package.", "additionalProperties": { "type": "string" } }, "provide": { "type": "object", "description": "This is a hash of package name (keys) and version constraints (values) that this package provides in addition to this package's name.", "additionalProperties": { "type": "string" } }, "require-dev": { "type": "object", "description": "This is a hash of package name (keys) and version constraints (values) that this package requires for developing it (testing tools and such).", "additionalProperties": { "type": "string" } }, "suggest": { "type": "object", "description": "This is a hash of package name (keys) and descriptions (values) that this package suggests work well with it (this will be suggested to the user during installation).", "additionalProperties": { "type": "string" } }, "config": { "type": "object", "description": "Composer options.", "properties": { "process-timeout": { "type": "integer", "description": "The timeout in seconds for process executions, defaults to 300 (5mins)." }, "use-include-path": { "type": "boolean", "description": "If true, the Composer autoloader will also look for classes in the PHP include path." }, "preferred-install": { "type": ["string", "object"], "description": "The install method Composer will prefer to use, defaults to auto and can be any of source, dist, auto, or a hash of {\"pattern\": \"preference\"}." }, "notify-on-install": { "type": "boolean", "description": "Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour, defaults to true." }, "github-protocols": { "type": "array", "description": "A list of protocols to use for github.com clones, in priority order, defaults to [\"git\", \"https\", \"http\"].", "items": { "type": "string" } }, "github-oauth": { "type": "object", "description": "A hash of domain name => github API oauth tokens, typically {\"github.com\":\"\"}.", "additionalProperties": { "type": "string" } }, "gitlab-oauth": { "type": "object", "description": "A hash of domain name => gitlab API oauth tokens, typically {\"gitlab.com\":\"\"}.", "additionalProperties": { "type": "string" } }, "gitlab-token": { "type": "object", "description": "A hash of domain name => gitlab private tokens, typically {\"gitlab.com\":\"\"}.", "additionalProperties": true }, "disable-tls": { "type": "boolean", "description": "Defaults to `false`. If set to true all HTTPS URLs will be tried with HTTP instead and no network level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini." }, "secure-http": { "type": "boolean", "description": "Defaults to `true`. If set to true only HTTPS URLs are allowed to be downloaded via Composer. If you really absolutely need HTTP access to something then you can disable it, but using \"Let's Encrypt\" to get a free SSL certificate is generally a better alternative." }, "cafile": { "type": "string", "description": "A way to set the path to the openssl CA file. In PHP 5.6+ you should rather set this via openssl.cafile in php.ini, although PHP 5.6+ should be able to detect your system CA file automatically." }, "capath": { "type": "string", "description": "If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory." }, "http-basic": { "type": "object", "description": "A hash of domain name => {\"username\": \"...\", \"password\": \"...\"}.", "additionalProperties": { "type": "object", "required": ["username", "password"], "properties": { "username": { "type": "string", "description": "The username used for HTTP Basic authentication" }, "password": { "type": "string", "description": "The password used for HTTP Basic authentication" } } } }, "store-auths": { "type": ["string", "boolean"], "description": "What to do after prompting for authentication, one of: true (store), false (do not store) or \"prompt\" (ask every time), defaults to prompt." }, "platform": { "type": "object", "description": "This is a hash of package name (keys) and version (values) that will be used to mock the platform packages on this machine.", "additionalProperties": { "type": "string" } }, "vendor-dir": { "type": "string", "description": "The location where all packages are installed, defaults to \"vendor\"." }, "bin-dir": { "type": "string", "description": "The location where all binaries are linked, defaults to \"vendor/bin\"." }, "data-dir": { "type": "string", "description": "The location where old phar files are stored, defaults to \"$home\" except on XDG Base Directory compliant unixes." }, "cache-dir": { "type": "string", "description": "The location where all caches are located, defaults to \"~/.composer/cache\" on *nix and \"%LOCALAPPDATA%\\Composer\" on windows." }, "cache-files-dir": { "type": "string", "description": "The location where files (zip downloads) are cached, defaults to \"{$cache-dir}/files\"." }, "cache-repo-dir": { "type": "string", "description": "The location where repo (git/hg repo clones) are cached, defaults to \"{$cache-dir}/repo\"." }, "cache-vcs-dir": { "type": "string", "description": "The location where vcs infos (git clones, github api calls, etc. when reading vcs repos) are cached, defaults to \"{$cache-dir}/vcs\"." }, "cache-ttl": { "type": "integer", "description": "The default cache time-to-live, defaults to 15552000 (6 months)." }, "cache-files-ttl": { "type": "integer", "description": "The cache time-to-live for files, defaults to the value of cache-ttl." }, "cache-files-maxsize": { "type": ["string", "integer"], "description": "The cache max size for the files cache, defaults to \"300MiB\"." }, "bin-compat": { "enum": ["auto", "full"], "description": "The compatibility of the binaries, defaults to \"auto\" (automatically guessed) and can be \"full\" (compatible with both Windows and Unix-based systems)." }, "discard-changes": { "type": ["string", "boolean"], "description": "The default style of handling dirty updates, defaults to false and can be any of true, false or \"stash\"." }, "autoloader-suffix": { "type": "string", "description": "Optional string to be used as a suffix for the generated Composer autoloader. When null a random one will be generated." }, "optimize-autoloader": { "type": "boolean", "description": "Always optimize when dumping the autoloader." }, "prepend-autoloader": { "type": "boolean", "description": "If false, the composer autoloader will not be prepended to existing autoloaders, defaults to true." }, "classmap-authoritative": { "type": "boolean", "description": "If true, the composer autoloader will not scan the filesystem for classes that are not found in the class map, defaults to false." }, "apcu-autoloader": { "type": "boolean", "description": "If true, the Composer autoloader will check for APCu and use it to cache found/not-found classes when the extension is enabled, defaults to false." }, "github-domains": { "type": "array", "description": "A list of domains to use in github mode. This is used for GitHub Enterprise setups, defaults to [\"github.com\"].", "items": { "type": "string" } }, "github-expose-hostname": { "type": "boolean", "description": "Defaults to true. If set to false, the OAuth tokens created to access the github API will have a date instead of the machine hostname." }, "gitlab-domains": { "type": "array", "description": "A list of domains to use in gitlab mode. This is used for custom GitLab setups, defaults to [\"gitlab.com\"].", "items": { "type": "string" } }, "archive-format": { "type": "string", "description": "The default archiving format when not provided on cli, defaults to \"tar\"." }, "archive-dir": { "type": "string", "description": "The default archive path when not provided on cli, defaults to \".\"." }, "htaccess-protect": { "type": "boolean", "description": "Defaults to true. If set to false, Composer will not create .htaccess files in the composer home, cache, and data directories." }, "sort-packages": { "type": "boolean", "description": "Defaults to false. If set to true, Composer will sort packages when adding/updating a new dependency." } } }, "extra": { "type": ["object", "array"], "description": "Arbitrary extra data that can be used by plugins, for example, package of type composer-plugin may have a 'class' key defining an installer class name.", "additionalProperties": true }, "autoload": { "$ref": "#/definitions/autoload" }, "autoload-dev": { "type": "object", "description": "Description of additional autoload rules for development purpose (eg. a test suite).", "properties": { "psr-0": { "type": "object", "description": "This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.", "additionalProperties": { "type": ["string", "array"], "items": { "type": "string" } } }, "psr-4": { "type": "object", "description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.", "additionalProperties": { "type": ["string", "array"], "items": { "type": "string" } } }, "classmap": { "type": "array", "description": "This is an array of directories that contain classes to be included in the class-map generation process." }, "files": { "type": "array", "description": "This is an array of files that are always required on every request." } } }, "archive": { "type": ["object"], "description": "Options for creating package archives for distribution.", "properties": { "exclude": { "type": "array", "description": "A list of patterns for paths to exclude or include if prefixed with an exclamation mark." } } }, "repositories": { "type": ["object", "array"], "description": "A set of additional repositories where packages can be found.", "additionalProperties": { "oneOf": [ { "$ref": "#/definitions/repository" }, { "type": "boolean", "enum": [false] } ] }, "items": { "oneOf": [ { "$ref": "#/definitions/repository" }, { "type": "object", "additionalProperties": { "type": "boolean", "enum": [false] }, "minProperties": 1, "maxProperties": 1 } ] } }, "minimum-stability": { "type": ["string"], "description": "The minimum stability the packages must have to be install-able. Possible values are: dev, alpha, beta, RC, stable.", "pattern": "^dev|alpha|beta|rc|RC|stable$" }, "prefer-stable": { "type": ["boolean"], "description": "If set to true, stable packages will be preferred to dev packages when possible, even if the minimum-stability allows unstable packages." }, "bin": { "type": ["string", "array"], "description": "A set of files, or a single file, that should be treated as binaries and symlinked into bin-dir (from config).", "items": { "type": "string" } }, "include-path": { "type": ["array"], "description": "DEPRECATED: A list of directories which should get added to PHP's include path. This is only present to support legacy projects, and all new code should preferably use autoloading.", "items": { "type": "string" } }, "scripts": { "type": ["object"], "description": "Script listeners that will be executed before/after some events.", "properties": { "pre-install-cmd": { "type": ["array", "string"], "description": "Occurs before the install command is executed, contains one or more Class::method callables or shell commands." }, "post-install-cmd": { "type": ["array", "string"], "description": "Occurs after the install command is executed, contains one or more Class::method callables or shell commands." }, "pre-update-cmd": { "type": ["array", "string"], "description": "Occurs before the update command is executed, contains one or more Class::method callables or shell commands." }, "post-update-cmd": { "type": ["array", "string"], "description": "Occurs after the update command is executed, contains one or more Class::method callables or shell commands." }, "pre-status-cmd": { "type": ["array", "string"], "description": "Occurs before the status command is executed, contains one or more Class::method callables or shell commands." }, "post-status-cmd": { "type": ["array", "string"], "description": "Occurs after the status command is executed, contains one or more Class::method callables or shell commands." }, "pre-package-install": { "type": ["array", "string"], "description": "Occurs before a package is installed, contains one or more Class::method callables or shell commands." }, "post-package-install": { "type": ["array", "string"], "description": "Occurs after a package is installed, contains one or more Class::method callables or shell commands." }, "pre-package-update": { "type": ["array", "string"], "description": "Occurs before a package is updated, contains one or more Class::method callables or shell commands." }, "post-package-update": { "type": ["array", "string"], "description": "Occurs after a package is updated, contains one or more Class::method callables or shell commands." }, "pre-package-uninstall": { "type": ["array", "string"], "description": "Occurs before a package has been uninstalled, contains one or more Class::method callables or shell commands." }, "post-package-uninstall": { "type": ["array", "string"], "description": "Occurs after a package has been uninstalled, contains one or more Class::method callables or shell commands." }, "pre-autoload-dump": { "type": ["array", "string"], "description": "Occurs before the autoloader is dumped, contains one or more Class::method callables or shell commands." }, "post-autoload-dump": { "type": ["array", "string"], "description": "Occurs after the autoloader is dumped, contains one or more Class::method callables or shell commands." }, "post-root-package-install": { "type": ["array", "string"], "description": "Occurs after the root-package is installed, contains one or more Class::method callables or shell commands." }, "post-create-project-cmd": { "type": ["array", "string"], "description": "Occurs after the create-project command is executed, contains one or more Class::method callables or shell commands." } } }, "scripts-descriptions": { "type": ["object"], "description": "Descriptions for custom commands, shown in console help.", "additionalProperties": { "type": "string" } }, "support": { "type": "object", "properties": { "email": { "type": "string", "description": "Email address for support.", "format": "email" }, "issues": { "type": "string", "description": "URL to the issue tracker.", "format": "uri" }, "forum": { "type": "string", "description": "URL to the forum.", "format": "uri" }, "wiki": { "type": "string", "description": "URL to the wiki.", "format": "uri" }, "irc": { "type": "string", "description": "IRC channel for support, as irc://server/channel.", "format": "uri" }, "source": { "type": "string", "description": "URL to browse or download the sources.", "format": "uri" }, "docs": { "type": "string", "description": "URL to the documentation.", "format": "uri" }, "rss": { "type": "string", "description": "URL to the RSS feed.", "format": "uri" } } }, "non-feature-branches": { "type": ["array"], "description": "A set of string or regex patterns for non-numeric branch names that will not be handled as feature branches.", "items": { "type": "string" } }, "abandoned": { "type": ["boolean", "string"], "description": "Indicates whether this package has been abandoned, it can be boolean or a package name/URL pointing to a recommended alternative. Defaults to false." }, "_comment": { "type": ["array", "string"], "description": "A key to store comments in" } }, "definitions": { "authors": { "type": "array", "description": "List of authors that contributed to the package. This is typically the main maintainers, not the full list.", "items": { "type": "object", "additionalProperties": false, "required": [ "name"], "properties": { "name": { "type": "string", "description": "Full name of the author." }, "email": { "type": "string", "description": "Email address of the author.", "format": "email" }, "homepage": { "type": "string", "description": "Homepage URL for the author.", "format": "uri" }, "role": { "type": "string", "description": "Author's role in the project." } } } }, "autoload": { "type": "object", "description": "Description of how the package can be autoloaded.", "properties": { "psr-0": { "type": "object", "description": "This is a hash of namespaces (keys) and the directories they can be found in (values, can be arrays of paths) by the autoloader.", "additionalProperties": { "type": ["string", "array"], "items": { "type": "string" } } }, "psr-4": { "type": "object", "description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.", "additionalProperties": { "type": ["string", "array"], "items": { "type": "string" } } }, "classmap": { "type": "array", "description": "This is an array of directories that contain classes to be included in the class-map generation process." }, "files": { "type": "array", "description": "This is an array of files that are always required on every request." }, "exclude-from-classmap": { "type": "array", "description": "This is an array of patterns to exclude from autoload classmap generation. (e.g. \"exclude-from-classmap\": [\"/test/\", \"/tests/\", \"/Tests/\"]" } } }, "repository": { "type": "object", "oneOf": [ { "$ref": "#/definitions/composer-repository" }, { "$ref": "#/definitions/vcs-repository" }, { "$ref": "#/definitions/path-repository" }, { "$ref": "#/definitions/artifact-repository" }, { "$ref": "#/definitions/pear-repository" }, { "$ref": "#/definitions/package-repository" } ] }, "composer-repository": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string", "enum": ["composer"] }, "url": { "type": "string" }, "options": { "type": "object", "additionalProperties": true }, "allow_ssl_downgrade": { "type": "boolean" }, "force-lazy-providers": { "type": "boolean" } } }, "vcs-repository": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string", "enum": ["vcs", "github", "git", "gitlab", "git-bitbucket", "hg", "hg-bitbucket", "fossil", "perforce", "svn"] }, "url": { "type": "string" }, "no-api": { "type": "boolean" }, "secure-http": { "type": "boolean" }, "svn-cache-credentials": { "type": "boolean" }, "trunk-path": { "type": ["string", "boolean"] }, "branches-path": { "type": ["string", "boolean"] }, "tags-path": { "type": ["string", "boolean"] }, "package-path": { "type": "string" }, "depot": { "type": "string" }, "branch": { "type": "string" }, "unique_perforce_client_name": { "type": "string" }, "p4user": { "type": "string" }, "p4password": { "type": "string" } } }, "path-repository": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string", "enum": ["path"] }, "url": { "type": "string" }, "options": { "type": "object", "properties": { "symlink": { "type": ["boolean", "null"] } }, "additionalProperties": true } } }, "artifact-repository": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string", "enum": ["artifact"] }, "url": { "type": "string" } } }, "pear-repository": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string", "enum": ["pear"] }, "url": { "type": "string" }, "vendor-alias": { "type": "string" } } }, "package-repository": { "type": "object", "required": ["type", "package"], "properties": { "type": { "type": "string", "enum": ["package"] }, "package": { "oneOf": [ { "$ref": "#/definitions/inline-package" }, { "type": "array", "items": { "type": { "$ref": "#/definitions/inline-package" } } } ] } } }, "inline-package": { "required": ["name", "version"], "properties": { "name": { "type": "string", "description": "Package name, including 'vendor-name/' prefix." }, "type": { "type": "string" }, "target-dir": { "description": "DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.", "type": "string" }, "description": { "type": "string" }, "keywords": { "type": "array", "items": { "type": "string" } }, "homepage": { "type": "string", "format": "uri" }, "version": { "type": "string" }, "time": { "type": "string" }, "license": { "type": [ "string", "array" ] }, "authors": { "$ref": "#/definitions/authors" }, "require": { "type": "object", "additionalProperties": { "type": "string" } }, "replace": { "type": "object", "additionalProperties": { "type": "string" } }, "conflict": { "type": "object", "additionalProperties": { "type": "string" } }, "provide": { "type": "object", "additionalProperties": { "type": "string" } }, "require-dev": { "type": "object", "additionalProperties": { "type": "string" } }, "suggest": { "type": "object", "additionalProperties": { "type": "string" } }, "extra": { "type": ["object", "array"], "additionalProperties": true }, "autoload": { "$ref": "#/definitions/autoload" }, "archive": { "type": ["object"], "properties": { "exclude": { "type": "array" } } }, "bin": { "type": ["string", "array"], "description": "A set of files, or a single file, that should be treated as binaries and symlinked into bin-dir (from config).", "items": { "type": "string" } }, "include-path": { "type": ["array"], "description": "DEPRECATED: A list of directories which should get added to PHP's include path. This is only present to support legacy projects, and all new code should preferably use autoloading.", "items": { "type": "string" } }, "source": { "type": "object", "required": ["type", "url", "reference"], "properties": { "type": { "type": "string" }, "url": { "type": "string" }, "reference": { "type": "string" }, "mirrors": { "type": "array" } } }, "dist": { "type": "object", "required": ["type", "url"], "properties": { "type": { "type": "string" }, "url": { "type": "string" }, "reference": { "type": "string" }, "shasum": { "type": "string" }, "mirrors": { "type": "array" } } } }, "additionalProperties": true } } } composer-1.6.3/src/000077500000000000000000000000001323436022200141345ustar00rootroot00000000000000composer-1.6.3/src/Composer/000077500000000000000000000000001323436022200157235ustar00rootroot00000000000000composer-1.6.3/src/Composer/Autoload/000077500000000000000000000000001323436022200174735ustar00rootroot00000000000000composer-1.6.3/src/Composer/Autoload/AutoloadGenerator.php000066400000000000000000001027411323436022200236300ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Installer\InstallationManager; use Composer\IO\IOInterface; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\Util\Filesystem; use Composer\Script\ScriptEvents; /** * @author Igor Wiedler * @author Jordi Boggiano */ class AutoloadGenerator { /** * @var EventDispatcher */ private $eventDispatcher; /** * @var IOInterface */ private $io; /** * @var bool */ private $devMode = false; /** * @var bool */ private $classMapAuthoritative = false; /** * @var bool */ private $apcu = false; /** * @var bool */ private $runScripts = false; public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null) { $this->eventDispatcher = $eventDispatcher; $this->io = $io; } public function setDevMode($devMode = true) { $this->devMode = (bool) $devMode; } /** * Whether or not generated autoloader considers the class map * authoritative. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = (bool) $classMapAuthoritative; } /** * Whether or not generated autoloader considers APCu caching. * * @param bool $apcu */ public function setApcu($apcu) { $this->apcu = (bool) $apcu; } /** * Set whether to run scripts or not * * @param bool $runScripts */ public function setRunScripts($runScripts = true) { $this->runScripts = (bool) $runScripts; } public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '') { if ($this->classMapAuthoritative) { // Force scanPsr0Packages when classmap is authoritative $scanPsr0Packages = true; } if ($this->runScripts) { $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array( 'optimize' => (bool) $scanPsr0Packages, )); } $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); // Do not remove double realpath() calls. // Fixes failing Windows realpath() implementation. // See https://bugs.php.net/bug.php?id=72738 $basePath = $filesystem->normalizePath(realpath(realpath(getcwd()))); $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir')))); $useGlobalIncludePath = (bool) $config->get('use-include-path'); $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true'; $targetDir = $vendorPath.'/'.$targetDir; $filesystem->ensureDirectoryExists($targetDir); $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true); $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode); $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true); $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true); $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode); $namespacesFile = <<buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages()); $autoloads = $this->parseAutoloads($packageMap, $mainPackage); // Process the 'psr-0' base directories. foreach ($autoloads['psr-0'] as $namespace => $paths) { $exportedPaths = array(); foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $namespacesFile .= " $exportedPrefix => "; $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n"; } $namespacesFile .= ");\n"; // Process the 'psr-4' base directories. foreach ($autoloads['psr-4'] as $namespace => $paths) { $exportedPaths = array(); foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $psr4File .= " $exportedPrefix => "; $psr4File .= "array(".implode(', ', $exportedPaths)."),\n"; } $psr4File .= ");\n"; $classmapFile = <<getAutoload(); if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) { $levels = substr_count($filesystem->normalizePath($mainPackage->getTargetDir()), '/') + 1; $prefixes = implode(', ', array_map(function ($prefix) { return var_export($prefix, true); }, array_keys($mainAutoload['psr-0']))); $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true); $targetDirLoader = << $paths) { $namespacesToScan[$namespace][] = array('paths' => $paths, 'type' => $psrType); } } krsort($namespacesToScan); foreach ($namespacesToScan as $namespace => $groups) { foreach ($groups as $group) { foreach ($group['paths'] as $dir) { $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir); if (!is_dir($dir)) { continue; } $namespaceFilter = $namespace === '' ? null : $namespace; $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, $namespaceFilter, $classMap); } } } } foreach ($autoloads['classmap'] as $dir) { $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, null, $classMap); } ksort($classMap); foreach ($classMap as $class => $code) { $classmapFile .= ' '.var_export($class, true).' => '.$code; } $classmapFile .= ");\n"; if (!$suffix) { if (!$config->get('autoloader-suffix') && is_readable($vendorPath.'/autoload.php')) { $content = file_get_contents($vendorPath.'/autoload.php'); if (preg_match('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) { $suffix = $match[1]; } } if (!$suffix) { $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true)); } } file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile); file_put_contents($targetDir.'/autoload_psr4.php', $psr4File); file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile); $includePathFilePath = $targetDir.'/include_paths.php'; if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) { file_put_contents($includePathFilePath, $includePathFileContents); } elseif (file_exists($includePathFilePath)) { unlink($includePathFilePath); } $includeFilesFilePath = $targetDir.'/autoload_files.php'; if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) { file_put_contents($includeFilesFilePath, $includeFilesFileContents); } elseif (file_exists($includeFilesFilePath)) { unlink($includeFilesFilePath); } file_put_contents($targetDir.'/autoload_static.php', $this->getStaticFile($suffix, $targetDir, $vendorPath, $basePath, $staticPhpVersion)); file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix)); file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $staticPhpVersion)); $this->safeCopy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php'); $this->safeCopy(__DIR__.'/../../../LICENSE', $targetDir.'/LICENSE'); if ($this->runScripts) { $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array( 'optimize' => (bool) $scanPsr0Packages, )); } } private function addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist = null, $namespaceFilter = null, array $classMap = array()) { foreach ($this->generateClassMap($dir, $blacklist, $namespaceFilter) as $class => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n"; if (!isset($classMap[$class])) { $classMap[$class] = $pathCode; } elseif ($this->io && $classMap[$class] !== $pathCode && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($classMap[$class].' '.$path, '\\', '/'))) { $this->io->writeError( 'Warning: Ambiguous class resolution, "'.$class.'"'. ' was found in both "'.str_replace(array('$vendorDir . \'', "',\n"), array($vendorPath, ''), $classMap[$class]).'" and "'.$path.'", the first will be used.' ); } } return $classMap; } private function generateClassMap($dir, $blacklist = null, $namespaceFilter = null, $showAmbiguousWarning = true) { return ClassMapGenerator::createMap($dir, $blacklist, $showAmbiguousWarning ? $this->io : null, $namespaceFilter); } public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages) { // build package => install path map $packageMap = array(array($mainPackage, '')); foreach ($packages as $package) { if ($package instanceof AliasPackage) { continue; } $this->validatePackage($package); $packageMap[] = array( $package, $installationManager->getInstallPath($package), ); } return $packageMap; } /** * @param PackageInterface $package * * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings. */ protected function validatePackage(PackageInterface $package) { $autoload = $package->getAutoload(); if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) { $name = $package->getName(); $package->getTargetDir(); throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'."); } if (!empty($autoload['psr-4'])) { foreach ($autoload['psr-4'] as $namespace => $dirs) { if ($namespace !== '' && '\\' !== substr($namespace, -1)) { throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'."); } } } } /** * Compiles an ordered list of namespace => path mappings * * @param array $packageMap array of array(package, installDir-relative-to-composer.json) * @param PackageInterface $mainPackage root package instance * @return array array('psr-0' => array('Ns\\Foo' => array('installDir'))) */ public function parseAutoloads(array $packageMap, PackageInterface $mainPackage) { $mainPackageMap = array_shift($packageMap); $sortedPackageMap = $this->sortPackageMap($packageMap); $sortedPackageMap[] = $mainPackageMap; array_unshift($packageMap, $mainPackageMap); $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage); $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage); $classmap = $this->parseAutoloadsType(array_reverse($sortedPackageMap), 'classmap', $mainPackage); $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage); $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $mainPackage); krsort($psr0); krsort($psr4); return array( 'psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files, 'exclude-from-classmap' => $exclude, ); } /** * Registers an autoloader based on an autoload map returned by parseAutoloads * * @param array $autoloads see parseAutoloads return value * @return ClassLoader */ public function createLoader(array $autoloads) { $loader = new ClassLoader(); if (isset($autoloads['psr-0'])) { foreach ($autoloads['psr-0'] as $namespace => $path) { $loader->add($namespace, $path); } } if (isset($autoloads['psr-4'])) { foreach ($autoloads['psr-4'] as $namespace => $path) { $loader->addPsr4($namespace, $path); } } if (isset($autoloads['classmap'])) { $blacklist = null; if (!empty($autoloads['exclude-from-classmap'])) { $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}'; } foreach ($autoloads['classmap'] as $dir) { try { $loader->addClassMap($this->generateClassMap($dir, $blacklist, null, false)); } catch (\RuntimeException $e) { $this->io->writeError(''.$e->getMessage().''); } } } return $loader; } protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode) { $includePaths = array(); foreach ($packageMap as $item) { list($package, $installPath) = $item; if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) { $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir())); } foreach ($package->getIncludePaths() as $includePath) { $includePath = trim($includePath, '/'); $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath; } } if (!$includePaths) { return; } $includePathsCode = ''; foreach ($includePaths as $path) { $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n"; } return << $functionFile) { $filesCode .= ' ' . var_export($fileIdentifier, true) . ' => ' . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . ",\n"; } if (!$filesCode) { return false; } return <<isAbsolutePath($path)) { $path = $basePath . '/' . $path; } $path = $filesystem->normalizePath($path); $baseDir = ''; if (strpos($path.'/', $vendorPath.'/') === 0) { $path = substr($path, strlen($vendorPath)); $baseDir = '$vendorDir'; if ($path !== false) { $baseDir .= " . "; } } else { $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true)); if (!$filesystem->isAbsolutePath($path)) { $baseDir = '$baseDir . '; $path = '/' . $path; } } if (preg_match('/\.phar.+$/', $path)) { $baseDir = "'phar://' . " . $baseDir; } return $baseDir . (($path !== false) ? var_export($path, true) : ""); } protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix) { $lastChar = $vendorPathToTargetDirCode[strlen($vendorPathToTargetDirCode) - 1]; if ("'" === $lastChar || '"' === $lastChar) { $vendorPathToTargetDirCode = substr($vendorPathToTargetDirCode, 0, -1).'/autoload_real.php'.$lastChar; } else { $vendorPathToTargetDirCode .= " . '/autoload_real.php'"; } return <<= $staticPhpVersion && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if (\$useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit$suffix::getInitializer(\$loader)); } else { STATIC_INIT; if (!$this->classMapAuthoritative) { $file .= <<<'PSR04' $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } PSR04; } if ($useClassMap) { $file .= <<<'CLASSMAP' $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } CLASSMAP; } $file .= " }\n\n"; if ($this->classMapAuthoritative) { $file .= <<<'CLASSMAPAUTHORITATIVE' $loader->setClassMapAuthoritative(true); CLASSMAPAUTHORITATIVE; } if ($this->apcu) { $apcuPrefix = substr(base64_encode(md5(uniqid('', true), true)), 0, -3); $file .= <<setApcuPrefix('$apcuPrefix'); APCU; } if ($useGlobalIncludePath) { $file .= <<<'INCLUDEPATH' $loader->setUseIncludePath(true); INCLUDEPATH; } if ($targetDirLoader) { $file .= <<register($prependAutoloader); REGISTER_LOADER; if ($useIncludeFiles) { $file .= << \$file) { composerRequire$suffix(\$fileIdentifier, \$file); } INCLUDE_FILES; } $file .= << $path) { $loader->set($namespace, $path); } $map = require $targetDir . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require $targetDir . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $filesystem = new Filesystem(); $vendorPathCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/"; $appBaseDirCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/"; $absoluteVendorPathCode = ' => ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1); $absoluteAppBaseDirCode = ' => ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1); $initializer = ''; $prefix = "\0Composer\Autoload\ClassLoader\0"; $prefixLen = strlen($prefix); if (file_exists($targetDir . '/autoload_files.php')) { $maps = array('files' => require $targetDir . '/autoload_files.php'); } else { $maps = array(); } foreach ((array) $loader as $prop => $value) { if ($value && 0 === strpos($prop, $prefix)) { $maps[substr($prop, $prefixLen)] = $value; } } foreach ($maps as $prop => $value) { if (count($value) > 32767) { // Static arrays are limited to 32767 values on PHP 5.6 // See https://bugs.php.net/68057 $staticPhpVersion = 70000; } $value = var_export($value, true); $value = str_replace($absoluteVendorPathCode, $vendorPathCode, $value); $value = str_replace($absoluteAppBaseDirCode, $appBaseDirCode, $value); $value = ltrim(preg_replace('/^ */m', ' $0$0', $value)); $file .= sprintf(" public static $%s = %s;\n\n", $prop, $value); if ('files' !== $prop) { $initializer .= " \$loader->$prop = ComposerStaticInit$suffix::\$$prop;\n"; } } return $file . <<getAutoload(); if ($this->devMode && $package === $mainPackage) { $autoload = array_merge_recursive($autoload, $package->getDevAutoload()); } // skip misconfigured packages if (!isset($autoload[$type]) || !is_array($autoload[$type])) { continue; } if (null !== $package->getTargetDir() && $package !== $mainPackage) { $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir())); } foreach ($autoload[$type] as $namespace => $paths) { foreach ((array) $paths as $path) { if (($type === 'files' || $type === 'classmap' || $type === 'exclude-from-classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) { // remove target-dir from file paths of the root package if ($package === $mainPackage) { $targetDir = str_replace('\\', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '', $package->getTargetDir()))); $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/'); } else { // add target-dir from file paths that don't have it $path = $package->getTargetDir() . '/' . $path; } } if ($type === 'exclude-from-classmap') { // first escape user input $path = preg_replace('{/+}', '/', preg_quote(trim(strtr($path, '\\', '/'), '/'))); // add support for wildcards * and ** $path = str_replace('\\*\\*', '.+?', $path); $path = str_replace('\\*', '[^/]+?', $path); // add support for up-level relative paths $updir = null; $path = preg_replace_callback( '{^((?:(?:\\\\\\.){1,2}+/)+)}', function ($matches) use (&$updir) { if (isset($matches[1])) { // undo preg_quote for the matched string $updir = str_replace('\\.', '.', $matches[1]); } return ''; }, $path ); if (empty($installPath)) { $installPath = strtr(getcwd(), '\\', '/'); } $resolvedPath = realpath($installPath . '/' . $updir); $autoloads[] = preg_quote(strtr($resolvedPath, '\\', '/')) . '/' . $path; continue; } $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path; if ($type === 'files') { $autoloads[$this->getFileIdentifier($package, $path)] = $relativePath; continue; } elseif ($type === 'classmap') { $autoloads[] = $relativePath; continue; } $autoloads[$namespace][] = $relativePath; } } } return $autoloads; } protected function getFileIdentifier(PackageInterface $package, $path) { return md5($package->getName() . ':' . $path); } /** * Sorts packages by dependency weight * * Packages of equal weight retain the original order * * @param array $packageMap * @return array */ protected function sortPackageMap(array $packageMap) { $packages = array(); $paths = array(); $usageList = array(); foreach ($packageMap as $item) { list($package, $path) = $item; $name = $package->getName(); $packages[$name] = $package; $paths[$name] = $path; foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) { $target = $link->getTarget(); $usageList[$target][] = $name; } } $computing = array(); $computed = array(); $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) { // reusing computed importance if (isset($computed[$name])) { return $computed[$name]; } // canceling circular dependency if (isset($computing[$name])) { return 0; } $computing[$name] = true; $weight = 0; if (isset($usageList[$name])) { foreach ($usageList[$name] as $user) { $weight -= 1 - $computeImportance($user); } } unset($computing[$name]); $computed[$name] = $weight; return $weight; }; $weightList = array(); foreach ($packages as $name => $package) { $weight = $computeImportance($name); $weightList[$name] = $weight; } $stable_sort = function (&$array) { static $transform, $restore; $i = 0; if (!$transform) { $transform = function (&$v, $k) use (&$i) { $v = array($v, ++$i, $k, $v); }; $restore = function (&$v, $k) { $v = $v[3]; }; } array_walk($array, $transform); asort($array); array_walk($array, $restore); }; $stable_sort($weightList); $sortedPackageMap = array(); foreach (array_keys($weightList) as $name) { $sortedPackageMap[] = array($packages[$name], $paths[$name]); } return $sortedPackageMap; } /** * Copy file using stream_copy_to_stream to work around https://bugs.php.net/bug.php?id=6463 * * @param string $source * @param string $target */ protected function safeCopy($source, $target) { $source = fopen($source, 'r'); $target = fopen($target, 'w+'); stream_copy_to_stream($source, $target); fclose($source); fclose($target); } } composer-1.6.3/src/Composer/Autoload/ClassLoader.php000066400000000000000000000321541323436022200224050ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier * @author Jordi Boggiano * @see http://www.php-fig.org/psr/psr-0/ * @see http://www.php-fig.org/psr/psr-4/ */ class ClassLoader { // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); private $fallbackDirsPsr4 = array(); // PSR-0 private $prefixesPsr0 = array(); private $fallbackDirsPsr0 = array(); private $useIncludePath = false; private $classMap = array(); private $classMapAuthoritative = false; private $missingClasses = array(); private $apcuPrefix; public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', $this->prefixesPsr0); } return array(); } public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } public function getFallbackDirs() { return $this->fallbackDirsPsr0; } public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } public function getClassMap() { return $this->classMap; } /** * @param array $classMap Class to filename map */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 base directories */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); } /** * Unregisters this instance as an autoloader. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); } /** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath.'\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. */ function includeFile($file) { include $file; } composer-1.6.3/src/Composer/Autoload/ClassMapGenerator.php000066400000000000000000000203111323436022200235530ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * This file is copied from the Symfony package. * * (c) Fabien Potencier */ namespace Composer\Autoload; use Symfony\Component\Finder\Finder; use Composer\IO\IOInterface; use Composer\Util\Filesystem; /** * ClassMapGenerator * * @author Gyula Sallai * @author Jordi Boggiano */ class ClassMapGenerator { /** * Generate a class map file * * @param \Traversable $dirs Directories or a single path to search in * @param string $file The name of the class map file */ public static function dump($dirs, $file) { $maps = array(); foreach ($dirs as $dir) { $maps = array_merge($maps, static::createMap($dir)); } file_put_contents($file, sprintf('files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path); } else { throw new \RuntimeException( 'Could not scan for classes inside "'.$path. '" which does not appear to be a file nor a folder' ); } } $map = array(); $filesystem = new Filesystem(); $cwd = realpath(getcwd()); foreach ($path as $file) { $filePath = $file->getPathname(); if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) { continue; } if (!$filesystem->isAbsolutePath($filePath)) { $filePath = $cwd . '/' . $filePath; $filePath = $filesystem->normalizePath($filePath); } else { $filePath = preg_replace('{[\\\\/]{2,}}', '/', $filePath); } // check the realpath of the file against the blacklist as the path might be a symlink and the blacklist is realpath'd so symlink are resolved if ($blacklist && preg_match($blacklist, strtr(realpath($filePath), '\\', '/'))) { continue; } $classes = self::findClasses($filePath); foreach ($classes as $class) { // skip classes not within the given namespace prefix if (null !== $namespace && 0 !== strpos($class, $namespace)) { continue; } if (!isset($map[$class])) { $map[$class] = $filePath; } elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) { $io->writeError( 'Warning: Ambiguous class resolution, "'.$class.'"'. ' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.' ); } } } return $map; } /** * Extract the classes in the given file * * @param string $path The file to check * @throws \RuntimeException * @return array The found classes */ private static function findClasses($path) { $extraTypes = PHP_VERSION_ID < 50400 ? '' : '|trait'; if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>=')) { $extraTypes .= '|enum'; } // Use @ here instead of Silencer to actively suppress 'unhelpful' output // @link https://github.com/composer/composer/pull/4886 $contents = @php_strip_whitespace($path); if (!$contents) { if (!file_exists($path)) { $message = 'File at "%s" does not exist, check your classmap definitions'; } elseif (!is_readable($path)) { $message = 'File at "%s" is not readable, check its permissions'; } elseif ('' === trim(file_get_contents($path))) { // The input file was really empty and thus contains no classes return array(); } else { $message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted'; } $error = error_get_last(); if (isset($error['message'])) { $message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message']; } throw new \RuntimeException(sprintf($message, $path)); } // return early if there is no chance of matching anything in this file if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) { return array(); } // strip heredocs/nowdocs $contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents); // strip strings $contents = preg_replace('{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents); // strip leading non-php code if needed if (substr($contents, 0, 2) !== '.+<\?}s', '?>'); if (false !== $pos && false === strpos(substr($contents, $pos), '])(?Pclass|interface'.$extraTypes.') \s++ (?P[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+) | \b(?])(?Pnamespace) (?P\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;] ) }ix', $contents, $matches); $classes = array(); $namespace = ''; for ($i = 0, $len = count($matches['type']); $i < $len; $i++) { if (!empty($matches['ns'][$i])) { $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\'; } else { $name = $matches['name'][$i]; // skip anon classes extending/implementing if ($name === 'extends' || $name === 'implements') { continue; } if ($name[0] === ':') { // This is an XHP class, https://github.com/facebook/xhp $name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1); } elseif ($matches['type'][$i] === 'enum') { // In Hack, something like: // enum Foo: int { HERP = '123'; } // The regex above captures the colon, which isn't part of // the class name. $name = rtrim($name, ':'); } $classes[] = ltrim($namespace . $name, '\\'); } } return $classes; } } composer-1.6.3/src/Composer/Cache.php000066400000000000000000000163661323436022200174530ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\IO\IOInterface; use Composer\Util\Filesystem; use Composer\Util\Silencer; use Symfony\Component\Finder\Finder; /** * Reads/writes to a filesystem cache * * @author Jordi Boggiano */ class Cache { private static $cacheCollected = false; private $io; private $root; private $enabled = true; private $whitelist; private $filesystem; /** * @param IOInterface $io * @param string $cacheDir location of the cache * @param string $whitelist List of characters that are allowed in path names (used in a regex character class) * @param Filesystem $filesystem optional filesystem instance */ public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null) { $this->io = $io; $this->root = rtrim($cacheDir, '/\\') . '/'; $this->whitelist = $whitelist; $this->filesystem = $filesystem ?: new Filesystem(); if (preg_match('{(^|[\\\\/])(\$null|NUL|/dev/null)([\\\\/]|$)}', $cacheDir)) { $this->enabled = false; return; } if ( (!is_dir($this->root) && !Silencer::call('mkdir', $this->root, 0777, true)) || !is_writable($this->root) ) { $this->io->writeError('Cannot create cache directory ' . $this->root . ', or directory is not writable. Proceeding without cache'); $this->enabled = false; } } public function isEnabled() { return $this->enabled; } public function getRoot() { return $this->root; } public function read($file) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if ($this->enabled && file_exists($this->root . $file)) { $this->io->writeError('Reading '.$this->root . $file.' from cache', true, IOInterface::DEBUG); return file_get_contents($this->root . $file); } return false; } public function write($file, $contents) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); $this->io->writeError('Writing '.$this->root . $file.' into cache', true, IOInterface::DEBUG); try { return file_put_contents($this->root . $file, $contents); } catch (\ErrorException $e) { $this->io->writeError('Failed to write into cache: '.$e->getMessage().'', true, IOInterface::DEBUG); if (preg_match('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) { // Remove partial file. unlink($this->root . $file); $message = sprintf( 'Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$u bytes of free space available', $this->root . $file, $m[1], $m[2], @disk_free_space($this->root . dirname($file)) ); $this->io->writeError($message); return false; } throw $e; } } return false; } /** * Copy a file into the cache */ public function copyFrom($file, $source) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); $this->filesystem->ensureDirectoryExists(dirname($this->root . $file)); if (!file_exists($source)) { $this->io->writeError(''.$source.' does not exist, can not write into cache'); } elseif ($this->io->isDebug()) { $this->io->writeError('Writing '.$this->root . $file.' into cache from '.$source); } return copy($source, $this->root . $file); } return false; } /** * Copy a file out of the cache */ public function copyTo($file, $target) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if ($this->enabled && file_exists($this->root . $file)) { try { touch($this->root . $file, filemtime($this->root . $file), time()); } catch (\ErrorException $e) { // fallback in case the above failed due to incorrect ownership // see https://github.com/composer/composer/issues/4070 Silencer::call('touch', $this->root . $file); } $this->io->writeError('Reading '.$this->root . $file.' from cache', true, IOInterface::DEBUG); return copy($this->root . $file, $target); } return false; } public function gcIsNecessary() { return (!self::$cacheCollected && !mt_rand(0, 50)); } public function remove($file) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if ($this->enabled && file_exists($this->root . $file)) { return $this->filesystem->unlink($this->root . $file); } return false; } public function clear() { if ($this->enabled) { return $this->filesystem->removeDirectory($this->root); } return false; } public function gc($ttl, $maxSize) { if ($this->enabled) { $expire = new \DateTime(); $expire->modify('-'.$ttl.' seconds'); $finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s')); foreach ($finder as $file) { $this->filesystem->unlink($file->getPathname()); } $totalSize = $this->filesystem->size($this->root); if ($totalSize > $maxSize) { $iterator = $this->getFinder()->sortByAccessedTime()->getIterator(); while ($totalSize > $maxSize && $iterator->valid()) { $filepath = $iterator->current()->getPathname(); $totalSize -= $this->filesystem->size($filepath); $this->filesystem->unlink($filepath); $iterator->next(); } } self::$cacheCollected = true; return true; } return false; } public function sha1($file) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if ($this->enabled && file_exists($this->root . $file)) { return sha1_file($this->root . $file); } return false; } public function sha256($file) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if ($this->enabled && file_exists($this->root . $file)) { return hash_file('sha256', $this->root . $file); } return false; } protected function getFinder() { return Finder::create()->in($this->root)->files(); } } composer-1.6.3/src/Composer/Command/000077500000000000000000000000001323436022200173015ustar00rootroot00000000000000composer-1.6.3/src/Composer/Command/AboutCommand.php000066400000000000000000000021431323436022200223630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class AboutCommand extends BaseCommand { protected function configure() { $this ->setName('about') ->setDescription('Shows the short information about Composer.') ->setHelp(<<php composer.phar about EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $this->getIO()->write(<<Composer - Package Management for PHP Composer is a dependency manager tracking local dependencies of your projects and libraries. See https://getcomposer.org/ for more information. EOT ); } } composer-1.6.3/src/Composer/Command/ArchiveCommand.php000066400000000000000000000146531323436022200227030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Composer; use Composer\Repository\CompositeRepository; use Composer\Repository\RepositoryFactory; use Composer\Script\ScriptEvents; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Creates an archive of a package for distribution. * * @author Nils Adermann */ class ArchiveCommand extends BaseCommand { protected function configure() { $this ->setName('archive') ->setDescription('Creates an archive of this composer package.') ->setDefinition(array( new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project'), new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar or zip'), new InputOption('dir', null, InputOption::VALUE_REQUIRED, 'Write the archive to this directory'), new InputOption('file', null, InputOption::VALUE_REQUIRED, 'Write the archive with the given file name.' .' Note that the format will be appended.'), new InputOption('ignore-filters', false, InputOption::VALUE_NONE, 'Ignore filters when saving package'), )) ->setHelp(<<archive command creates an archive of the specified format containing the files and directories of the Composer project or the specified package in the specified version and writes it to the specified directory. php composer.phar archive [--format=zip] [--dir=/foo] [package [version]] EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $composer = $this->getComposer(false); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD); } if (null === $input->getOption('format')) { $input->setOption('format', $config->get('archive-format')); } if (null === $input->getOption('dir')) { $input->setOption('dir', $config->get('archive-dir')); } $returnCode = $this->archive( $this->getIO(), $config, $input->getArgument('package'), $input->getArgument('version'), $input->getOption('format'), $input->getOption('dir'), $input->getOption('file'), $input->getOption('ignore-filters'), $composer ); if (0 === $returnCode && $composer) { $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD); } return $returnCode; } protected function archive(IOInterface $io, Config $config, $packageName = null, $version = null, $format = 'tar', $dest = '.', $fileName = null, $ignoreFilters = false, Composer $composer = null) { if ($composer) { $archiveManager = $composer->getArchiveManager(); } else { $factory = new Factory; $downloadManager = $factory->createDownloadManager($io, $config); $archiveManager = $factory->createArchiveManager($config, $downloadManager); } if ($packageName) { $package = $this->selectPackage($io, $packageName, $version); if (!$package) { return 1; } } else { $package = $this->getComposer()->getPackage(); } $io->writeError('Creating the archive into "'.$dest.'".'); $packagePath = $archiveManager->archive($package, $format, $dest, $fileName, $ignoreFilters); $fs = new Filesystem; $shortPath = $fs->findShortestPath(getcwd(), $packagePath, true); $io->writeError('Created: ', false); $io->write(strlen($shortPath) < strlen($packagePath) ? $shortPath : $packagePath); return 0; } protected function selectPackage(IOInterface $io, $packageName, $version = null) { $io->writeError('Searching for the specified package.'); if ($composer = $this->getComposer(false)) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $repo = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories())); } else { $defaultRepos = RepositoryFactory::defaultRepos($this->getIO()); $io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos))); $repo = new CompositeRepository($defaultRepos); } $packages = $repo->findPackages($packageName, $version); if (count($packages) > 1) { $package = reset($packages); $io->writeError('Found multiple matches, selected '.$package->getPrettyString().'.'); $io->writeError('Alternatives were '.implode(', ', array_map(function ($p) { return $p->getPrettyString(); }, $packages)).'.'); $io->writeError('Please use a more specific constraint to pick a different package.'); } elseif ($packages) { $package = reset($packages); $io->writeError('Found an exact match '.$package->getPrettyString().'.'); } else { $io->writeError('Could not find a package matching '.$packageName.'.'); return false; } return $package; } } composer-1.6.3/src/Composer/Command/BaseCommand.php000066400000000000000000000110121323436022200221560ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Config; use Composer\Console\Application; use Composer\IO\IOInterface; use Composer\IO\NullIO; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Command\Command; /** * Base class for Composer commands * * @author Ryan Weaver * @author Konstantin Kudryashov */ abstract class BaseCommand extends Command { /** * @var Composer */ private $composer; /** * @var IOInterface */ private $io; /** * @param bool $required * @param bool|null $disablePlugins * @throws \RuntimeException * @return Composer */ public function getComposer($required = true, $disablePlugins = null) { if (null === $this->composer) { $application = $this->getApplication(); if ($application instanceof Application) { /* @var $application Application */ $this->composer = $application->getComposer($required, $disablePlugins); } elseif ($required) { throw new \RuntimeException( 'Could not create a Composer\Composer instance, you must inject '. 'one if this command is not used with a Composer\Console\Application instance' ); } } return $this->composer; } /** * @param Composer $composer */ public function setComposer(Composer $composer) { $this->composer = $composer; } /** * Removes the cached composer instance */ public function resetComposer() { $this->composer = null; $this->getApplication()->resetComposer(); } /** * Whether or not this command is meant to call another command. * * This is mainly needed to avoid duplicated warnings messages. * * @return bool */ public function isProxyCommand() { return false; } /** * @return IOInterface */ public function getIO() { if (null === $this->io) { $application = $this->getApplication(); if ($application instanceof Application) { /* @var $application Application */ $this->io = $application->getIO(); } else { $this->io = new NullIO(); } } return $this->io; } /** * @param IOInterface $io */ public function setIO(IOInterface $io) { $this->io = $io; } /** * {@inheritDoc} */ protected function initialize(InputInterface $input, OutputInterface $output) { if (true === $input->hasParameterOption(array('--no-ansi')) && $input->hasOption('no-progress')) { $input->setOption('no-progress', true); } parent::initialize($input, $output); } /** * Returns preferSource and preferDist values based on the configuration. * * @param Config $config * @param InputInterface $input * @param bool $keepVcsRequiresPreferSource * * @return bool[] An array composed of the preferSource and preferDist values */ protected function getPreferredInstallOptions(Config $config, InputInterface $input, $keepVcsRequiresPreferSource = false) { $preferSource = false; $preferDist = false; switch ($config->get('preferred-install')) { case 'source': $preferSource = true; break; case 'dist': $preferDist = true; break; case 'auto': default: // noop break; } if ($input->getOption('prefer-source') || $input->getOption('prefer-dist') || ($keepVcsRequiresPreferSource && $input->hasOption('keep-vcs') && $input->getOption('keep-vcs'))) { $preferSource = $input->getOption('prefer-source') || ($keepVcsRequiresPreferSource && $input->hasOption('keep-vcs') && $input->getOption('keep-vcs')); $preferDist = $input->getOption('prefer-dist'); } return array($preferSource, $preferDist); } } composer-1.6.3/src/Composer/Command/BaseDependencyCommand.php000066400000000000000000000233211323436022200241630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\DependencyResolver\Pool; use Composer\Package\Link; use Composer\Package\PackageInterface; use Composer\Repository\ArrayRepository; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Composer\Package\Version\VersionParser; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Base implementation for commands mapping dependency relationships. * * @author Niels Keurentjes */ class BaseDependencyCommand extends BaseCommand { const ARGUMENT_PACKAGE = 'package'; const ARGUMENT_CONSTRAINT = 'constraint'; const OPTION_RECURSIVE = 'recursive'; const OPTION_TREE = 'tree'; protected $colors; /** * Set common options and arguments. */ protected function configure() { $this->setDefinition(array( new InputArgument(self::ARGUMENT_PACKAGE, InputArgument::REQUIRED, 'Package to inspect'), new InputArgument(self::ARGUMENT_CONSTRAINT, InputArgument::OPTIONAL, 'Optional version constraint', '*'), new InputOption(self::OPTION_RECURSIVE, 'r', InputOption::VALUE_NONE, 'Recursively resolves up to the root package'), new InputOption(self::OPTION_TREE, 't', InputOption::VALUE_NONE, 'Prints the results as a nested tree'), )); } /** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output * @param bool $inverted Whether to invert matching process (why-not vs why behaviour) * @return int|null Exit code of the operation. */ protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false) { // Emit command event on startup $composer = $this->getComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, $this->getName(), $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); // Prepare repositories and set up a pool $platformOverrides = $composer->getConfig()->get('platform') ?: array(); $repository = new CompositeRepository(array( new ArrayRepository(array($composer->getPackage())), $composer->getRepositoryManager()->getLocalRepository(), new PlatformRepository(array(), $platformOverrides), )); $pool = new Pool(); $pool->addRepository($repository); // Parse package name and constraint list($needle, $textConstraint) = array_pad( explode(':', $input->getArgument(self::ARGUMENT_PACKAGE)), 2, $input->getArgument(self::ARGUMENT_CONSTRAINT) ); // Find packages that are or provide the requested package first $packages = $pool->whatProvides($needle); if (empty($packages)) { throw new \InvalidArgumentException(sprintf('Could not find package "%s" in your project', $needle)); } // If the version we ask for is not installed then we need to locate it in remote repos and add it. // This is needed for why-not to resolve conflicts from an uninstalled version against installed packages. if (!$repository->findPackage($needle, $textConstraint)) { $defaultRepos = new CompositeRepository(RepositoryFactory::defaultRepos($this->getIO())); if ($match = $defaultRepos->findPackage($needle, $textConstraint)) { $repository->addRepository(new ArrayRepository(array(clone $match))); } } // Include replaced packages for inverted lookups as they are then the actual starting point to consider $needles = array($needle); if ($inverted) { foreach ($packages as $package) { $needles = array_merge($needles, array_map(function (Link $link) { return $link->getTarget(); }, $package->getReplaces())); } } // Parse constraint if one was supplied if ('*' !== $textConstraint) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($textConstraint); } else { $constraint = null; } // Parse rendering options $renderTree = $input->getOption(self::OPTION_TREE); $recursive = $renderTree || $input->getOption(self::OPTION_RECURSIVE); // Resolve dependencies $results = $repository->getDependents($needles, $constraint, $inverted, $recursive); if (empty($results)) { $extra = (null !== $constraint) ? sprintf(' in versions %smatching %s', $inverted ? 'not ' : '', $textConstraint) : ''; $this->getIO()->writeError(sprintf('There is no installed package depending on "%s"%s', $needle, $extra)); } elseif ($renderTree) { $this->initStyles($output); $root = $packages[0]; $this->getIO()->write(sprintf('%s %s %s', $root->getPrettyName(), $root->getPrettyVersion(), $root->getDescription())); $this->printTree($results); } else { $this->printTable($output, $results); } return 0; } /** * Assembles and prints a bottom-up table of the dependencies. * * @param OutputInterface $output * @param array $results */ protected function printTable(OutputInterface $output, $results) { $table = array(); $doubles = array(); do { $queue = array(); $rows = array(); foreach ($results as $result) { /** * @var PackageInterface $package * @var Link $link */ list($package, $link, $children) = $result; $unique = (string) $link; if (isset($doubles[$unique])) { continue; } $doubles[$unique] = true; $version = (strpos($package->getPrettyVersion(), 'No version set') === 0) ? '-' : $package->getPrettyVersion(); $rows[] = array($package->getPrettyName(), $version, $link->getDescription(), sprintf('%s (%s)', $link->getTarget(), $link->getPrettyConstraint())); if ($children) { $queue = array_merge($queue, $children); } } $results = $queue; $table = array_merge($rows, $table); } while (!empty($results)); // Render table $renderer = new Table($output); $renderer->setStyle('compact'); $renderer->getStyle()->setVerticalBorderChar(''); $renderer->getStyle()->setCellRowContentFormat('%s '); $renderer->setRows($table)->render(); } /** * Init styles for tree * * @param OutputInterface $output */ protected function initStyles(OutputInterface $output) { $this->colors = array( 'green', 'yellow', 'cyan', 'magenta', 'blue', ); foreach ($this->colors as $color) { $style = new OutputFormatterStyle($color); $output->getFormatter()->setStyle($color, $style); } } /** * Recursively prints a tree of the selected results. * * @param array $results Results to be printed at this level. * @param string $prefix Prefix of the current tree level. * @param int $level Current level of recursion. */ protected function printTree($results, $prefix = '', $level = 1) { $count = count($results); $idx = 0; foreach ($results as $result) { /** * @var PackageInterface $package * @var Link $link * @var array|bool $children */ list($package, $link, $children) = $result; $color = $this->colors[$level % count($this->colors)]; $prevColor = $this->colors[($level - 1) % count($this->colors)]; $isLast = (++$idx == $count); $versionText = (strpos($package->getPrettyVersion(), 'No version set') === 0) ? '' : $package->getPrettyVersion(); $packageText = rtrim(sprintf('<%s>%s %s', $color, $package->getPrettyName(), $versionText)); $linkText = sprintf('%s <%s>%s %s', $link->getDescription(), $prevColor, $link->getTarget(), $link->getPrettyConstraint()); $circularWarn = $children === false ? '(circular dependency aborted here)' : ''; $this->writeTreeLine(rtrim(sprintf("%s%s%s (%s) %s", $prefix, $isLast ? '└──' : '├──', $packageText, $linkText, $circularWarn))); if ($children) { $this->printTree($children, $prefix . ($isLast ? ' ' : '│ '), $level + 1); } } } private function writeTreeLine($line) { $io = $this->getIO(); if (!$io->isDecorated()) { $line = str_replace(array('â””', '├', '──', '│'), array('`-', '|-', '-', '|'), $line); } $io->write($line); } } composer-1.6.3/src/Composer/Command/CheckPlatformReqsCommand.php000066400000000000000000000116251323436022200246730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Package\Link; use Composer\Package\PackageInterface; use Composer\Semver\Constraint\Constraint; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Composer\Repository\PlatformRepository; class CheckPlatformReqsCommand extends BaseCommand { protected function configure() { $this->setName('check-platform-reqs') ->setDescription('Check that platform requirements are satisfied.') ->setHelp(<<php composer.phar check-platform-reqs EOT ); } protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(); $repos = $composer->getRepositoryManager()->getLocalRepository(); $allPackages = array_merge(array($composer->getPackage()), $repos->getPackages()); $requires = $composer->getPackage()->getDevRequires(); foreach ($requires as $require => $link) { $requires[$require] = array($link); } /** * @var PackageInterface $package */ foreach ($allPackages as $package) { foreach ($package->getRequires() as $require => $link) { $requires[$require][] = $link; } } ksort($requires); $platformRepo = new PlatformRepository(array(), array()); $currentPlatformPackages = $platformRepo->getPackages(); $currentPlatformPackageMap = array(); /** * @var PackageInterface $currentPlatformPackage */ foreach ($currentPlatformPackages as $currentPlatformPackage) { $currentPlatformPackageMap[$currentPlatformPackage->getName()] = $currentPlatformPackage; } $results = array(); $exitCode = 0; /** * @var Link $require */ foreach ($requires as $require => $links) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $require)) { if (isset($currentPlatformPackageMap[$require])) { $pass = true; $version = $currentPlatformPackageMap[$require]->getVersion(); foreach ($links as $link) { if (!$link->getConstraint()->matches(new Constraint('=', $version))) { $results[] = array( $currentPlatformPackageMap[$require]->getPrettyName(), $currentPlatformPackageMap[$require]->getPrettyVersion(), $link, 'failed', ); $pass = false; $exitCode = max($exitCode, 1); } } if ($pass) { $results[] = array( $currentPlatformPackageMap[$require]->getPrettyName(), $currentPlatformPackageMap[$require]->getPrettyVersion(), null, 'success', ); } } else { $results[] = array( $require, 'n/a', $links[0], 'missing', ); $exitCode = max($exitCode, 2); } } } $this->printTable($output, $results); return $exitCode; } protected function printTable(OutputInterface $output, $results) { $table = array(); $rows = array(); foreach ($results as $result) { /** * @var Link|null $link */ list($platformPackage, $version, $link, $status) = $result; $rows[] = array( $platformPackage, $version, $link ? sprintf('%s %s %s (%s)', $link->getSource(), $link->getDescription(), $link->getTarget(), $link->getPrettyConstraint()) : '', $status, ); } $table = array_merge($rows, $table); // Render table $renderer = new Table($output); $renderer->setStyle('compact'); $renderer->getStyle()->setVerticalBorderChar(''); $renderer->getStyle()->setCellRowContentFormat('%s '); $renderer->setRows($table)->render(); } } composer-1.6.3/src/Composer/Command/ClearCacheCommand.php000066400000000000000000000037671323436022200233000ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Cache; use Composer\Factory; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author David Neilsen */ class ClearCacheCommand extends BaseCommand { protected function configure() { $this ->setName('clear-cache') ->setAliases(array('clearcache')) ->setDescription('Clears composer\'s internal package cache.') ->setHelp(<<clear-cache deletes all cached packages from composer's cache directory. EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $io = $this->getIO(); $cachePaths = array( 'cache-vcs-dir' => $config->get('cache-vcs-dir'), 'cache-repo-dir' => $config->get('cache-repo-dir'), 'cache-files-dir' => $config->get('cache-files-dir'), 'cache-dir' => $config->get('cache-dir'), ); foreach ($cachePaths as $key => $cachePath) { $cachePath = realpath($cachePath); if (!$cachePath) { $io->writeError("Cache directory does not exist ($key): $cachePath"); continue; } $cache = new Cache($io, $cachePath); if (!$cache->isEnabled()) { $io->writeError("Cache is not enabled ($key): $cachePath"); continue; } $io->writeError("Clearing cache ($key): $cachePath"); $cache->clear(); } $io->writeError('All caches cleared.'); } } composer-1.6.3/src/Composer/Command/ConfigCommand.php000066400000000000000000000643311323436022200225250ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Config; use Composer\Config\JsonConfigSource; use Composer\Factory; use Composer\Json\JsonFile; use Composer\Semver\VersionParser; use Composer\Package\BasePackage; /** * @author Joshua Estes * @author Jordi Boggiano */ class ConfigCommand extends BaseCommand { /** * @var Config */ protected $config; /** * @var JsonFile */ protected $configFile; /** * @var JsonConfigSource */ protected $configSource; /** * @var JsonFile */ protected $authConfigFile; /** * @var JsonConfigSource */ protected $authConfigSource; /** * {@inheritDoc} */ protected function configure() { $this ->setName('config') ->setDescription('Sets config options.') ->setDefinition(array( new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'), new InputOption('editor', 'e', InputOption::VALUE_NONE, 'Open editor'), new InputOption('auth', 'a', InputOption::VALUE_NONE, 'Affect auth config file (only used for --editor)'), new InputOption('unset', null, InputOption::VALUE_NONE, 'Unset the given setting-key'), new InputOption('list', 'l', InputOption::VALUE_NONE, 'List configuration settings'), new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json'), new InputOption('absolute', null, InputOption::VALUE_NONE, 'Returns absolute paths when fetching *-dir config values instead of relative'), new InputArgument('setting-key', null, 'Setting key'), new InputArgument('setting-value', InputArgument::IS_ARRAY, 'Setting value'), )) ->setHelp(<<%command.full_name% bin-dir bin/ To read a config setting: %command.full_name% bin-dir Outputs: bin To edit the global config.json file: %command.full_name% --global To add a repository: %command.full_name% repositories.foo vcs https://bar.com To remove a repository (repo is a short alias for repositories): %command.full_name% --unset repo.foo To disable packagist: %command.full_name% repo.packagist false You can alter repositories in the global config.json file by passing in the --global option. To edit the file in an external editor: %command.full_name% --editor To choose your editor you can set the "EDITOR" env variable. To get a list of configuration values in the file: %command.full_name% --list You can always pass more than one option. As an example, if you want to edit the global config.json file. %command.full_name% --editor --global EOT ) ; } /** * {@inheritDoc} */ protected function initialize(InputInterface $input, OutputInterface $output) { parent::initialize($input, $output); if ($input->getOption('global') && null !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $io = $this->getIO(); $this->config = Factory::createConfig($io); // Get the local composer.json, global config.json, or if the user // passed in a file to use $configFile = $input->getOption('global') ? ($this->config->get('home') . '/config.json') : ($input->getOption('file') ?: Factory::getComposerFile()); // Create global composer.json if this was invoked using `composer global config` if ( ($configFile === 'composer.json' || $configFile === './composer.json') && !file_exists($configFile) && realpath(getcwd()) === realpath($this->config->get('home')) ) { file_put_contents($configFile, "{\n}\n"); } $this->configFile = new JsonFile($configFile, null, $io); $this->configSource = new JsonConfigSource($this->configFile); $authConfigFile = $input->getOption('global') ? ($this->config->get('home') . '/auth.json') : dirname(realpath($configFile)) . '/auth.json'; $this->authConfigFile = new JsonFile($authConfigFile, null, $io); $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true); // Initialize the global file if it's not there, ignoring any warnings or notices if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(array('config' => new \ArrayObject)); Silencer::call('chmod', $this->configFile->getPath(), 0600); } if ($input->getOption('global') && !$this->authConfigFile->exists()) { touch($this->authConfigFile->getPath()); $this->authConfigFile->write(array('bitbucket-oauth' => new \ArrayObject, 'github-oauth' => new \ArrayObject, 'gitlab-oauth' => new \ArrayObject, 'gitlab-token' => new \ArrayObject, 'http-basic' => new \ArrayObject)); Silencer::call('chmod', $this->authConfigFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile)); } } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { // Open file in editor if ($input->getOption('editor')) { $editor = escapeshellcmd(getenv('EDITOR')); if (!$editor) { if (Platform::isWindows()) { $editor = 'notepad'; } else { foreach (array('editor', 'vim', 'vi', 'nano', 'pico', 'ed') as $candidate) { if (exec('which '.$candidate)) { $editor = $candidate; break; } } } } $file = $input->getOption('auth') ? $this->authConfigFile->getPath() : $this->configFile->getPath(); system($editor . ' ' . $file . (Platform::isWindows() ? '' : ' > `tty`')); return 0; } if (!$input->getOption('global')) { $this->config->merge($this->configFile->read()); $this->config->merge(array('config' => $this->authConfigFile->exists() ? $this->authConfigFile->read() : array())); } // List the configuration of the file settings if ($input->getOption('list')) { $this->listConfiguration($this->config->all(), $this->config->raw(), $output); return 0; } $settingKey = $input->getArgument('setting-key'); if (!$settingKey) { return 0; } // If the user enters in a config variable, parse it and save to file if (array() !== $input->getArgument('setting-value') && $input->getOption('unset')) { throw new \RuntimeException('You can not combine a setting value with --unset'); } // show the value if no value is provided if (array() === $input->getArgument('setting-value') && !$input->getOption('unset')) { $properties = array('name', 'type', 'description', 'homepage', 'version', 'minimum-stability', 'prefer-stable', 'keywords', 'license', 'extra'); $rawData = $this->configFile->read(); $data = $this->config->all(); if (preg_match('/^repos?(?:itories)?(?:\.(.+))?/', $settingKey, $matches)) { if (!isset($matches[1]) || $matches[1] === '') { $value = isset($data['repositories']) ? $data['repositories'] : array(); } else { if (!isset($data['repositories'][$matches[1]])) { throw new \InvalidArgumentException('There is no '.$matches[1].' repository defined'); } $value = $data['repositories'][$matches[1]]; } } elseif (strpos($settingKey, '.')) { $bits = explode('.', $settingKey); if ($bits[0] === 'extra') { $data = $rawData; } else { $data = $data['config']; } $match = false; foreach ($bits as $bit) { $key = isset($key) ? $key.'.'.$bit : $bit; $match = false; if (isset($data[$key])) { $match = true; $data = $data[$key]; unset($key); } } if (!$match) { throw new \RuntimeException($settingKey.' is not defined.'); } $value = $data; } elseif (isset($data['config'][$settingKey])) { $value = $this->config->get($settingKey, $input->getOption('absolute') ? 0 : Config::RELATIVE_PATHS); } elseif (in_array($settingKey, $properties, true) && isset($rawData[$settingKey])) { $value = $rawData[$settingKey]; } else { throw new \RuntimeException($settingKey.' is not defined'); } if (is_array($value)) { $value = json_encode($value); } $this->getIO()->write($value); return 0; } $values = $input->getArgument('setting-value'); // what the user is trying to add/change $booleanValidator = function ($val) { return in_array($val, array('true', 'false', '1', '0'), true); }; $booleanNormalizer = function ($val) { return $val !== 'false' && (bool) $val; }; // handle config values $uniqueConfigValues = array( 'process-timeout' => array('is_numeric', 'intval'), 'use-include-path' => array($booleanValidator, $booleanNormalizer), 'preferred-install' => array( function ($val) { return in_array($val, array('auto', 'source', 'dist'), true); }, function ($val) { return $val; }, ), 'store-auths' => array( function ($val) { return in_array($val, array('true', 'false', 'prompt'), true); }, function ($val) { if ('prompt' === $val) { return 'prompt'; } return $val !== 'false' && (bool) $val; }, ), 'notify-on-install' => array($booleanValidator, $booleanNormalizer), 'vendor-dir' => array('is_string', function ($val) { return $val; }), 'bin-dir' => array('is_string', function ($val) { return $val; }), 'archive-dir' => array('is_string', function ($val) { return $val; }), 'archive-format' => array('is_string', function ($val) { return $val; }), 'data-dir' => array('is_string', function ($val) { return $val; }), 'cache-dir' => array('is_string', function ($val) { return $val; }), 'cache-files-dir' => array('is_string', function ($val) { return $val; }), 'cache-repo-dir' => array('is_string', function ($val) { return $val; }), 'cache-vcs-dir' => array('is_string', function ($val) { return $val; }), 'cache-ttl' => array('is_numeric', 'intval'), 'cache-files-ttl' => array('is_numeric', 'intval'), 'cache-files-maxsize' => array( function ($val) { return preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val) > 0; }, function ($val) { return $val; }, ), 'bin-compat' => array( function ($val) { return in_array($val, array('auto', 'full')); }, function ($val) { return $val; }, ), 'discard-changes' => array( function ($val) { return in_array($val, array('stash', 'true', 'false', '1', '0'), true); }, function ($val) { if ('stash' === $val) { return 'stash'; } return $val !== 'false' && (bool) $val; }, ), 'autoloader-suffix' => array('is_string', function ($val) { return $val === 'null' ? null : $val; }), 'sort-packages' => array($booleanValidator, $booleanNormalizer), 'optimize-autoloader' => array($booleanValidator, $booleanNormalizer), 'classmap-authoritative' => array($booleanValidator, $booleanNormalizer), 'apcu-autoloader' => array($booleanValidator, $booleanNormalizer), 'prepend-autoloader' => array($booleanValidator, $booleanNormalizer), 'disable-tls' => array($booleanValidator, $booleanNormalizer), 'secure-http' => array($booleanValidator, $booleanNormalizer), 'cafile' => array( function ($val) { return file_exists($val) && is_readable($val); }, function ($val) { return $val === 'null' ? null : $val; }, ), 'capath' => array( function ($val) { return is_dir($val) && is_readable($val); }, function ($val) { return $val === 'null' ? null : $val; }, ), 'github-expose-hostname' => array($booleanValidator, $booleanNormalizer), 'htaccess-protect' => array($booleanValidator, $booleanNormalizer), ); $multiConfigValues = array( 'github-protocols' => array( function ($vals) { if (!is_array($vals)) { return 'array expected'; } foreach ($vals as $val) { if (!in_array($val, array('git', 'https', 'ssh'))) { return 'valid protocols include: git, https, ssh'; } } return true; }, function ($vals) { return $vals; }, ), 'github-domains' => array( function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, function ($vals) { return $vals; }, ), 'gitlab-domains' => array( function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, function ($vals) { return $vals; }, ), ); if ($input->getOption('unset') && (isset($uniqueConfigValues[$settingKey]) || isset($multiConfigValues[$settingKey]))) { return $this->configSource->removeConfigSetting($settingKey); } if (isset($uniqueConfigValues[$settingKey])) { return $this->handleSingleValue($settingKey, $uniqueConfigValues[$settingKey], $values, 'addConfigSetting'); } if (isset($multiConfigValues[$settingKey])) { return $this->handleMultiValue($settingKey, $multiConfigValues[$settingKey], $values, 'addConfigSetting'); } // handle properties $uniqueProps = array( 'name' => array('is_string', function ($val) { return $val; }), 'type' => array('is_string', function ($val) { return $val; }), 'description' => array('is_string', function ($val) { return $val; }), 'homepage' => array('is_string', function ($val) { return $val; }), 'version' => array('is_string', function ($val) { return $val; }), 'minimum-stability' => array( function ($val) { return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]); }, function ($val) { return VersionParser::normalizeStability($val); }, ), 'prefer-stable' => array($booleanValidator, $booleanNormalizer), ); $multiProps = array( 'keywords' => array( function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, function ($vals) { return $vals; }, ), 'license' => array( function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, function ($vals) { return $vals; }, ), ); if ($input->getOption('global') && (isset($uniqueProps[$settingKey]) || isset($multiProps[$settingKey]) || substr($settingKey, 0, 6) === 'extra.')) { throw new \InvalidArgumentException('The '.$settingKey.' property can not be set in the global config.json file. Use `composer global config` to apply changes to the global composer.json'); } if ($input->getOption('unset') && (isset($uniqueProps[$settingKey]) || isset($multiProps[$settingKey]))) { return $this->configSource->removeProperty($settingKey); } if (isset($uniqueProps[$settingKey])) { return $this->handleSingleValue($settingKey, $uniqueProps[$settingKey], $values, 'addProperty'); } if (isset($multiProps[$settingKey])) { return $this->handleMultiValue($settingKey, $multiProps[$settingKey], $values, 'addProperty'); } // handle repositories if (preg_match('/^repos?(?:itories)?\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { return $this->configSource->removeRepository($matches[1]); } if (2 === count($values)) { return $this->configSource->addRepository($matches[1], array( 'type' => $values[0], 'url' => $values[1], )); } if (1 === count($values)) { $value = strtolower($values[0]); if (true === $booleanValidator($value)) { if (false === $booleanNormalizer($value)) { return $this->configSource->addRepository($matches[1], false); } } else { $value = JsonFile::parseJson($values[0]); return $this->configSource->addRepository($matches[1], $value); } } throw new \RuntimeException('You must pass the type and a url. Example: php composer.phar config repositories.foo vcs https://bar.com'); } // handle extra if (preg_match('/^extra\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { return $this->configSource->removeProperty($settingKey); } return $this->configSource->addProperty($settingKey, $values[0]); } // handle platform if (preg_match('/^platform\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { return $this->configSource->removeConfigSetting($settingKey); } return $this->configSource->addConfigSetting($settingKey, $values[0]); } if ($settingKey === 'platform' && $input->getOption('unset')) { return $this->configSource->removeConfigSetting($settingKey); } // handle auth if (preg_match('/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic)\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->authConfigSource->removeConfigSetting($matches[1].'.'.$matches[2]); $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]); return; } if ($matches[1] === 'bitbucket-oauth') { if (2 !== count($values)) { throw new \RuntimeException('Expected two arguments (consumer-key, consumer-secret), got '.count($values)); } $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]); $this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], array('consumer-key' => $values[0], 'consumer-secret' => $values[1])); } elseif (in_array($matches[1], array('github-oauth', 'gitlab-oauth', 'gitlab-token'), true)) { if (1 !== count($values)) { throw new \RuntimeException('Too many arguments, expected only one token'); } $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]); $this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], $values[0]); } elseif ($matches[1] === 'http-basic') { if (2 !== count($values)) { throw new \RuntimeException('Expected two arguments (username, password), got '.count($values)); } $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]); $this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], array('username' => $values[0], 'password' => $values[1])); } return; } throw new \InvalidArgumentException('Setting '.$settingKey.' does not exist or is not supported by this command'); } protected function handleSingleValue($key, array $callbacks, array $values, $method) { list($validator, $normalizer) = $callbacks; if (1 !== count($values)) { throw new \RuntimeException('You can only pass one value. Example: php composer.phar config process-timeout 300'); } if (true !== $validation = $validator($values[0])) { throw new \RuntimeException(sprintf( '"%s" is an invalid value'.($validation ? ' ('.$validation.')' : ''), $values[0] )); } return call_user_func(array($this->configSource, $method), $key, $normalizer($values[0])); } protected function handleMultiValue($key, array $callbacks, array $values, $method) { list($validator, $normalizer) = $callbacks; if (true !== $validation = $validator($values)) { throw new \RuntimeException(sprintf( '%s is an invalid value'.($validation ? ' ('.$validation.')' : ''), json_encode($values) )); } return call_user_func(array($this->configSource, $method), $key, $normalizer($values)); } /** * Display the contents of the file in a pretty formatted way * * @param array $contents * @param array $rawContents * @param OutputInterface $output * @param string|null $k */ protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null) { $origK = $k; $io = $this->getIO(); foreach ($contents as $key => $value) { if ($k === null && !in_array($key, array('config', 'repositories'))) { continue; } $rawVal = isset($rawContents[$key]) ? $rawContents[$key] : null; if (is_array($value) && (!is_numeric(key($value)) || ($key === 'repositories' && null === $k))) { $k .= preg_replace('{^config\.}', '', $key . '.'); $this->listConfiguration($value, $rawVal, $output, $k); $k = $origK; continue; } if (is_array($value)) { $value = array_map(function ($val) { return is_array($val) ? json_encode($val) : $val; }, $value); $value = '['.implode(', ', $value).']'; } if (is_bool($value)) { $value = var_export($value, true); } if (is_string($rawVal) && $rawVal != $value) { $io->write('[' . $k . $key . '] ' . $rawVal . ' (' . $value . ')'); } else { $io->write('[' . $k . $key . '] ' . $value . ''); } } } } composer-1.6.3/src/Composer/Command/CreateProjectCommand.php000066400000000000000000000425461323436022200240560ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Config; use Composer\Factory; use Composer\Installer; use Composer\Installer\ProjectInstaller; use Composer\Installer\InstallationManager; use Composer\Installer\SuggestedPackagesReporter; use Composer\IO\IOInterface; use Composer\Package\BasePackage; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\Package\Version\VersionSelector; use Composer\Package\AliasPackage; use Composer\Repository\RepositoryFactory; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\InstalledFilesystemRepository; use Composer\Script\ScriptEvents; use Composer\Util\Silencer; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; use Composer\Json\JsonFile; use Composer\Config\JsonConfigSource; use Composer\Util\Filesystem; use Composer\Package\Version\VersionParser; /** * Install a package as new project into new directory. * * @author Benjamin Eberlei * @author Jordi Boggiano * @author Tobias Munk * @author Nils Adermann */ class CreateProjectCommand extends BaseCommand { /** * @var SuggestedPackagesReporter */ protected $suggestedPackagesReporter; protected function configure() { $this ->setName('create-project') ->setDescription('Creates new project from a package into given directory.') ->setDefinition(array( new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed'), new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'), new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'), new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'), new InputOption('repository', null, InputOption::VALUE_REQUIRED, 'Pick a different repository (as url or json config) to look for the package.'), new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'DEPRECATED: Use --repository instead.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-secure-http', null, InputOption::VALUE_NONE, 'Disable the secure-http config option temporarily while installing the root package. Use at your own risk. Using this flag is a bad idea.'), new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deleting the vcs folder.'), new InputOption('remove-vcs', null, InputOption::VALUE_NONE, 'Whether to force deletion of the vcs folder without prompting.'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'), )) ->setHelp(<<create-project command creates a new project from a given package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project. You can use this command to bootstrap new projects or setup a clean version-controlled installation for developers of your project. php composer.phar create-project vendor/project target-directory [version] You can also specify the version with the package name using = or : as separator. php composer.phar create-project vendor/project:version target-directory To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev). To setup a developer workable version you should create the project using the source controlled code by appending the '--prefer-source' flag. To install a package from another repository than the default one you can pass the '--repository=https://myrepository.org' flag. EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $io = $this->getIO(); list($preferSource, $preferDist) = $this->getPreferredInstallOptions($config, $input, true); if ($input->getOption('dev')) { $io->writeError('You are using the deprecated option "dev". Dev packages are installed by default now.'); } if ($input->getOption('no-custom-installers')) { $io->writeError('You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.'); $input->setOption('no-plugins', true); } return $this->installProject( $io, $config, $input, $input->getArgument('package'), $input->getArgument('directory'), $input->getArgument('version'), $input->getOption('stability'), $preferSource, $preferDist, !$input->getOption('no-dev'), $input->getOption('repository') ?: $input->getOption('repository-url'), $input->getOption('no-plugins'), $input->getOption('no-scripts'), $input->getOption('keep-vcs'), $input->getOption('no-progress'), $input->getOption('no-install'), $input->getOption('ignore-platform-reqs'), !$input->getOption('no-secure-http'), $input->getOption('remove-vcs') ); } public function installProject(IOInterface $io, Config $config, InputInterface $input, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repository = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $noInstall = false, $ignorePlatformReqs = false, $secureHttp = true, $removeVcs = false) { $oldCwd = getcwd(); // we need to manually load the configuration to pass the auth credentials to the io interface! $io->loadConfiguration($config); $this->suggestedPackagesReporter = new SuggestedPackagesReporter($io); if ($packageName !== null) { $installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repository, $disablePlugins, $noScripts, $keepVcs, $noProgress, $ignorePlatformReqs, $secureHttp); } else { $installedFromVcs = false; } $composer = Factory::create($io, null, $disablePlugins); $composer->getDownloadManager()->setOutputProgress(!$noProgress); $fs = new Filesystem(); if ($noScripts === false) { // dispatch event $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages); } // use the new config including the newly installed project $config = $composer->getConfig(); list($preferSource, $preferDist) = $this->getPreferredInstallOptions($config, $input); // install dependencies of the created project if ($noInstall === false) { $installer = Installer::create($io, $composer); $installer->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode($installDevPackages) ->setRunScripts(!$noScripts) ->setIgnorePlatformRequirements($ignorePlatformReqs) ->setSuggestedPackagesReporter($this->suggestedPackagesReporter) ->setOptimizeAutoloader($config->get('optimize-autoloader')); if ($disablePlugins) { $installer->disablePlugins(); } $status = $installer->run(); if (0 !== $status) { return $status; } } $hasVcs = $installedFromVcs; if ( !$keepVcs && $installedFromVcs && ( $removeVcs || !$io->isInteractive() || $io->askConfirmation('Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? ', true) ) ) { $finder = new Finder(); $finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false); foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg', '.fslckout', '_FOSSIL_') as $vcsName) { $finder->name($vcsName); } try { $dirs = iterator_to_array($finder); unset($finder); foreach ($dirs as $dir) { if (!$fs->removeDirectory($dir)) { throw new \RuntimeException('Could not remove '.$dir); } } } catch (\Exception $e) { $io->writeError('An error occurred while removing the VCS metadata: '.$e->getMessage().''); } $hasVcs = false; } // rewriting self.version dependencies with explicit version numbers if the package's vcs metadata is gone if (!$hasVcs) { $package = $composer->getPackage(); $configSource = new JsonConfigSource(new JsonFile('composer.json')); foreach (BasePackage::$supportedLinkTypes as $type => $meta) { foreach ($package->{'get'.$meta['method']}() as $link) { if ($link->getPrettyConstraint() === 'self.version') { $configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion()); } } } } if ($noScripts === false) { // dispatch event $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages); } chdir($oldCwd); $vendorComposerDir = $config->get('vendor-dir').'/composer'; if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) { Silencer::call('rmdir', $vendorComposerDir); $vendorDir = $config->get('vendor-dir'); if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) { Silencer::call('rmdir', $vendorDir); } } return 0; } protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repository = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $ignorePlatformReqs = false, $secureHttp = true) { if (!$secureHttp) { $config->merge(array('config' => array('secure-http' => false))); } if (null === $repository) { $sourceRepo = new CompositeRepository(RepositoryFactory::defaultRepos($io, $config)); } else { $sourceRepo = RepositoryFactory::fromString($io, $config, $repository, true); } $parser = new VersionParser(); $requirements = $parser->parseNameVersionPairs(array($packageName)); $name = strtolower($requirements[0]['name']); if (!$packageVersion && isset($requirements[0]['version'])) { $packageVersion = $requirements[0]['version']; } if (null === $stability) { if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) { $stability = $match[1]; } else { $stability = VersionParser::parseStability($packageVersion); } } $stability = VersionParser::normalizeStability($stability); if (!isset(BasePackage::$stabilities[$stability])) { throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities))); } $pool = new Pool($stability); $pool->addRepository($sourceRepo); $phpVersion = null; $prettyPhpVersion = null; if (!$ignorePlatformReqs) { $platformOverrides = $config->get('platform') ?: array(); // initialize $this->repos as it is used by the parent InitCommand $platform = new PlatformRepository(array(), $platformOverrides); $phpPackage = $platform->findPackage('php', '*'); $phpVersion = $phpPackage->getVersion(); $prettyPhpVersion = $phpPackage->getPrettyVersion(); } // find the latest version if there are multiple $versionSelector = new VersionSelector($pool); $package = $versionSelector->findBestCandidate($name, $packageVersion, $phpVersion, $stability); if (!$package) { $errorMessage = "Could not find package $name with " . ($packageVersion ? "version $packageVersion" : "stability $stability"); if ($phpVersion && $versionSelector->findBestCandidate($name, $packageVersion, null, $stability)) { throw new \InvalidArgumentException($errorMessage .' in a version installable using your PHP version '.$prettyPhpVersion.'.'); } throw new \InvalidArgumentException($errorMessage .'.'); } if (null === $directory) { $parts = explode("/", $name, 2); $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts); } // handler Ctrl+C for unix-like systems if (function_exists('pcntl_async_signals')) { @mkdir($directory, 0777, true); if ($realDir = realpath($directory)) { pcntl_async_signals(true); pcntl_signal(SIGINT, function () use ($realDir) { $fs = new Filesystem(); $fs->removeDirectory($realDir); exit(130); }); } } $io->writeError('Installing ' . $package->getName() . ' (' . $package->getFullPrettyVersion(false) . ')'); if ($disablePlugins) { $io->writeError('Plugins have been disabled.'); } if ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) { $package->setSourceReference(substr($package->getPrettyVersion(), 4)); } $dm = $this->createDownloadManager($io, $config); $dm->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setOutputProgress(!$noProgress); $projectInstaller = new ProjectInstaller($directory, $dm); $im = $this->createInstallationManager(); $im->addInstaller($projectInstaller); $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package)); $im->notifyInstalls($io); // collect suggestions $this->suggestedPackagesReporter->addSuggestionsFromPackage($package); $installedFromVcs = 'source' === $package->getInstallationSource(); $io->writeError('Created project in ' . $directory . ''); chdir($directory); $_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion(); putenv('COMPOSER_ROOT_VERSION='.$_SERVER['COMPOSER_ROOT_VERSION']); return $installedFromVcs; } protected function createDownloadManager(IOInterface $io, Config $config) { $factory = new Factory(); return $factory->createDownloadManager($io, $config); } protected function createInstallationManager() { return new InstallationManager(); } } composer-1.6.3/src/Composer/Command/DependsCommand.php000066400000000000000000000024501323436022200226740ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Niels Keurentjes */ class DependsCommand extends BaseDependencyCommand { /** * Configure command metadata. */ protected function configure() { parent::configure(); $this ->setName('depends') ->setAliases(array('why')) ->setDescription('Shows which packages cause the given package to be installed.') ->setHelp(<<php composer.phar depends composer/composer EOT ) ; } /** * Execute the function. * * @param InputInterface $input * @param OutputInterface $output * @return int|null */ protected function execute(InputInterface $input, OutputInterface $output) { return parent::doExecute($input, $output, false); } } composer-1.6.3/src/Composer/Command/DiagnoseCommand.php000066400000000000000000000630311323436022200230450ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Downloader\TransportException; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\ConfigValidator; use Composer\Util\IniHelper; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\Util\StreamContextFactory; use Composer\SelfUpdate\Keys; use Composer\SelfUpdate\Versions; use Composer\IO\NullIO; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class DiagnoseCommand extends BaseCommand { /** @var RemoteFileSystem */ protected $rfs; /** @var ProcessExecutor */ protected $process; /** @var int */ protected $exitCode = 0; protected function configure() { $this ->setName('diagnose') ->setDescription('Diagnoses the system to identify common errors.') ->setHelp(<<diagnose command checks common errors to help debugging problems. The process exit code will be 1 in case of warnings and 2 for errors. EOT ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(false); $io = $this->getIO(); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $io->write('Checking composer.json: ', false); $this->outputResult($this->checkComposerSchema()); } if ($composer) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } $config->merge(array('config' => array('secure-http' => false))); $config->prohibitUrlByConfig('http://packagist.org', new NullIO); $this->rfs = Factory::createRemoteFilesystem($io, $config); $this->process = new ProcessExecutor($io); $io->write('Checking platform settings: ', false); $this->outputResult($this->checkPlatform()); $io->write('Checking git settings: ', false); $this->outputResult($this->checkGit()); $io->write('Checking http connectivity to packagist: ', false); $this->outputResult($this->checkHttp('http', $config)); $io->write('Checking https connectivity to packagist: ', false); $this->outputResult($this->checkHttp('https', $config)); $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org')); if (!empty($opts['http']['proxy'])) { $io->write('Checking HTTP proxy: ', false); $this->outputResult($this->checkHttpProxy()); $io->write('Checking HTTP proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpProxyFullUriRequestParam()); $io->write('Checking HTTPS proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpsProxyFullUriRequestParam()); } if ($oauth = $config->get('github-oauth')) { foreach ($oauth as $domain => $token) { $io->write('Checking '.$domain.' oauth access: ', false); $this->outputResult($this->checkGithubOauth($domain, $token)); } } else { $io->write('Checking github.com rate limit: ', false); try { $rate = $this->getGithubRateLimit('github.com'); $this->outputResult(true); if (10 > $rate['remaining']) { $io->write('WARNING'); $io->write(sprintf( 'Github has a rate limit on their API. ' . 'You currently have %u ' . 'out of %u requests left.' . PHP_EOL . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens', $rate['remaining'], $rate['limit'] )); } } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { $this->outputResult('The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it'); } else { $this->outputResult($e); } } } $io->write('Checking disk free space: ', false); $this->outputResult($this->checkDiskSpace($config)); if ('phar:' === substr(__FILE__, 0, 5)) { $io->write('Checking pubkeys: ', false); $this->outputResult($this->checkPubKeys($config)); $io->write('Checking composer version: ', false); $this->outputResult($this->checkVersion($config)); } $io->write(sprintf('Composer version: %s', Composer::VERSION)); $io->write(sprintf('PHP version: %s', PHP_VERSION)); if (defined('PHP_BINARY')) { $io->write(sprintf('PHP binary path: %s', PHP_BINARY)); } return $this->exitCode; } private function checkComposerSchema() { $validator = new ConfigValidator($this->getIO()); list($errors, , $warnings) = $validator->validate(Factory::getComposerFile()); if ($errors || $warnings) { $messages = array( 'error' => $errors, 'warning' => $warnings, ); $output = ''; foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { $output .= '<' . $style . '>' . $msg . '' . PHP_EOL; } } return rtrim($output); } return true; } private function checkGit() { $this->process->execute('git config color.ui', $output); if (strtolower(trim($output)) === 'always') { return 'Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.'; } return true; } private function checkHttp($proto, Config $config) { $disableTls = false; $result = array(); if ($proto === 'https' && $config->get('disable-tls') === true) { $disableTls = true; $result[] = 'Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.'; } if ($proto === 'https' && !extension_loaded('openssl') && !$disableTls) { $result[] = 'Composer is configured to use SSL/TLS protection but the openssl extension is not available.'; } try { $this->rfs->getContents('packagist.org', $proto . '://packagist.org/packages.json', false); } catch (TransportException $e) { if (false !== strpos($e->getMessage(), 'cafile')) { $result[] = '[' . get_class($e) . '] ' . $e->getMessage() . ''; $result[] = 'Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.'; $result[] = 'You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.'; } else { array_unshift($result, '[' . get_class($e) . '] ' . $e->getMessage()); } } if (count($result) > 0) { return $result; } return true; } private function checkHttpProxy() { $protocol = extension_loaded('openssl') ? 'https' : 'http'; try { $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true); $hash = reset($json['provider-includes']); $hash = $hash['sha256']; $path = str_replace('%hash%', $hash, key($json['provider-includes'])); $provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false); if (hash('sha256', $provider) !== $hash) { return 'It seems that your proxy is modifying http traffic on the fly'; } } catch (\Exception $e) { return $e; } return true; } /** * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter, * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825. * This method will test, if you need to disable this parameter via setting extra environment variable in your system. * * @return bool|string */ private function checkHttpProxyFullUriRequestParam() { $url = 'http://packagist.org/packages.json'; try { $this->rfs->getContents('packagist.org', $url, false); } catch (TransportException $e) { try { $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false))); } catch (TransportException $e) { return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')'; } return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"'; } return true; } /** * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter, * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825. * This method will test, if you need to disable this parameter via setting extra environment variable in your system. * * @return bool|string */ private function checkHttpsProxyFullUriRequestParam() { if (!extension_loaded('openssl')) { return 'You need the openssl extension installed for this check'; } $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0'; try { $this->rfs->getContents('github.com', $url, false); } catch (TransportException $e) { try { $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false))); } catch (TransportException $e) { return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')'; } return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"'; } return true; } private function checkGithubOauth($domain, $token) { $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); try { $url = $domain === 'github.com' ? 'https://api.'.$domain.'/' : 'https://'.$domain.'/api/v3/'; return $this->rfs->getContents($domain, $url, false, array( 'retry-auth-failure' => false, )) ? true : 'Unexpected error'; } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { return 'The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it'; } return $e; } } /** * @param string $domain * @param string $token * @throws TransportException * @return array */ private function getGithubRateLimit($domain, $token = null) { if ($token) { $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); } $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit'; $json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false)); $data = json_decode($json, true); return $data['resources']['core']; } private function checkDiskSpace($config) { $minSpaceFree = 1024 * 1024; if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree) || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree) ) { return 'The disk hosting '.$dir.' is full'; } return true; } private function checkPubKeys($config) { $home = $config->get('home'); $errors = array(); $io = $this->getIO(); if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) { $io->write(''); } if (file_exists($home.'/keys.tags.pub')) { $io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub')); } else { $errors[] = 'Missing pubkey for tags verification'; } if (file_exists($home.'/keys.dev.pub')) { $io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub')); } else { $errors[] = 'Missing pubkey for dev verification'; } if ($errors) { $errors[] = 'Run composer self-update --update-keys to set them up'; } return $errors ?: true; } private function checkVersion($config) { $versionsUtil = new Versions($config, $this->rfs); $latest = $versionsUtil->getLatest(); if (Composer::VERSION !== $latest['version'] && Composer::VERSION !== '@package_version@') { return 'You are not running the latest '.$versionsUtil->getChannel().' version, run `composer self-update` to update ('.Composer::VERSION.' => '.$latest['version'].')'; } return true; } /** * @param bool|string|\Exception $result */ private function outputResult($result) { $io = $this->getIO(); if (true === $result) { $io->write('OK'); return; } $hadError = false; if ($result instanceof \Exception) { $result = '['.get_class($result).'] '.$result->getMessage().''; } if (!$result) { // falsey results should be considered as an error, even if there is nothing to output $hadError = true; } else { if (!is_array($result)) { $result = array($result); } foreach ($result as $message) { if (false !== strpos($message, '')) { $hadError = true; } } } if ($hadError) { $io->write('FAIL'); $this->exitCode = 2; } else { $io->write('WARNING'); $this->exitCode = 1; } if ($result) { foreach ($result as $message) { $io->write($message); } } } private function checkPlatform() { $output = ''; $out = function ($msg, $style) use (&$output) { $output .= '<'.$style.'>'.$msg.''.PHP_EOL; }; // code below taken from getcomposer.org/installer, any changes should be made there and replicated here $errors = array(); $warnings = array(); $displayIniMessage = false; $iniMessage = PHP_EOL.PHP_EOL.IniHelper::getMessage(); $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.'; if (!function_exists('json_decode')) { $errors['json'] = true; } if (!extension_loaded('Phar')) { $errors['phar'] = true; } if (!extension_loaded('filter')) { $errors['filter'] = true; } if (!extension_loaded('hash')) { $errors['hash'] = true; } if (!extension_loaded('iconv') && !extension_loaded('mbstring')) { $errors['iconv_mbstring'] = true; } if (!ini_get('allow_url_fopen')) { $errors['allow_url_fopen'] = true; } if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) { $errors['ioncube'] = ioncube_loader_version(); } if (PHP_VERSION_ID < 50302) { $errors['php'] = PHP_VERSION; } if (!isset($errors['php']) && PHP_VERSION_ID < 50304) { $warnings['php'] = PHP_VERSION; } if (!extension_loaded('openssl')) { $errors['openssl'] = true; } if (extension_loaded('openssl') && OPENSSL_VERSION_NUMBER < 0x1000100f) { $warnings['openssl_version'] = true; } if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) { $warnings['apc_cli'] = true; } if (!extension_loaded('zlib')) { $warnings['zlib'] = true; } ob_start(); phpinfo(INFO_GENERAL); $phpinfo = ob_get_clean(); if (preg_match('{Configure Command(?: *| *=> *)(.*?)(?:|$)}m', $phpinfo, $match)) { $configure = $match[1]; if (false !== strpos($configure, '--enable-sigchild')) { $warnings['sigchild'] = true; } if (false !== strpos($configure, '--with-curlwrappers')) { $warnings['curlwrappers'] = true; } } if (ini_get('xdebug.profiler_enabled')) { $warnings['xdebug_profile'] = true; } elseif (extension_loaded('xdebug')) { $warnings['xdebug_loaded'] = true; } if (!empty($errors)) { foreach ($errors as $error => $current) { switch ($error) { case 'json': $text = PHP_EOL."The json extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-json"; break; case 'phar': $text = PHP_EOL."The phar extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-phar"; break; case 'filter': $text = PHP_EOL."The filter extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-filter"; break; case 'hash': $text = PHP_EOL."The hash extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-hash"; break; case 'iconv_mbstring': $text = PHP_EOL."The iconv OR mbstring extension is required and both are missing.".PHP_EOL; $text .= "Install either of them or recompile php without --disable-iconv"; break; case 'unicode': $text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " detect_unicode = Off"; $displayIniMessage = true; break; case 'suhosin': $text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL; $text .= " suhosin.executor.include.whitelist = phar ".$current; $displayIniMessage = true; break; case 'php': $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher."; break; case 'allow_url_fopen': $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " allow_url_fopen = On"; $displayIniMessage = true; break; case 'ioncube': $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL; $text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL; $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so"; $displayIniMessage = true; break; case 'openssl': $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL; $text .= "If possible you should enable it or recompile php with --with-openssl"; break; } $out($text, 'error'); } $output .= PHP_EOL; } if (!empty($warnings)) { foreach ($warnings as $warning => $current) { switch ($warning) { case 'apc_cli': $text = "The apc.enable_cli setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " apc.enable_cli = Off"; $displayIniMessage = true; break; case 'zlib': $text = 'The zlib extension is not loaded, this can slow down Composer a lot.'.PHP_EOL; $text .= 'If possible, enable it or recompile php with --with-zlib'.PHP_EOL; $displayIniMessage = true; break; case 'sigchild': $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL; $text .= "Recompile it without this flag if possible, see also:".PHP_EOL; $text .= " https://bugs.php.net/bug.php?id=22999"; break; case 'curlwrappers': $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL; $text .= " Recompile it without this flag if possible"; break; case 'php': $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL; $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues."; break; case 'openssl_version': // Attempt to parse version number out, fallback to whole string value. $opensslVersion = strstr(trim(strstr(OPENSSL_VERSION_TEXT, ' ')), ' ', true); $opensslVersion = $opensslVersion ?: OPENSSL_VERSION_TEXT; $text = "The OpenSSL library ({$opensslVersion}) used by PHP does not support TLSv1.2 or TLSv1.1.".PHP_EOL; $text .= "If possible you should upgrade OpenSSL to version 1.0.1 or above."; break; case 'xdebug_loaded': $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL; $text .= " Disabling it when using Composer is recommended."; break; case 'xdebug_profile': $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL; $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL; $text .= " xdebug.profiler_enabled = 0"; $displayIniMessage = true; break; } $out($text, 'comment'); } } if ($displayIniMessage) { $out($iniMessage, 'comment'); } return !$warnings && !$errors ? true : $output; } } composer-1.6.3/src/Composer/Command/DumpAutoloadCommand.php000066400000000000000000000063221323436022200237120ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class DumpAutoloadCommand extends BaseCommand { protected function configure() { $this ->setName('dump-autoload') ->setAliases(array('dumpautoload')) ->setDescription('Dumps the autoloader.') ->setDefinition(array( new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'), new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize`.'), new InputOption('apcu', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables autoload-dev rules.'), )) ->setHelp(<<php composer.phar dump-autoload EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'dump-autoload', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $installationManager = $composer->getInstallationManager(); $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $package = $composer->getPackage(); $config = $composer->getConfig(); $optimize = $input->getOption('optimize') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcu = $input->getOption('apcu') || $config->get('apcu-autoloader'); if ($authoritative) { $this->getIO()->writeError('Generating optimized autoload files (authoritative)'); } elseif ($optimize) { $this->getIO()->writeError('Generating optimized autoload files'); } else { $this->getIO()->writeError('Generating autoload files'); } $generator = $composer->getAutoloadGenerator(); $generator->setDevMode(!$input->getOption('no-dev')); $generator->setClassMapAuthoritative($authoritative); $generator->setApcu($apcu); $generator->setRunScripts(!$input->getOption('no-scripts')); $generator->dump($config, $localRepo, $package, $installationManager, 'composer', $optimize); } } composer-1.6.3/src/Composer/Command/ExecCommand.php000066400000000000000000000053651323436022200222060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; /** * @author Davey Shafik */ class ExecCommand extends BaseCommand { protected function configure() { $this ->setName('exec') ->setDescription('Executes a vendored binary/script.') ->setDefinition(array( new InputOption('list', 'l', InputOption::VALUE_NONE), new InputArgument('binary', InputArgument::OPTIONAL, 'The binary to run, e.g. phpunit'), new InputArgument( 'args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Arguments to pass to the binary. Use -- to separate from composer arguments' ), )) ; } protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(); $binDir = $composer->getConfig()->get('bin-dir'); if ($input->getOption('list') || !$input->getArgument('binary')) { $bins = glob($binDir . '/*'); $bins = array_merge($bins, array_map(function ($e) { return "$e (local)"; }, $composer->getPackage()->getBinaries())); if (!$bins) { throw new \RuntimeException("No binaries found in composer.json or in bin-dir ($binDir)"); } $this->getIO()->write(<<Available binaries: EOT ); foreach ($bins as $bin) { // skip .bat copies if (isset($previousBin) && $bin === $previousBin.'.bat') { continue; } $previousBin = $bin; $bin = basename($bin); $this->getIO()->write(<<- $bin EOT ); } return 0; } $binary = $input->getArgument('binary'); $dispatcher = $composer->getEventDispatcher(); $dispatcher->addListener('__exec_command', $binary); if ($output->getVerbosity() === OutputInterface::VERBOSITY_NORMAL) { $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); } return $dispatcher->dispatchScript('__exec_command', true, $input->getArgument('args')); } } composer-1.6.3/src/Composer/Command/GlobalCommand.php000066400000000000000000000055611323436022200225200ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class GlobalCommand extends BaseCommand { protected function configure() { $this ->setName('global') ->setDescription('Allows running commands in the global composer dir ($COMPOSER_HOME).') ->setDefinition(array( new InputArgument('command-name', InputArgument::REQUIRED, ''), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), )) ->setHelp(<<\AppData\Roaming\Composer on Windows and /home//.composer on unix systems. If your system uses freedesktop.org standards, then it will first check XDG_CONFIG_HOME or default to /home//.config/composer Note: This path may vary depending on customizations to bin-dir in composer.json or the environmental variable COMPOSER_BIN_DIR. EOT ) ; } public function run(InputInterface $input, OutputInterface $output) { // extract real command name $tokens = preg_split('{\s+}', $input->__toString()); $args = array(); foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } // show help for this command if no command was found if (count($args) < 2) { return parent::run($input, $output); } // change to global dir $config = Factory::createConfig(); chdir($config->get('home')); $this->getIO()->writeError('Changed current directory to '.$config->get('home').''); // create new input without "global" command prefix $input = new StringInput(preg_replace('{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}', '', $input->__toString(), 1)); $this->getApplication()->resetComposer(); return $this->getApplication()->run($input, $output); } /** * {@inheritDoc} */ public function isProxyCommand() { return true; } } composer-1.6.3/src/Composer/Command/HomeCommand.php000066400000000000000000000124441323436022200222060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Package\CompletePackageInterface; use Composer\Repository\RepositoryInterface; use Composer\Repository\ArrayRepository; use Composer\Repository\RepositoryFactory; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Robert Schönthal */ class HomeCommand extends BaseCommand { /** * {@inheritDoc} */ protected function configure() { $this ->setName('browse') ->setAliases(array('home')) ->setDescription('Opens the package\'s repository URL or homepage in your browser.') ->setDefinition(array( new InputArgument('packages', InputArgument::IS_ARRAY, 'Package(s) to browse to.'), new InputOption('homepage', 'H', InputOption::VALUE_NONE, 'Open the homepage instead of the repository URL.'), new InputOption('show', 's', InputOption::VALUE_NONE, 'Only show the homepage or repository URL.'), )) ->setHelp(<<initializeRepos(); $io = $this->getIO(); $return = 0; $packages = $input->getArgument('packages'); if (!$packages) { $io->writeError('No package specified, opening homepage for the root package'); $packages = array($this->getComposer()->getPackage()->getName()); } foreach ($packages as $packageName) { $handled = false; $packageExists = false; foreach ($repos as $repo) { foreach ($repo->findPackages($packageName) as $package) { $packageExists = true; if ($package instanceof CompletePackageInterface && $this->handlePackage($package, $input->getOption('homepage'), $input->getOption('show'))) { $handled = true; break 2; } } } if (!$packageExists) { $return = 1; $io->writeError('Package '.$packageName.' not found'); } if (!$handled) { $return = 1; $io->writeError(''.($input->getOption('homepage') ? 'Invalid or missing homepage' : 'Invalid or missing repository URL').' for '.$packageName.''); } } return $return; } private function handlePackage(CompletePackageInterface $package, $showHomepage, $showOnly) { $support = $package->getSupport(); $url = isset($support['source']) ? $support['source'] : $package->getSourceUrl(); if (!$url || $showHomepage) { $url = $package->getHomepage(); } if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) { return false; } if ($showOnly) { $this->getIO()->write(sprintf('%s', $url)); } else { $this->openBrowser($url); } return true; } /** * opens a url in your system default browser * * @param string $url */ private function openBrowser($url) { $url = ProcessExecutor::escape($url); $process = new ProcessExecutor($this->getIO()); if (Platform::isWindows()) { return $process->execute('start "web" explorer "' . $url . '"', $output); } $linux = $process->execute('which xdg-open', $output); $osx = $process->execute('which open', $output); if (0 === $linux) { $process->execute('xdg-open ' . $url, $output); } elseif (0 === $osx) { $process->execute('open ' . $url, $output); } else { $this->getIO()->writeError('No suitable browser opening command found, open yourself: ' . $url); } } /** * Initializes repositories * * Returns an array of repos in order they should be checked in * * @return RepositoryInterface[] */ private function initializeRepos() { $composer = $this->getComposer(false); if ($composer) { return array_merge( array(new ArrayRepository(array($composer->getPackage()))), // root package array($composer->getRepositoryManager()->getLocalRepository()), // installed packages $composer->getRepositoryManager()->getRepositories() // remotes ); } return RepositoryFactory::defaultRepos($this->getIO()); } } composer-1.6.3/src/Composer/Command/InitCommand.php000066400000000000000000000701341323436022200222210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\DependencyResolver\Pool; use Composer\Factory; use Composer\Json\JsonFile; use Composer\Package\BasePackage; use Composer\Package\Version\VersionParser; use Composer\Package\Version\VersionSelector; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Util\ProcessExecutor; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; /** * @author Justin Rainbow * @author Jordi Boggiano */ class InitCommand extends BaseCommand { /** @var CompositeRepository */ protected $repos; /** @var array */ private $gitConfig; /** @var Pool[] */ private $pools; /** * {@inheritdoc} */ protected function configure() { $this ->setName('init') ->setDescription('Creates a basic composer.json file in current directory.') ->setDefinition(array( new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'), new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'), new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'), // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'), new InputOption('type', null, InputOption::VALUE_OPTIONAL, 'Type of package (e.g. library, project, metapackage, composer-plugin)'), new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'), new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'), new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'), new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'), new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'), new InputOption('repository', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add custom repositories, either by URL or using JSON arrays'), )) ->setHelp(<<init command creates a basic composer.json file in the current directory. php composer.phar init EOT ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = $this->getIO(); $whitelist = array('name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license'); $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist))); if (isset($options['author'])) { $options['authors'] = $this->formatAuthors($options['author']); unset($options['author']); } $repositories = $input->getOption('repository'); if ($repositories) { $config = Factory::createConfig($io); foreach ($repositories as $repo) { $options['repositories'][] = RepositoryFactory::configFromString($io, $config, $repo); } } if (isset($options['stability'])) { $options['minimum-stability'] = $options['stability']; unset($options['stability']); } $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass; if (array() === $options['require']) { $options['require'] = new \stdClass; } if (isset($options['require-dev'])) { $options['require-dev'] = $this->formatRequirements($options['require-dev']); if (array() === $options['require-dev']) { $options['require-dev'] = new \stdClass; } } $file = new JsonFile(Factory::getComposerFile()); $json = $file->encode($options); if ($input->isInteractive()) { $io->writeError(array('', $json, '')); if (!$io->askConfirmation('Do you confirm generation [yes]? ', true)) { $io->writeError('Command aborted'); return 1; } } $file->write($options); if ($input->isInteractive() && is_dir('.git')) { $ignoreFile = realpath('.gitignore'); if (false === $ignoreFile) { $ignoreFile = realpath('.') . '/.gitignore'; } if (!$this->hasVendorIgnore($ignoreFile)) { $question = 'Would you like the vendor directory added to your .gitignore [yes]? '; if ($io->askConfirmation($question, true)) { $this->addVendorIgnore($ignoreFile); } } } } /** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $git = $this->getGitConfig(); $io = $this->getIO(); $formatter = $this->getHelperSet()->get('formatter'); // initialize repos if configured $repositories = $input->getOption('repository'); if ($repositories) { $config = Factory::createConfig($io); $repos = array(new PlatformRepository); foreach ($repositories as $repo) { $repos[] = RepositoryFactory::fromString($io, $config, $repo); } $repos[] = RepositoryFactory::createRepo($io, $config, array( 'type' => 'composer', 'url' => 'https://packagist.org', )); $this->repos = new CompositeRepository($repos); unset($repos, $config, $repositories); } $io->writeError(array( '', $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true), '', )); // namespace $io->writeError(array( '', 'This command will guide you through creating your composer.json config.', '', )); $cwd = realpath("."); if (!$name = $input->getOption('name')) { $name = basename($cwd); $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name); $name = strtolower($name); if (!empty($_SERVER['COMPOSER_DEFAULT_VENDOR'])) { $name = $_SERVER['COMPOSER_DEFAULT_VENDOR'] . '/' . $name; } elseif (isset($git['github.user'])) { $name = $git['github.user'] . '/' . $name; } elseif (!empty($_SERVER['USERNAME'])) { $name = $_SERVER['USERNAME'] . '/' . $name; } elseif (!empty($_SERVER['USER'])) { $name = $_SERVER['USER'] . '/' . $name; } elseif (get_current_user()) { $name = get_current_user() . '/' . $name; } else { // package names must be in the format foo/bar $name = $name . '/' . $name; } $name = strtolower($name); } else { if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) { throw new \InvalidArgumentException( 'The package name '.$name.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+' ); } } $name = $io->askAndValidate( 'Package name (/) ['.$name.']: ', function ($value) use ($name) { if (null === $value) { return $name; } if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) { throw new \InvalidArgumentException( 'The package name '.$value.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+' ); } return $value; }, null, $name ); $input->setOption('name', $name); $description = $input->getOption('description') ?: false; $description = $io->ask( 'Description ['.$description.']: ', $description ); $input->setOption('description', $description); if (null === $author = $input->getOption('author')) { if (!empty($_SERVER['COMPOSER_DEFAULT_AUTHOR'])) { $author_name = $_SERVER['COMPOSER_DEFAULT_AUTHOR']; } elseif (isset($git['user.name'])) { $author_name = $git['user.name']; } if (!empty($_SERVER['COMPOSER_DEFAULT_EMAIL'])) { $author_email = $_SERVER['COMPOSER_DEFAULT_EMAIL']; } elseif (isset($git['user.email'])) { $author_email = $git['user.email']; } if (isset($author_name) && isset($author_email)) { $author = sprintf('%s <%s>', $author_name, $author_email); } } $self = $this; $author = $io->askAndValidate( 'Author ['.$author.', n to skip]: ', function ($value) use ($self, $author) { if ($value === 'n' || $value === 'no') { return; } $value = $value ?: $author; $author = $self->parseAuthorString($value); return sprintf('%s <%s>', $author['name'], $author['email']); }, null, $author ); $input->setOption('author', $author); $minimumStability = $input->getOption('stability') ?: null; $minimumStability = $io->askAndValidate( 'Minimum Stability ['.$minimumStability.']: ', function ($value) use ($self, $minimumStability) { if (null === $value) { return $minimumStability; } if (!isset(BasePackage::$stabilities[$value])) { throw new \InvalidArgumentException( 'Invalid minimum stability "'.$value.'". Must be empty or one of: '. implode(', ', array_keys(BasePackage::$stabilities)) ); } return $value; }, null, $minimumStability ); $input->setOption('stability', $minimumStability); $type = $input->getOption('type') ?: false; $type = $io->ask( 'Package Type (e.g. library, project, metapackage, composer-plugin) ['.$type.']: ', $type ); $input->setOption('type', $type); if (null === $license = $input->getOption('license')) { if (!empty($_SERVER['COMPOSER_DEFAULT_LICENSE'])) { $license = $_SERVER['COMPOSER_DEFAULT_LICENSE']; } } $license = $io->ask( 'License ['.$license.']: ', $license ); $input->setOption('license', $license); $io->writeError(array('', 'Define your dependencies.', '')); $question = 'Would you like to define your dependencies (require) interactively [yes]? '; $require = $input->getOption('require'); $requirements = array(); if ($require || $io->askConfirmation($question, true)) { $requirements = $this->determineRequirements($input, $output, $require); } $input->setOption('require', $requirements); $question = 'Would you like to define your dev dependencies (require-dev) interactively [yes]? '; $requireDev = $input->getOption('require-dev'); $devRequirements = array(); if ($requireDev || $io->askConfirmation($question, true)) { $devRequirements = $this->determineRequirements($input, $output, $requireDev); } $input->setOption('require-dev', $devRequirements); } /** * @private * @param string $author * @return array */ public function parseAuthorString($author) { if (preg_match('/^(?P[- .,\p{L}\p{N}\p{Mn}\'’"()]+) <(?P.+?)>$/u', $author, $match)) { if ($this->isValidEmail($match['email'])) { return array( 'name' => trim($match['name']), 'email' => $match['email'], ); } } throw new \InvalidArgumentException( 'Invalid author string. Must be in the format: '. 'John Smith ' ); } protected function findPackages($name) { return $this->getRepos()->search($name); } protected function getRepos() { if (!$this->repos) { $this->repos = new CompositeRepository(array_merge( array(new PlatformRepository), RepositoryFactory::defaultRepos($this->getIO()) )); } return $this->repos; } protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array(), $phpVersion = null, $preferredStability = 'stable') { if ($requires) { $requires = $this->normalizeRequirements($requires); $result = array(); $io = $this->getIO(); foreach ($requires as $requirement) { if (!isset($requirement['version'])) { // determine the best version automatically list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $phpVersion, $preferredStability); $requirement['version'] = $version; // replace package name from packagist.org $requirement['name'] = $name; $io->writeError(sprintf( 'Using version %s for %s', $requirement['version'], $requirement['name'] )); } else { // check that the specified version/constraint exists before we proceed list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $phpVersion, $preferredStability, $requirement['version'], 'dev'); // replace package name from packagist.org $requirement['name'] = $name; } $result[] = $requirement['name'] . ' ' . $requirement['version']; } return $result; } $versionParser = new VersionParser(); $io = $this->getIO(); while (null !== $package = $io->ask('Search for a package: ')) { $matches = $this->findPackages($package); if (count($matches)) { $exactMatch = null; $choices = array(); foreach ($matches as $position => $foundPackage) { $abandoned = ''; if (isset($foundPackage['abandoned'])) { if (is_string($foundPackage['abandoned'])) { $replacement = sprintf('Use %s instead', $foundPackage['abandoned']); } else { $replacement = 'No replacement was suggested'; } $abandoned = sprintf('Abandoned. %s.', $replacement); } $choices[] = sprintf(' %5s %s %s', "[$position]", $foundPackage['name'], $abandoned); if ($foundPackage['name'] === $package) { $exactMatch = true; break; } } // no match, prompt which to pick if (!$exactMatch) { $io->writeError(array( '', sprintf('Found %s packages matching %s', count($matches), $package), '', )); $io->writeError($choices); $io->writeError(''); $validator = function ($selection) use ($matches, $versionParser) { if ('' === $selection) { return false; } if (is_numeric($selection) && isset($matches[(int) $selection])) { $package = $matches[(int) $selection]; return $package['name']; } if (preg_match('{^\s*(?P[\S/]+)(?:\s+(?P\S+))?\s*$}', $selection, $packageMatches)) { if (isset($packageMatches['version'])) { // parsing `acme/example ~2.3` // validate version constraint $versionParser->parseConstraints($packageMatches['version']); return $packageMatches['name'].' '.$packageMatches['version']; } // parsing `acme/example` return $packageMatches['name']; } throw new \Exception('Not a valid selection'); }; $package = $io->askAndValidate( 'Enter package # to add, or the complete package name if it is not listed: ', $validator, 3, false ); } // no constraint yet, determine the best version automatically if (false !== $package && false === strpos($package, ' ')) { $validator = function ($input) { $input = trim($input); return $input ?: false; }; $constraint = $io->askAndValidate( 'Enter the version constraint to require (or leave blank to use the latest version): ', $validator, 3, false ); if (false === $constraint) { list($name, $constraint) = $this->findBestVersionAndNameForPackage($input, $package, $phpVersion, $preferredStability); $io->writeError(sprintf( 'Using version %s for %s', $constraint, $package )); } $package .= ' '.$constraint; } if (false !== $package) { $requires[] = $package; } } } return $requires; } protected function formatAuthors($author) { return array($this->parseAuthorString($author)); } protected function formatRequirements(array $requirements) { $requires = array(); $requirements = $this->normalizeRequirements($requirements); foreach ($requirements as $requirement) { $requires[$requirement['name']] = $requirement['version']; } return $requires; } protected function getGitConfig() { if (null !== $this->gitConfig) { return $this->gitConfig; } $finder = new ExecutableFinder(); $gitBin = $finder->find('git'); $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin))); $cmd->run(); if ($cmd->isSuccessful()) { $this->gitConfig = array(); preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER); foreach ($matches as $match) { $this->gitConfig[$match[1]] = $match[2]; } return $this->gitConfig; } return $this->gitConfig = array(); } /** * Checks the local .gitignore file for the Composer vendor directory. * * Tested patterns include: * "/$vendor" * "$vendor" * "$vendor/" * "/$vendor/" * "/$vendor/*" * "$vendor/*" * * @param string $ignoreFile * @param string $vendor * * @return bool */ protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor') { if (!file_exists($ignoreFile)) { return false; } $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor)); $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES); foreach ($lines as $line) { if (preg_match($pattern, $line)) { return true; } } return false; } protected function normalizeRequirements(array $requirements) { $parser = new VersionParser(); return $parser->parseNameVersionPairs($requirements); } protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/') { $contents = ""; if (file_exists($ignoreFile)) { $contents = file_get_contents($ignoreFile); if ("\n" !== substr($contents, 0, -1)) { $contents .= "\n"; } } file_put_contents($ignoreFile, $contents . $vendor. "\n"); } protected function isValidEmail($email) { // assume it's valid if we can't validate it if (!function_exists('filter_var')) { return true; } // php <5.3.3 has a very broken email validator, so bypass checks if (PHP_VERSION_ID < 50303) { return true; } return false !== filter_var($email, FILTER_VALIDATE_EMAIL); } private function getPool(InputInterface $input, $minimumStability = null) { $key = $minimumStability ?: 'default'; if (!isset($this->pools[$key])) { $this->pools[$key] = $pool = new Pool($minimumStability ?: $this->getMinimumStability($input)); $pool->addRepository($this->getRepos()); } return $this->pools[$key]; } private function getMinimumStability(InputInterface $input) { if ($input->hasOption('stability')) { return $input->getOption('stability') ?: 'stable'; } $file = Factory::getComposerFile(); if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) { if (!empty($composer['minimum-stability'])) { return $composer['minimum-stability']; } } return 'stable'; } /** * Given a package name, this determines the best version to use in the require key. * * This returns a version with the ~ operator prefixed when possible. * * @param InputInterface $input * @param string $name * @param string|null $phpVersion * @param string $preferredStability * @param string|null $requiredVersion * @param string $minimumStability * @throws \InvalidArgumentException * @return array name version */ private function findBestVersionAndNameForPackage(InputInterface $input, $name, $phpVersion, $preferredStability = 'stable', $requiredVersion = null, $minimumStability = null) { // find the latest version allowed in this pool $versionSelector = new VersionSelector($this->getPool($input, $minimumStability)); $package = $versionSelector->findBestCandidate($name, $requiredVersion, $phpVersion, $preferredStability); // retry without phpVersion if platform requirements are ignored in case nothing was found if ($input->hasOption('ignore-platform-reqs') && $input->getOption('ignore-platform-reqs')) { $phpVersion = null; $package = $versionSelector->findBestCandidate($name, $requiredVersion, $phpVersion, $preferredStability); } if (!$package) { // Check whether the PHP version was the problem if ($phpVersion && $versionSelector->findBestCandidate($name, $requiredVersion, null, $preferredStability)) { throw new \InvalidArgumentException(sprintf( 'Package %s at version %s has a PHP requirement incompatible with your PHP version (%s)', $name, $requiredVersion, $phpVersion )); } // Check whether the required version was the problem if ($requiredVersion && $versionSelector->findBestCandidate($name, null, $phpVersion, $preferredStability)) { throw new \InvalidArgumentException(sprintf( 'Could not find package %s in a version matching %s', $name, $requiredVersion )); } // Check whether the PHP version was the problem if ($phpVersion && $versionSelector->findBestCandidate($name)) { throw new \InvalidArgumentException(sprintf( 'Could not find package %s in any version matching your PHP version (%s)', $name, $phpVersion )); } // Check for similar names/typos $similar = $this->findSimilar($name); if ($similar) { // Check whether the minimum stability was the problem but the package exists if ($requiredVersion === null && in_array($name, $similar, true)) { throw new \InvalidArgumentException(sprintf( 'Could not find a version of package %s matching your minimum-stability (%s). Require it with an explicit version constraint allowing its desired stability.', $name, $this->getMinimumStability($input) )); } throw new \InvalidArgumentException(sprintf( "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s", $name, implode("\n ", $similar) )); } throw new \InvalidArgumentException(sprintf( 'Could not find a matching version of package %s. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (%s).', $name, $this->getMinimumStability($input) )); } return array( $package->getPrettyName(), $versionSelector->findRecommendedRequireVersion($package) ); } private function findSimilar($package) { try { $results = $this->repos->search($package); } catch (\Exception $e) { // ignore search errors return array(); } $similarPackages = array(); foreach ($results as $result) { $similarPackages[$result['name']] = levenshtein($package, $result['name']); } asort($similarPackages); return array_keys(array_slice($similarPackages, 0, 5)); } } composer-1.6.3/src/Composer/Command/InstallCommand.php000066400000000000000000000142621323436022200227240ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Installer; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano * @author Ryan Weaver * @author Konstantin Kudryashov * @author Nils Adermann */ class InstallCommand extends BaseCommand { protected function configure() { $this ->setName('install') ->setDescription('Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.') ->setDefinition(array( new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'), new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'Do not show package suggestions.'), new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'), new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Should not be provided, use composer require instead to add a given package to composer.json.'), )) ->setHelp(<<install command reads the composer.lock file from the current directory, processes it, and downloads and installs all the libraries and dependencies outlined in that file. If the file does not exist it will look for composer.json and do the same. php composer.phar install EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $io = $this->getIO(); if ($args = $input->getArgument('packages')) { $io->writeError('Invalid argument '.implode(' ', $args).'. Use "composer require '.implode(' ', $args).'" instead to add packages to your composer.json.'); return 1; } if ($input->getOption('no-custom-installers')) { $io->writeError('You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.'); $input->setOption('no-plugins', true); } if ($input->getOption('dev')) { $io->writeError('You are using the deprecated option "dev". Dev packages are installed by default now.'); } $composer = $this->getComposer(true, $input->getOption('no-plugins')); $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress')); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'install', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $install = Installer::create($io, $composer); $config = $composer->getConfig(); list($preferSource, $preferDist) = $this->getPreferredInstallOptions($config, $input); $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcu = $input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $install ->setDryRun($input->getOption('dry-run')) ->setVerbose($input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$input->getOption('no-dev')) ->setDumpAutoloader(!$input->getOption('no-autoloader')) ->setRunScripts(!$input->getOption('no-scripts')) ->setSkipSuggest($input->getOption('no-suggest')) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')) ; if ($input->getOption('no-plugins')) { $install->disablePlugins(); } return $install->run(); } } composer-1.6.3/src/Composer/Command/LicensesCommand.php000066400000000000000000000125031323436022200230570ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Json\JsonFile; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Package\PackageInterface; use Composer\Repository\RepositoryInterface; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Benoît Merlet */ class LicensesCommand extends BaseCommand { protected function configure() { $this ->setName('licenses') ->setDescription('Shows information about licenses of dependencies.') ->setDefinition(array( new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables search in require-dev packages.'), )) ->setHelp(<<getComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'licenses', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $root = $composer->getPackage(); $repo = $composer->getRepositoryManager()->getLocalRepository(); if ($input->getOption('no-dev')) { $packages = $this->filterRequiredPackages($repo, $root); } else { $packages = $this->appendPackages($repo->getPackages(), array()); } ksort($packages); $io = $this->getIO(); switch ($format = $input->getOption('format')) { case 'text': $io->write('Name: '.$root->getPrettyName().''); $io->write('Version: '.$root->getFullPrettyVersion().''); $io->write('Licenses: '.(implode(', ', $root->getLicense()) ?: 'none').''); $io->write('Dependencies:'); $io->write(''); $table = new Table($output); $table->setStyle('compact'); $table->getStyle()->setVerticalBorderChar(''); $table->getStyle()->setCellRowContentFormat('%s '); $table->setHeaders(array('Name', 'Version', 'License')); foreach ($packages as $package) { $table->addRow(array( $package->getPrettyName(), $package->getFullPrettyVersion(), implode(', ', $package->getLicense()) ?: 'none', )); } $table->render(); break; case 'json': $dependencies = array(); foreach ($packages as $package) { $dependencies[$package->getPrettyName()] = array( 'version' => $package->getFullPrettyVersion(), 'license' => $package->getLicense(), ); } $io->write(JsonFile::encode(array( 'name' => $root->getPrettyName(), 'version' => $root->getFullPrettyVersion(), 'license' => $root->getLicense(), 'dependencies' => $dependencies, ))); break; default: throw new \RuntimeException(sprintf('Unsupported format "%s". See help for supported formats.', $format)); } } /** * Find package requires and child requires * * @param RepositoryInterface $repo * @param PackageInterface $package * @param array $bucket * @return array */ private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()) { $requires = array_keys($package->getRequires()); $packageListNames = array_keys($bucket); $packages = array_filter( $repo->getPackages(), function ($package) use ($requires, $packageListNames) { return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames); } ); $bucket = $this->appendPackages($packages, $bucket); foreach ($packages as $package) { $bucket = $this->filterRequiredPackages($repo, $package, $bucket); } return $bucket; } /** * Adds packages to the package list * * @param array $packages the list of packages to add * @param array $bucket the list to add packages to * @return array */ public function appendPackages(array $packages, array $bucket) { foreach ($packages as $package) { $bucket[$package->getName()] = $package; } return $bucket; } } composer-1.6.3/src/Composer/Command/OutdatedCommand.php000066400000000000000000000067021323436022200230670ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class OutdatedCommand extends ShowCommand { protected function configure() { $this ->setName('outdated') ->setDescription('Shows a list of installed packages that have updates available, including their latest version.') ->setDefinition(array( new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect. Or a name including a wildcard (*) to filter lists of packages instead.'), new InputOption('outdated', 'o', InputOption::VALUE_NONE, 'Show only packages that are outdated (this is the default, but present here for compat with `show`'), new InputOption('all', 'a', InputOption::VALUE_NONE, 'Show all installed packages with their latest versions'), new InputOption('direct', 'D', InputOption::VALUE_NONE, 'Shows only packages that are directly required by the root package'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code when there are outdated packages'), new InputOption('minor-only', 'm', InputOption::VALUE_NONE, 'Show only packages that have minor SemVer-compatible updates. Use with the --outdated option.'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'), )) ->setHelp(<<green (=): Dependency is in the latest version and is up to date. - yellow (~): Dependency has a new version available that includes backwards compatibility breaks according to semver, so upgrade when you can but it may involve work. - red (!): Dependency has a new version that is semver-compatible and you should upgrade it. EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $args = array( 'show', '--latest' => true, ); if (!$input->getOption('all')) { $args['--outdated'] = true; } if ($input->getOption('direct')) { $args['--direct'] = true; } if ($input->getArgument('package')) { $args['package'] = $input->getArgument('package'); } if ($input->getOption('strict')) { $args['--strict'] = true; } if ($input->getOption('minor-only')) { $args['--minor-only'] = true; } $args['--format'] = $input->getOption('format'); $input = new ArrayInput($args); return $this->getApplication()->run($input, $output); } /** * {@inheritDoc} */ public function isProxyCommand() { return true; } } composer-1.6.3/src/Composer/Command/ProhibitsCommand.php000066400000000000000000000024741323436022200232630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Niels Keurentjes */ class ProhibitsCommand extends BaseDependencyCommand { /** * Configure command metadata. */ protected function configure() { parent::configure(); $this ->setName('prohibits') ->setAliases(array('why-not')) ->setDescription('Shows which packages prevent the given package from being installed.') ->setHelp(<<php composer.phar prohibits composer/composer EOT ) ; } /** * Execute the function. * * @param InputInterface $input * @param OutputInterface $output * @return int|null */ protected function execute(InputInterface $input, OutputInterface $output) { return parent::doExecute($input, $output, true); } } composer-1.6.3/src/Composer/Command/RemoveCommand.php000066400000000000000000000155021323436022200225510ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Config\JsonConfigSource; use Composer\Installer; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Json\JsonFile; use Composer\Factory; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Pierre du Plessis * @author Jordi Boggiano */ class RemoveCommand extends BaseCommand { protected function configure() { $this ->setName('remove') ->setDescription('Removes a package from the require or require-dev.') ->setDefinition(array( new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Packages that should be removed.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Removes a package from the require-dev section.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'), new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'), new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies. (Deprecrated, is now default behavior)'), new InputOption('no-update-with-dependencies', null, InputOption::VALUE_NONE, 'Does not allow inherited dependencies to be updated with explicit dependencies.'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), )) ->setHelp(<<remove command removes a package from the current list of installed packages php composer.phar remove EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $packages = $input->getArgument('packages'); $packages = array_map('strtolower', $packages); $file = Factory::getComposerFile(); $jsonFile = new JsonFile($file); $composer = $jsonFile->read(); $composerBackup = file_get_contents($jsonFile->getPath()); $json = new JsonConfigSource($jsonFile); $type = $input->getOption('dev') ? 'require-dev' : 'require'; $altType = !$input->getOption('dev') ? 'require-dev' : 'require'; $io = $this->getIO(); if ($input->getOption('update-with-dependencies')) { $io->writeError('You are using the deprecated option "update-with-dependencies". This is now default behaviour. The --no-update-with-dependencies option can be used to remove a package without its dependencies.'); } // make sure name checks are done case insensitively foreach (array('require', 'require-dev') as $linkType) { if (isset($composer[$linkType])) { foreach ($composer[$linkType] as $name => $version) { $composer[$linkType][strtolower($name)] = $name; } } } foreach ($packages as $package) { if (isset($composer[$type][$package])) { $json->removeLink($type, $composer[$type][$package]); } elseif (isset($composer[$altType][$package])) { $io->writeError(''.$composer[$altType][$package].' could not be found in '.$type.' but it is present in '.$altType.''); if ($io->isInteractive()) { if ($io->askConfirmation('Do you want to remove it from '.$altType.' [yes]? ', true)) { $json->removeLink($altType, $composer[$altType][$package]); } } } else { $io->writeError(''.$package.' is not required in your composer.json and has not been removed'); } } if ($input->getOption('no-update')) { return 0; } // Update packages $this->resetComposer(); $composer = $this->getComposer(true, $input->getOption('no-plugins')); $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress')); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $install = Installer::create($io, $composer); $updateDevMode = !$input->getOption('update-no-dev'); $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative'); $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader'); $install ->setVerbose($input->getOption('verbose')) ->setDevMode($updateDevMode) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setUpdate(true) ->setUpdateWhitelist($packages) ->setWhitelistTransitiveDependencies(!$input->getOption('no-update-with-dependencies')) ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')) ->setRunScripts(!$input->getOption('no-scripts')) ; $status = $install->run(); if ($status !== 0) { $io->writeError("\n".'Removal failed, reverting '.$file.' to its original content.'); file_put_contents($jsonFile->getPath(), $composerBackup); } return $status; } } composer-1.6.3/src/Composer/Command/RequireCommand.php000066400000000000000000000242261323436022200227330ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Factory; use Composer\Installer; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Package\Version\VersionParser; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; /** * @author Jérémy Romey * @author Jordi Boggiano */ class RequireCommand extends InitCommand { protected function configure() { $this ->setName('require') ->setDescription('Adds required packages to your composer.json and installs them.') ->setDefinition(array( new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name can also include a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'Do not show package suggestions.'), new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'), new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'), new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'), new InputOption('update-with-all-dependencies', null, InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'), new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'), new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'), new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), )) ->setHelp(<<getIO(); $newlyCreated = !file_exists($file); if ($newlyCreated && !file_put_contents($file, "{\n}\n")) { $io->writeError(''.$file.' could not be created.'); return 1; } if (!is_readable($file)) { $io->writeError(''.$file.' is not readable.'); return 1; } if (!is_writable($file)) { $io->writeError(''.$file.' is not writable.'); return 1; } if (filesize($file) === 0) { file_put_contents($file, "{\n}\n"); } $json = new JsonFile($file); $composerBackup = file_get_contents($json->getPath()); $composer = $this->getComposer(true, $input->getOption('no-plugins')); $repos = $composer->getRepositoryManager()->getRepositories(); $platformOverrides = $composer->getConfig()->get('platform') ?: array(); // initialize $this->repos as it is used by the parent InitCommand $this->repos = new CompositeRepository(array_merge( array(new PlatformRepository(array(), $platformOverrides)), $repos )); if ($composer->getPackage()->getPreferStable()) { $preferredStability = 'stable'; } else { $preferredStability = $composer->getPackage()->getMinimumStability(); } $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion(); $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability); $requireKey = $input->getOption('dev') ? 'require-dev' : 'require'; $removeKey = $input->getOption('dev') ? 'require' : 'require-dev'; $requirements = $this->formatRequirements($requirements); // validate requirements format $versionParser = new VersionParser(); foreach ($requirements as $constraint) { $versionParser->parseConstraints($constraint); } $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages'); if (!$this->updateFileCleanly($json, $requirements, $requireKey, $removeKey, $sortPackages)) { $composerDefinition = $json->read(); foreach ($requirements as $package => $version) { $composerDefinition[$requireKey][$package] = $version; unset($composerDefinition[$removeKey][$package]); } $json->write($composerDefinition); } $io->writeError(''.$file.' has been '.($newlyCreated ? 'created' : 'updated').''); if ($input->getOption('no-update')) { return 0; } $updateDevMode = !$input->getOption('update-no-dev'); $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative'); $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader'); // Update packages $this->resetComposer(); $composer = $this->getComposer(true, $input->getOption('no-plugins')); $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress')); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $install = Installer::create($io, $composer); $install ->setVerbose($input->getOption('verbose')) ->setPreferSource($input->getOption('prefer-source')) ->setPreferDist($input->getOption('prefer-dist')) ->setDevMode($updateDevMode) ->setRunScripts(!$input->getOption('no-scripts')) ->setSkipSuggest($input->getOption('no-suggest')) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setUpdate(true) ->setUpdateWhitelist(array_keys($requirements)) ->setWhitelistTransitiveDependencies($input->getOption('update-with-dependencies')) ->setWhitelistAllDependencies($input->getOption('update-with-all-dependencies')) ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')) ->setPreferStable($input->getOption('prefer-stable')) ->setPreferLowest($input->getOption('prefer-lowest')) ; $status = $install->run(); if ($status !== 0) { if ($newlyCreated) { $io->writeError("\n".'Installation failed, deleting '.$file.'.'); unlink($json->getPath()); } else { $io->writeError("\n".'Installation failed, reverting '.$file.' to its original content.'); file_put_contents($json->getPath(), $composerBackup); } } return $status; } private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages) { $contents = file_get_contents($json->getPath()); $manipulator = new JsonManipulator($contents); foreach ($new as $package => $constraint) { if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) { return false; } if (!$manipulator->removeSubNode($removeKey, $package)) { return false; } } file_put_contents($json->getPath(), $manipulator->getContents()); return true; } protected function interact(InputInterface $input, OutputInterface $output) { return; } } composer-1.6.3/src/Composer/Command/RunScriptCommand.php000066400000000000000000000115051323436022200232440ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Script\Event as ScriptEvent; use Composer\Script\ScriptEvents; use Composer\Util\ProcessExecutor; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Helper\Table; /** * @author Fabien Potencier */ class RunScriptCommand extends BaseCommand { /** * @var array Array with command events */ protected $scriptEvents = array( ScriptEvents::PRE_INSTALL_CMD, ScriptEvents::POST_INSTALL_CMD, ScriptEvents::PRE_UPDATE_CMD, ScriptEvents::POST_UPDATE_CMD, ScriptEvents::PRE_STATUS_CMD, ScriptEvents::POST_STATUS_CMD, ScriptEvents::POST_ROOT_PACKAGE_INSTALL, ScriptEvents::POST_CREATE_PROJECT_CMD, ScriptEvents::PRE_ARCHIVE_CMD, ScriptEvents::POST_ARCHIVE_CMD, ScriptEvents::PRE_AUTOLOAD_DUMP, ScriptEvents::POST_AUTOLOAD_DUMP, ); protected function configure() { $this ->setName('run-script') ->setDescription('Runs the scripts defined in composer.json.') ->setDefinition(array( new InputArgument('script', InputArgument::OPTIONAL, 'Script name to run.'), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), new InputOption('timeout', null, InputOption::VALUE_REQUIRED, 'Sets script timeout in seconds, or 0 for never.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'), new InputOption('list', 'l', InputOption::VALUE_NONE, 'List scripts.'), )) ->setHelp(<<run-script command runs scripts defined in composer.json: php composer.phar run-script post-update-cmd EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('list')) { return $this->listScripts($output); } elseif (!$input->getArgument('script')) { throw new \RuntimeException('Missing required argument "script"'); } $script = $input->getArgument('script'); if (!in_array($script, $this->scriptEvents)) { if (defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) { throw new \InvalidArgumentException(sprintf('Script "%s" cannot be run with this command', $script)); } } $composer = $this->getComposer(); $devMode = $input->getOption('dev') || !$input->getOption('no-dev'); $event = new ScriptEvent($script, $composer, $this->getIO(), $devMode); $hasListeners = $composer->getEventDispatcher()->hasEventListeners($event); if (!$hasListeners) { throw new \InvalidArgumentException(sprintf('Script "%s" is not defined in this package', $script)); } $args = $input->getArgument('args'); if (null !== $timeout = $input->getOption('timeout')) { if (!ctype_digit($timeout)) { throw new \RuntimeException('Timeout value must be numeric and positive if defined, or 0 for forever'); } // Override global timeout set before in Composer by environment or config ProcessExecutor::setTimeout((int) $timeout); } return $composer->getEventDispatcher()->dispatchScript($script, $devMode, $args); } protected function listScripts(OutputInterface $output) { $scripts = $this->getComposer()->getPackage()->getScripts(); if (!count($scripts)) { return 0; } $io = $this->getIO(); $io->writeError('scripts:'); $table = array(); foreach ($scripts as $name => $script) { $cmd = $this->getApplication()->find($name); $description = ''; if ($cmd instanceof ScriptAliasCommand) { $description = $cmd->getDescription(); } $table[] = array(' '.$name, $description); } $renderer = new Table($output); $renderer->setStyle('compact'); $renderer->getStyle()->setVerticalBorderChar(''); $renderer->getStyle()->setCellRowContentFormat('%s '); $renderer->setRows($table)->render(); return 0; } } composer-1.6.3/src/Composer/Command/ScriptAliasCommand.php000066400000000000000000000036031323436022200235310ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano */ class ScriptAliasCommand extends BaseCommand { private $script; private $description; public function __construct($script, $description) { $this->script = $script; $this->description = empty($description) ? 'Runs the '.$script.' script as defined in composer.json.' : $description; parent::__construct(); } protected function configure() { $this ->setName($this->script) ->setDescription($this->description) ->setDefinition(array( new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), )) ->setHelp(<<run-script command runs scripts defined in composer.json: php composer.phar run-script post-update-cmd EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(); $args = $input->getArguments(); return $composer->getEventDispatcher()->dispatchScript($this->script, $input->getOption('dev') || !$input->getOption('no-dev'), $args['args']); } } composer-1.6.3/src/Composer/Command/SearchCommand.php000066400000000000000000000055631323436022200225270ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryInterface; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; /** * @author Robert Schönthal */ class SearchCommand extends BaseCommand { protected $matches; protected $lowMatches = array(); protected $tokens; protected $output; protected $onlyName; protected function configure() { $this ->setName('search') ->setDescription('Searches for packages.') ->setDefinition(array( new InputOption('only-name', 'N', InputOption::VALUE_NONE, 'Search only in name'), new InputOption('type', 't', InputOption::VALUE_REQUIRED, 'Search for a specific package type'), new InputArgument('tokens', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'tokens to search for'), )) ->setHelp(<<php composer.phar search symfony composer EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { // init repos $platformRepo = new PlatformRepository; $io = $this->getIO(); if (!($composer = $this->getComposer(false))) { $composer = Factory::create($this->getIO(), array()); } $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $installedRepo = new CompositeRepository(array($localRepo, $platformRepo)); $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories())); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'search', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $onlyName = $input->getOption('only-name'); $type = $input->getOption('type') ?: null; $flags = $onlyName ? RepositoryInterface::SEARCH_NAME : RepositoryInterface::SEARCH_FULLTEXT; $results = $repos->search(implode(' ', $input->getArgument('tokens')), $flags, $type); foreach ($results as $result) { $io->write($result['name'] . (isset($result['description']) ? ' '. $result['description'] : '')); } } } composer-1.6.3/src/Composer/Command/SelfUpdateCommand.php000066400000000000000000000407511323436022200233540ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Util\Filesystem; use Composer\SelfUpdate\Keys; use Composer\SelfUpdate\Versions; use Composer\IO\IOInterface; use Composer\Downloader\FilesystemException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; /** * @author Igor Wiedler * @author Kevin Ran * @author Jordi Boggiano */ class SelfUpdateCommand extends BaseCommand { const HOMEPAGE = 'getcomposer.org'; const OLD_INSTALL_EXT = '-old.phar'; protected function configure() { $this ->setName('self-update') ->setAliases(array('selfupdate')) ->setDescription('Updates composer.phar to the latest version.') ->setDefinition(array( new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'), new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'), new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('update-keys', null, InputOption::VALUE_NONE, 'Prompt user for a key update'), new InputOption('stable', null, InputOption::VALUE_NONE, 'Force an update to the stable channel'), new InputOption('preview', null, InputOption::VALUE_NONE, 'Force an update to the preview channel'), new InputOption('snapshot', null, InputOption::VALUE_NONE, 'Force an update to the snapshot channel'), new InputOption('set-channel-only', null, InputOption::VALUE_NONE, 'Only store the channel as the default one and then exit'), )) ->setHelp(<<self-update command checks getcomposer.org for newer versions of composer and if found, installs the latest. php composer.phar self-update EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); if ($config->get('disable-tls') === true) { $baseUrl = 'http://' . self::HOMEPAGE; } else { $baseUrl = 'https://' . self::HOMEPAGE; } $io = $this->getIO(); $remoteFilesystem = Factory::createRemoteFilesystem($io, $config); $versionsUtil = new Versions($config, $remoteFilesystem); // switch channel if requested foreach (array('stable', 'preview', 'snapshot') as $channel) { if ($input->getOption($channel)) { $versionsUtil->setChannel($channel); } } if ($input->getOption('set-channel-only')) { return 0; } $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('data-dir'); $home = $config->get('home'); $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; if ($input->getOption('update-keys')) { return $this->fetchKeys($io, $config); } // check if current dir is writable and if not try the cache dir from settings $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; // check for permissions in local filesystem before start connection process if (!is_writable($tmpDir)) { throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written'); } // check if composer is running as the same user that owns the directory root, only if POSIX is defined and callable if (function_exists('posix_getpwuid') && function_exists('posix_geteuid')) { $composeUser = posix_getpwuid(posix_geteuid()); $homeOwner = posix_getpwuid(fileowner($home)); if (isset($composeUser['name']) && isset($homeOwner['name']) && $composeUser['name'] !== $homeOwner['name']) { $io->writeError('You are running composer as "'.$composeUser['name'].'", while "'.$home.'" is owned by "'.$homeOwner['name'].'"'); } } if ($input->getOption('rollback')) { return $this->rollback($output, $rollbackDir, $localFilename); } $latest = $versionsUtil->getLatest(); $latestVersion = $latest['version']; $updateVersion = $input->getArgument('version') ?: $latestVersion; if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) { $io->writeError('You can not update to a specific SHA-1 as those phars are not available for download'); return 1; } if (Composer::VERSION === $updateVersion) { $io->writeError(sprintf('You are already using composer version %s (%s channel).', $updateVersion, $versionsUtil->getChannel())); // remove all backups except for the most recent, if any if ($input->getOption('clean-backups')) { $this->cleanBackups($rollbackDir, $this->getLastBackupVersion($rollbackDir)); } return 0; } $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar'; $backupFile = sprintf( '%s/%s-%s%s', $rollbackDir, strtr(Composer::RELEASE_DATE, ' :', '_-'), preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION), self::OLD_INSTALL_EXT ); $updatingToTag = !preg_match('{^[0-9a-f]{40}$}', $updateVersion); $io->write(sprintf("Updating to version %s (%s channel).", $updateVersion, $versionsUtil->getChannel())); $remoteFilename = $baseUrl . ($updatingToTag ? "/download/{$updateVersion}/composer.phar" : '/composer.phar'); $signature = $remoteFilesystem->getContents(self::HOMEPAGE, $remoteFilename.'.sig', false); $io->writeError(' ', false); $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename, !$input->getOption('no-progress')); $io->writeError(''); if (!file_exists($tempFilename) || !$signature) { $io->writeError('The download of the new composer version failed for an unexpected reason'); return 1; } // verify phar signature if (!extension_loaded('openssl') && $config->get('disable-tls')) { $io->writeError('Skipping phar signature verification as you have disabled OpenSSL via config.disable-tls'); } else { if (!extension_loaded('openssl')) { throw new \RuntimeException('The openssl extension is required for phar signatures to be verified but it is not available. ' . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.'); } $sigFile = 'file://'.$home.'/' . ($updatingToTag ? 'keys.tags.pub' : 'keys.dev.pub'); if (!file_exists($sigFile)) { file_put_contents($home.'/keys.dev.pub', <<getOption('clean-backups')) { $this->cleanBackups($rollbackDir); } if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) { @unlink($tempFilename); $io->writeError('The file is corrupted ('.$err->getMessage().').'); $io->writeError('Please re-run the self-update command to try again.'); return 1; } if (file_exists($backupFile)) { $io->writeError(sprintf( 'Use composer self-update --rollback to return to version %s', Composer::VERSION )); } else { $io->writeError('A backup of the current version could not be written to '.$backupFile.', no rollback possible'); } } protected function fetchKeys(IOInterface $io, Config $config) { if (!$io->isInteractive()) { throw new \RuntimeException('Public keys can not be fetched in non-interactive mode, please run Composer interactively'); } $io->write('Open https://composer.github.io/pubkeys.html to find the latest keys'); $validator = function ($value) { if (!preg_match('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { throw new \UnexpectedValueException('Invalid input'); } return trim($value)."\n"; }; $devKey = ''; while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $devKey, $match)) { $devKey = $io->askAndValidate('Enter Dev / Snapshot Public Key (including lines with -----): ', $validator); while ($line = $io->ask('')) { $devKey .= trim($line)."\n"; if (trim($line) === '-----END PUBLIC KEY-----') { break; } } } file_put_contents($keyPath = $config->get('home').'/keys.dev.pub', $match[0]); $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $tagsKey = ''; while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $tagsKey, $match)) { $tagsKey = $io->askAndValidate('Enter Tags Public Key (including lines with -----): ', $validator); while ($line = $io->ask('')) { $tagsKey .= trim($line)."\n"; if (trim($line) === '-----END PUBLIC KEY-----') { break; } } } file_put_contents($keyPath = $config->get('home').'/keys.tags.pub', $match[0]); $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $io->write('Public keys stored in '.$config->get('home')); } protected function rollback(OutputInterface $output, $rollbackDir, $localFilename) { $rollbackVersion = $this->getLastBackupVersion($rollbackDir); if (!$rollbackVersion) { throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"'); } $oldFile = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT; if (!is_file($oldFile)) { throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be found'); } if (!is_readable($oldFile)) { throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be read'); } $io = $this->getIO(); $io->writeError(sprintf("Rolling back to version %s.", $rollbackVersion)); if ($err = $this->setLocalPhar($localFilename, $oldFile)) { $io->writeError('The backup file was corrupted ('.$err->getMessage().').'); return 1; } return 0; } /** * @param string $localFilename * @param string $newFilename * @param string $backupTarget * @throws \Exception * @return \UnexpectedValueException|\PharException|null */ protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null) { try { @chmod($newFilename, fileperms($localFilename)); if (!ini_get('phar.readonly')) { // test the phar validity $phar = new \Phar($newFilename); // free the variable to unlock the file unset($phar); } // copy current file into installations dir if ($backupTarget && file_exists($localFilename)) { @copy($localFilename, $backupTarget); } rename($newFilename, $localFilename); return null; } catch (\Exception $e) { if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { throw $e; } return $e; } } protected function cleanBackups($rollbackDir, $except = null) { $finder = $this->getOldInstallationFinder($rollbackDir); $io = $this->getIO(); $fs = new Filesystem; foreach ($finder as $file) { if ($except && $file->getBasename(self::OLD_INSTALL_EXT) === $except) { continue; } $file = (string) $file; $io->writeError('Removing: '.$file.''); $fs->remove($file); } } protected function getLastBackupVersion($rollbackDir) { $finder = $this->getOldInstallationFinder($rollbackDir); $finder->sortByName(); $files = iterator_to_array($finder); if (count($files)) { return basename(end($files), self::OLD_INSTALL_EXT); } return false; } protected function getOldInstallationFinder($rollbackDir) { $finder = Finder::create() ->depth(0) ->files() ->name('*' . self::OLD_INSTALL_EXT) ->in($rollbackDir); return $finder; } } composer-1.6.3/src/Composer/Command/ShowCommand.php000066400000000000000000001135061323436022200222370ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\DependencyResolver\DefaultPolicy; use Composer\DependencyResolver\Pool; use Composer\Json\JsonFile; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; use Composer\Package\Version\VersionSelector; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\ArrayRepository; use Composer\Repository\ComposerRepository; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Repository\RepositoryInterface; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Semver; use Composer\Spdx\SpdxLicenses; use Composer\Util\Platform; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Terminal; /** * @author Robert Schönthal * @author Jordi Boggiano * @author Jérémy Romey * @author Mihai Plasoianu */ class ShowCommand extends BaseCommand { /** @var VersionParser */ protected $versionParser; protected $colors; /** @var Pool */ private $pool; protected function configure() { $this ->setName('show') ->setAliases(array('info')) ->setDescription('Shows information about packages.') ->setDefinition(array( new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect. Or a name including a wildcard (*) to filter lists of packages instead.'), new InputArgument('version', InputArgument::OPTIONAL, 'Version or version constraint to inspect'), new InputOption('all', null, InputOption::VALUE_NONE, 'List all packages'), new InputOption('installed', 'i', InputOption::VALUE_NONE, 'List installed packages only (enabled by default, only present for BC).'), new InputOption('platform', 'p', InputOption::VALUE_NONE, 'List platform packages only'), new InputOption('available', 'a', InputOption::VALUE_NONE, 'List available packages only'), new InputOption('self', 's', InputOption::VALUE_NONE, 'Show the root package information'), new InputOption('name-only', 'N', InputOption::VALUE_NONE, 'List package names only'), new InputOption('path', 'P', InputOption::VALUE_NONE, 'Show package paths'), new InputOption('tree', 't', InputOption::VALUE_NONE, 'List the dependencies as a tree'), new InputOption('latest', 'l', InputOption::VALUE_NONE, 'Show the latest version'), new InputOption('outdated', 'o', InputOption::VALUE_NONE, 'Show the latest version but only for packages that are outdated'), new InputOption('minor-only', 'm', InputOption::VALUE_NONE, 'Show only packages that have minor SemVer-compatible updates. Use with the --outdated option.'), new InputOption('direct', 'D', InputOption::VALUE_NONE, 'Shows only packages that are directly required by the root package'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code when there are outdated packages'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'), )) ->setHelp(<<versionParser = new VersionParser; if ($input->getOption('tree')) { $this->initStyles($output); } $composer = $this->getComposer(false); $io = $this->getIO(); if ($input->getOption('installed')) { $io->writeError('You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages.'); } if ($input->getOption('outdated')) { $input->setOption('latest', true); } if ($input->getOption('direct') && ($input->getOption('all') || $input->getOption('available') || $input->getOption('platform'))) { $io->writeError('The --direct (-D) option is not usable in combination with --all, --platform (-p) or --available (-a)'); return 1; } if ($input->getOption('tree') && ($input->getOption('all') || $input->getOption('available'))) { $io->writeError('The --tree (-t) option is not usable in combination with --all or --available (-a)'); return 1; } $format = $input->getOption('format'); if (!in_array($format, array('text', 'json'))) { $io->writeError(sprintf('Unsupported format "%s". See help for supported formats.', $format)); return 1; } // init repos $platformOverrides = array(); if ($composer) { $platformOverrides = $composer->getConfig()->get('platform') ?: array(); } $platformRepo = new PlatformRepository(array(), $platformOverrides); $phpVersion = $platformRepo->findPackage('php', '*')->getVersion(); if ($input->getOption('self')) { $package = $this->getComposer()->getPackage(); $repos = $installedRepo = new ArrayRepository(array($package)); } elseif ($input->getOption('platform')) { $repos = $installedRepo = $platformRepo; } elseif ($input->getOption('available')) { $installedRepo = $platformRepo; if ($composer) { $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories()); } else { $defaultRepos = RepositoryFactory::defaultRepos($io); $repos = new CompositeRepository($defaultRepos); $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos))); } } elseif ($input->getOption('all') && $composer) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $installedRepo = new CompositeRepository(array($localRepo, $platformRepo)); $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories())); } elseif ($input->getOption('all')) { $defaultRepos = RepositoryFactory::defaultRepos($io); $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos))); $installedRepo = $platformRepo; $repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos)); } else { $repos = $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository(); $rootPkg = $this->getComposer()->getPackage(); if (!$installedRepo->getPackages() && ($rootPkg->getRequires() || $rootPkg->getDevRequires())) { $io->writeError('No dependencies installed. Try running composer install or update.'); } } if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'show', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); } if ($input->getOption('latest') && null === $composer) { $io->writeError('No composer.json found in the current directory, disabling "latest" option'); $input->setOption('latest', false); } $packageFilter = $input->getArgument('package'); // show single package or single version if (($packageFilter && false === strpos($packageFilter, '*')) || !empty($package)) { if ('json' === $format) { $io->writeError('Format "json" is only supported for package listings, falling back to format "text"'); } if (empty($package)) { list($package, $versions) = $this->getPackage($installedRepo, $repos, $input->getArgument('package'), $input->getArgument('version')); if (empty($package)) { $options = $input->getOptions(); if (!isset($options['working-dir']) || !file_exists('composer.json')) { throw new \InvalidArgumentException('Package ' . $packageFilter . ' not found'); } $io->writeError('Package ' . $packageFilter . ' not found in ' . $options['working-dir'] . '/composer.json'); return 1; } } else { $versions = array($package->getPrettyVersion() => $package->getVersion()); } $exitCode = 0; if ($input->getOption('tree')) { $this->displayPackageTree($package, $installedRepo, $repos); } else { $latestPackage = null; if ($input->getOption('latest')) { $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion); } if ($input->getOption('outdated') && $input->getOption('strict') && $latestPackage && $latestPackage->getFullPrettyVersion() !== $package->getFullPrettyVersion() && !$latestPackage->isAbandoned()) { $exitCode = 1; } $this->printMeta($package, $versions, $installedRepo, $latestPackage ?: null); $this->printLinks($package, 'requires'); $this->printLinks($package, 'devRequires', 'requires (dev)'); if ($package->getSuggests()) { $io->write("\nsuggests"); foreach ($package->getSuggests() as $suggested => $reason) { $io->write($suggested . ' ' . $reason . ''); } } $this->printLinks($package, 'provides'); $this->printLinks($package, 'conflicts'); $this->printLinks($package, 'replaces'); } return $exitCode; } // show tree view if requested if ($input->getOption('tree')) { if ('json' === $format) { $io->writeError('Format "json" is only supported for package listings, falling back to format "text"'); } $rootRequires = $this->getRootRequires(); $packages = $installedRepo->getPackages(); usort($packages, 'strcmp'); foreach ($packages as $package) { if (in_array($package->getName(), $rootRequires, true)) { $this->displayPackageTree($package, $installedRepo, $repos); } } return 0; } if ($repos instanceof CompositeRepository) { $repos = $repos->getRepositories(); } elseif (!is_array($repos)) { $repos = array($repos); } // list packages $packages = array(); if (null !== $packageFilter) { $packageFilter = '{^'.str_replace('\\*', '.*?', preg_quote($packageFilter)).'$}i'; } $packageListFilter = array(); if ($input->getOption('direct')) { $packageListFilter = $this->getRootRequires(); } if (class_exists('Symfony\Component\Console\Terminal')) { $terminal = new Terminal(); $width = $terminal->getWidth(); } else { // For versions of Symfony console before 3.2 list($width) = $this->getApplication()->getTerminalDimensions(); } if (null === $width) { // In case the width is not detected, we're probably running the command // outside of a real terminal, use space without a limit $width = PHP_INT_MAX; } if (Platform::isWindows()) { $width--; } else { $width = max(80, $width); } if ($input->getOption('path') && null === $composer) { $io->writeError('No composer.json found in the current directory, disabling "path" option'); $input->setOption('path', false); } foreach ($repos as $repo) { if ($repo === $platformRepo) { $type = 'platform'; } elseif ( $repo === $installedRepo || ($installedRepo instanceof CompositeRepository && in_array($repo, $installedRepo->getRepositories(), true)) ) { $type = 'installed'; } else { $type = 'available'; } if ($repo instanceof ComposerRepository && $repo->hasProviders()) { foreach ($repo->getProviderNames() as $name) { if (!$packageFilter || preg_match($packageFilter, $name)) { $packages[$type][$name] = $name; } } } else { foreach ($repo->getPackages() as $package) { if (!isset($packages[$type][$package->getName()]) || !is_object($packages[$type][$package->getName()]) || version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<') ) { if (!$packageFilter || preg_match($packageFilter, $package->getName())) { if (!$packageListFilter || in_array($package->getName(), $packageListFilter, true)) { $packages[$type][$package->getName()] = $package; } } } } } } $showAllTypes = $input->getOption('all'); $showLatest = $input->getOption('latest'); $showMinorOnly = $input->getOption('minor-only'); $indent = $showAllTypes ? ' ' : ''; $latestPackages = array(); $exitCode = 0; $viewData = array(); $viewMetaData = array(); foreach (array('platform' => true, 'available' => false, 'installed' => true) as $type => $showVersion) { if (isset($packages[$type])) { ksort($packages[$type]); $nameLength = $versionLength = $latestLength = 0; foreach ($packages[$type] as $package) { if (is_object($package)) { $nameLength = max($nameLength, strlen($package->getPrettyName())); if ($showVersion) { $versionLength = max($versionLength, strlen($package->getFullPrettyVersion())); if ($showLatest) { $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion, $showMinorOnly); if ($latestPackage === false) { continue; } $latestPackages[$package->getPrettyName()] = $latestPackage; $latestLength = max($latestLength, strlen($latestPackage->getFullPrettyVersion())); } } } else { $nameLength = max($nameLength, strlen($package)); } } $writePath = !$input->getOption('name-only') && $input->getOption('path'); $writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion; $writeLatest = $writeVersion && $showLatest; $writeDescription = !$input->getOption('name-only') && !$input->getOption('path'); $hasOutdatedPackages = false; $viewData[$type] = array(); $viewMetaData[$type] = array( 'nameLength' => $nameLength, 'versionLength' => $versionLength, 'latestLength' => $latestLength, ); foreach ($packages[$type] as $package) { $packageViewData = array(); if (is_object($package)) { $latestPackage = null; if ($showLatest && isset($latestPackages[$package->getPrettyName()])) { $latestPackage = $latestPackages[$package->getPrettyName()]; } if ($input->getOption('outdated') && $latestPackage && $latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion() && !$latestPackage->isAbandoned()) { continue; } elseif ($input->getOption('outdated') || $input->getOption('strict')) { $hasOutdatedPackages = true; } $packageViewData['name'] = $package->getPrettyName(); if ($writeVersion) { $packageViewData['version'] = $package->getFullPrettyVersion(); } if ($writeLatest && $latestPackage) { $packageViewData['latest'] = $latestPackage->getFullPrettyVersion(); $packageViewData['latest-status'] = $this->getUpdateStatus($latestPackage, $package); } if ($writeDescription) { $packageViewData['description'] = $package->getDescription(); } if ($writePath) { $packageViewData['path'] = strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n"); } if ($latestPackage && $latestPackage->isAbandoned()) { $replacement = (is_string($latestPackage->getReplacementPackage())) ? 'Use ' . $latestPackage->getReplacementPackage() . ' instead' : 'No replacement was suggested'; $packageWarning = sprintf( 'Package %s is abandoned, you should avoid using it. %s.', $package->getPrettyName(), $replacement ); $packageViewData['warning'] = $packageWarning; } } else { $packageViewData['name'] = $package; } $viewData[$type][] = $packageViewData; } if ($input->getOption('strict') && $hasOutdatedPackages) { $exitCode = 1; break; } } } if ('json' === $format) { $io->write(JsonFile::encode($viewData)); } else { foreach ($viewData as $type => $packages) { $nameLength = $viewMetaData[$type]['nameLength']; $versionLength = $viewMetaData[$type]['versionLength']; $latestLength = $viewMetaData[$type]['latestLength']; $writeVersion = $nameLength + $versionLength + 3 <= $width; $writeLatest = $nameLength + $versionLength + $latestLength + 3 <= $width; $writeDescription = $nameLength + $versionLength + $latestLength + 24 <= $width; if ($writeLatest && !$io->isDecorated()) { $latestLength += 2; } if ($showAllTypes) { if ('available' === $type) { $io->write('' . $type . ':'); } else { $io->write('' . $type . ':'); } } foreach ($packages as $package) { $io->write($indent . str_pad($package['name'], $nameLength, ' '), false); if (isset($package['version']) && $writeVersion) { $io->write(' ' . str_pad($package['version'], $versionLength, ' '), false); } if (isset($package['latest']) && $writeLatest) { $latestVersion = $package['latest']; $updateStatus = $package['latest-status']; $style = $this->updateStatusToVersionStyle($updateStatus); if (!$io->isDecorated()) { $latestVersion = str_replace(array('up-to-date', 'semver-safe-update', 'update-possible'), array('=', '!', '~'), $updateStatus) . ' ' . $latestVersion; } $io->write(' <' . $style . '>' . str_pad($latestVersion, $latestLength, ' ') . '', false); } if (isset($package['description']) && $writeDescription) { $description = strtok($package['description'], "\r\n"); $remaining = $width - $nameLength - $versionLength - 4; if ($writeLatest) { $remaining -= $latestLength; } if (strlen($description) > $remaining) { $description = substr($description, 0, $remaining - 3) . '...'; } $io->write(' ' . $description, false); } if (isset($package['path'])) { $io->write(' ' . $package['path'], false); } $io->write(''); if (isset($package['warning'])) { $io->write('' . $package['warning'] . ''); } } if ($showAllTypes) { $io->write(''); } } } return $exitCode; } protected function getRootRequires() { $rootPackage = $this->getComposer()->getPackage(); return array_map( 'strtolower', array_keys(array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires())) ); } protected function getVersionStyle(PackageInterface $latestPackage, PackageInterface $package) { return $this->updateStatusToVersionStyle($this->getUpdateStatus($latestPackage, $package)); } /** * finds a package by name and version if provided * * @param RepositoryInterface $installedRepo * @param RepositoryInterface $repos * @param string $name * @param ConstraintInterface|string $version * @throws \InvalidArgumentException * @return array array(CompletePackageInterface, array of versions) */ protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null) { $name = strtolower($name); $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version; $policy = new DefaultPolicy(); $pool = new Pool('dev'); $pool->addRepository($repos); $matchedPackage = null; $versions = array(); $matches = $pool->whatProvides($name, $constraint); foreach ($matches as $index => $package) { // skip providers/replacers if ($package->getName() !== $name) { unset($matches[$index]); continue; } // select an exact match if it is in the installed repo and no specific version was required if (null === $version && $installedRepo->hasPackage($package)) { $matchedPackage = $package; } $versions[$package->getPrettyVersion()] = $package->getVersion(); $matches[$index] = $package->getId(); } // select preferred package according to policy rules if (!$matchedPackage && $matches && $preferred = $policy->selectPreferredPackages($pool, array(), $matches)) { $matchedPackage = $pool->literalToPackage($preferred[0]); } return array($matchedPackage, $versions); } /** * Prints package metadata. * * @param CompletePackageInterface $package * @param array $versions * @param RepositoryInterface $installedRepo */ protected function printMeta(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, PackageInterface $latestPackage = null) { $io = $this->getIO(); $io->write('name : ' . $package->getPrettyName()); $io->write('descrip. : ' . $package->getDescription()); $io->write('keywords : ' . implode(', ', $package->getKeywords() ?: array())); $this->printVersions($package, $versions, $installedRepo); if ($latestPackage) { $style = $this->getVersionStyle($latestPackage, $package); $io->write('latest : <'.$style.'>' . $latestPackage->getPrettyVersion() . ''); } else { $latestPackage = $package; } $io->write('type : ' . $package->getType()); $this->printLicenses($package); $io->write('source : ' . sprintf('[%s] %s %s', $package->getSourceType(), $package->getSourceUrl(), $package->getSourceReference())); $io->write('dist : ' . sprintf('[%s] %s %s', $package->getDistType(), $package->getDistUrl(), $package->getDistReference())); $io->write('names : ' . implode(', ', $package->getNames())); if ($latestPackage->isAbandoned()) { $replacement = ($latestPackage->getReplacementPackage() !== null) ? ' The author suggests using the ' . $latestPackage->getReplacementPackage(). ' package instead.' : null; $io->writeError( sprintf('Attention: This package is abandoned and no longer maintained.%s', $replacement) ); } if ($package->getSupport()) { $io->write("\nsupport"); foreach ($package->getSupport() as $type => $value) { $io->write('' . $type . ' : '.$value); } } if ($package->getAutoload()) { $io->write("\nautoload"); foreach ($package->getAutoload() as $type => $autoloads) { $io->write('' . $type . ''); if ($type === 'psr-0') { foreach ($autoloads as $name => $path) { $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.'))); } } elseif ($type === 'psr-4') { foreach ($autoloads as $name => $path) { $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.'))); } } elseif ($type === 'classmap') { $io->write(implode(', ', $autoloads)); } } if ($package->getIncludePaths()) { $io->write('include-path'); $io->write(implode(', ', $package->getIncludePaths())); } } } /** * Prints all available versions of this package and highlights the installed one if any. * * @param CompletePackageInterface $package * @param array $versions * @param RepositoryInterface $installedRepo */ protected function printVersions(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo) { uasort($versions, 'version_compare'); $versions = array_keys(array_reverse($versions)); // highlight installed version if ($installedRepo->hasPackage($package)) { $installedVersion = $package->getPrettyVersion(); $key = array_search($installedVersion, $versions); if (false !== $key) { $versions[$key] = '* ' . $installedVersion . ''; } } $versions = implode(', ', $versions); $this->getIO()->write('versions : ' . $versions); } /** * print link objects * * @param CompletePackageInterface $package * @param string $linkType * @param string $title */ protected function printLinks(CompletePackageInterface $package, $linkType, $title = null) { $title = $title ?: $linkType; $io = $this->getIO(); if ($links = $package->{'get'.ucfirst($linkType)}()) { $io->write("\n" . $title . ""); foreach ($links as $link) { $io->write($link->getTarget() . ' ' . $link->getPrettyConstraint() . ''); } } } /** * Prints the licenses of a package with metadata * * @param CompletePackageInterface $package */ protected function printLicenses(CompletePackageInterface $package) { $spdxLicenses = new SpdxLicenses(); $licenses = $package->getLicense(); $io = $this->getIO(); foreach ($licenses as $licenseId) { $license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url if (!$license) { $out = $licenseId; } else { // is license OSI approved? if ($license[1] === true) { $out = sprintf('%s (%s) (OSI approved) %s', $license[0], $licenseId, $license[2]); } else { $out = sprintf('%s (%s) %s', $license[0], $licenseId, $license[2]); } } $io->write('license : ' . $out); } } /** * Init styles for tree * * @param OutputInterface $output */ protected function initStyles(OutputInterface $output) { $this->colors = array( 'green', 'yellow', 'cyan', 'magenta', 'blue', ); foreach ($this->colors as $color) { $style = new OutputFormatterStyle($color); $output->getFormatter()->setStyle($color, $style); } } /** * Display the tree * * @param PackageInterface|string $package * @param RepositoryInterface $installedRepo * @param RepositoryInterface $distantRepos */ protected function displayPackageTree(PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos) { $io = $this->getIO(); $io->write(sprintf('%s', $package->getPrettyName()), false); $io->write(' ' . $package->getPrettyVersion(), false); $io->write(' ' . strtok($package->getDescription(), "\r\n")); if (is_object($package)) { $requires = $package->getRequires(); ksort($requires); $treeBar = '├'; $j = 0; $total = count($requires); foreach ($requires as $requireName => $require) { $j++; if ($j == 0) { $this->writeTreeLine($treeBar); } if ($j == $total) { $treeBar = 'â””'; } $level = 1; $color = $this->colors[$level]; $info = sprintf('%s──<%s>%s %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint()); $this->writeTreeLine($info); $treeBar = str_replace('â””', ' ', $treeBar); $packagesInTree = array($package->getName(), $requireName); $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $packagesInTree, $treeBar, $level + 1); } } } /** * Display a package tree * * @param string $name * @param PackageInterface|string $package * @param RepositoryInterface $installedRepo * @param RepositoryInterface $distantRepos * @param array $packagesInTree * @param string $previousTreeBar * @param int $level */ protected function displayTree($name, $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos, array $packagesInTree, $previousTreeBar = '├', $level = 1) { $previousTreeBar = str_replace('├', '│', $previousTreeBar); list($package, $versions) = $this->getPackage($installedRepo, $distantRepos, $name, $package->getPrettyConstraint() === 'self.version' ? $package->getConstraint() : $package->getPrettyConstraint()); if (is_object($package)) { $requires = $package->getRequires(); ksort($requires); $treeBar = $previousTreeBar . ' ├'; $i = 0; $total = count($requires); foreach ($requires as $requireName => $require) { $currentTree = $packagesInTree; $i++; if ($i == $total) { $treeBar = $previousTreeBar . ' â””'; } $colorIdent = $level % count($this->colors); $color = $this->colors[$colorIdent]; $circularWarn = in_array($requireName, $currentTree) ? '(circular dependency aborted here)' : ''; $info = rtrim(sprintf('%s──<%s>%s %s %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint(), $circularWarn)); $this->writeTreeLine($info); $treeBar = str_replace('â””', ' ', $treeBar); if (!in_array($requireName, $currentTree)) { $currentTree[] = $requireName; $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $currentTree, $treeBar, $level + 1); } } } } private function updateStatusToVersionStyle($updateStatus) { // 'up-to-date' is printed green // 'semver-safe-update' is printed red // 'update-possible' is printed yellow return str_replace(array('up-to-date', 'semver-safe-update', 'update-possible'), array('info', 'highlight', 'comment'), $updateStatus); } private function getUpdateStatus(PackageInterface $latestPackage, PackageInterface $package) { if ($latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion()) { return 'up-to-date'; } $constraint = $package->getVersion(); if (0 !== strpos($constraint, 'dev-')) { $constraint = '^'.$constraint; } if ($latestPackage->getVersion() && Semver::satisfies($latestPackage->getVersion(), $constraint)) { // it needs an immediate semver-compliant upgrade return 'semver-safe-update'; } // it needs an upgrade but has potential BC breaks so is not urgent return 'update-possible'; } private function writeTreeLine($line) { $io = $this->getIO(); if (!$io->isDecorated()) { $line = str_replace(array('â””', '├', '──', '│'), array('`-', '|-', '-', '|'), $line); } $io->write($line); } /** * Given a package, this finds the latest package matching it * * @param PackageInterface $package * @param Composer $composer * @param string $phpVersion * @param bool $minorOnly * * @return PackageInterface|null */ private function findLatestPackage(PackageInterface $package, Composer $composer, $phpVersion, $minorOnly = false) { // find the latest version allowed in this pool $name = $package->getName(); $versionSelector = new VersionSelector($this->getPool($composer)); $stability = $composer->getPackage()->getMinimumStability(); $flags = $composer->getPackage()->getStabilityFlags(); if (isset($flags[$name])) { $stability = array_search($flags[$name], BasePackage::$stabilities, true); } $bestStability = $stability; if ($composer->getPackage()->getPreferStable()) { $bestStability = $package->getStability(); } $targetVersion = null; if (0 === strpos($package->getVersion(), 'dev-')) { $targetVersion = $package->getVersion(); } if ($targetVersion === null && $minorOnly) { $targetVersion = '^' . $package->getVersion(); } return $versionSelector->findBestCandidate($name, $targetVersion, $phpVersion, $bestStability); } private function getPool(Composer $composer) { if (!$this->pool) { $this->pool = new Pool($composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags()); $this->pool->addRepository(new CompositeRepository($composer->getRepositoryManager()->getRepositories())); } return $this->pool; } } composer-1.6.3/src/Composer/Command/StatusCommand.php000066400000000000000000000176151323436022200226060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Downloader\ChangeReportInterface; use Composer\Downloader\DvcsDownloaderInterface; use Composer\Downloader\VcsCapableDownloaderInterface; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Script\ScriptEvents; use Composer\Util\ProcessExecutor; /** * @author Tiago Ribeiro * @author Rui Marinho */ class StatusCommand extends BaseCommand { const EXIT_CODE_ERRORS = 1; const EXIT_CODE_UNPUSHED_CHANGES = 2; const EXIT_CODE_VERSION_CHANGES = 4; protected function configure() { $this ->setName('status') ->setDescription('Shows a list of locally modified packages.') ->setDefinition(array( new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Show modified files for each directory that contains changes.'), )) ->setHelp(<<getComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'status', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $installedRepo = $composer->getRepositoryManager()->getLocalRepository(); $dm = $composer->getDownloadManager(); $im = $composer->getInstallationManager(); // Dispatch pre-status-command $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_STATUS_CMD, true); $errors = array(); $io = $this->getIO(); $unpushedChanges = array(); $vcsVersionChanges = array(); $parser = new VersionParser; $guesser = new VersionGuesser($composer->getConfig(), new ProcessExecutor($io), $parser); $dumper = new ArrayDumper; // list packages foreach ($installedRepo->getCanonicalPackages() as $package) { $downloader = $dm->getDownloaderForInstalledPackage($package); $targetDir = $im->getInstallPath($package); if ($downloader instanceof ChangeReportInterface) { if (is_link($targetDir)) { $errors[$targetDir] = $targetDir . ' is a symbolic link.'; } if ($changes = $downloader->getLocalChanges($package, $targetDir)) { $errors[$targetDir] = $changes; } } if ($downloader instanceof VcsCapableDownloaderInterface) { if ($currentRef = $downloader->getVcsReference($package, $targetDir)) { switch ($package->getInstallationSource()) { case 'source': $previousRef = $package->getSourceReference(); break; case 'dist': $previousRef = $package->getDistReference(); break; default: $previousRef = null; } $currentVersion = $guesser->guessVersion($dumper->dump($package), $targetDir); if ($previousRef && $currentVersion && $currentVersion['commit'] !== $previousRef) { $vcsVersionChanges[$targetDir] = array( 'previous' => array( 'version' => $package->getPrettyVersion(), 'ref' => $previousRef, ), 'current' => array( 'version' => $currentVersion['pretty_version'], 'ref' => $currentVersion['commit'], ), ); } } } if ($downloader instanceof DvcsDownloaderInterface) { if ($unpushed = $downloader->getUnpushedChanges($package, $targetDir)) { $unpushedChanges[$targetDir] = $unpushed; } } } // output errors/warnings if (!$errors && !$unpushedChanges && !$vcsVersionChanges) { $io->writeError('No local changes'); return 0; } if ($errors) { $io->writeError('You have changes in the following dependencies:'); foreach ($errors as $path => $changes) { if ($input->getOption('verbose')) { $indentedChanges = implode("\n", array_map(function ($line) { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write(''.$path.':'); $io->write($indentedChanges); } else { $io->write($path); } } } if ($unpushedChanges) { $io->writeError('You have unpushed changes on the current branch in the following dependencies:'); foreach ($unpushedChanges as $path => $changes) { if ($input->getOption('verbose')) { $indentedChanges = implode("\n", array_map(function ($line) { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write(''.$path.':'); $io->write($indentedChanges); } else { $io->write($path); } } } if ($vcsVersionChanges) { $io->writeError('You have version variations in the following dependencies:'); foreach ($vcsVersionChanges as $path => $changes) { if ($input->getOption('verbose')) { // If we don't can't find a version, use the ref instead. $currentVersion = $changes['current']['version'] ?: $changes['current']['ref']; $previousVersion = $changes['previous']['version'] ?: $changes['previous']['ref']; if ($io->isVeryVerbose()) { // Output the ref regardless of whether or not it's being used as the version $currentVersion .= sprintf(' (%s)', $changes['current']['ref']); $previousVersion .= sprintf(' (%s)', $changes['previous']['ref']); } $io->write(''.$path.':'); $io->write(sprintf(' From %s to %s', $previousVersion, $currentVersion)); } else { $io->write($path); } } } if (($errors || $unpushedChanges || $vcsVersionChanges) && !$input->getOption('verbose')) { $io->writeError('Use --verbose (-v) to see a list of files'); } // Dispatch post-status-command $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_STATUS_CMD, true); return ($errors ? self::EXIT_CODE_ERRORS : 0) + ($unpushedChanges ? self::EXIT_CODE_UNPUSHED_CHANGES : 0) + ($vcsVersionChanges ? self::EXIT_CODE_VERSION_CHANGES : 0); } } composer-1.6.3/src/Composer/Command/SuggestsCommand.php000066400000000000000000000121511323436022200231150ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Repository\PlatformRepository; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class SuggestsCommand extends BaseCommand { protected function configure() { $this ->setName('suggests') ->setDescription('Shows package suggestions.') ->setDefinition(array( new InputOption('by-package', null, InputOption::VALUE_NONE, 'Groups output by suggesting package'), new InputOption('by-suggestion', null, InputOption::VALUE_NONE, 'Groups output by suggested package'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Exclude suggestions from require-dev packages'), new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Packages that you want to list suggestions from.'), )) ->setHelp(<<%command.name% command shows a sorted list of suggested packages. Enabling -v implies --by-package --by-suggestion, showing both lists. EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $lock = $this->getComposer()->getLocker()->getLockData(); if (empty($lock)) { throw new \RuntimeException('Lockfile seems to be empty?'); } $packages = $lock['packages']; if (!$input->getOption('no-dev')) { $packages += $lock['packages-dev']; } $filter = $input->getArgument('packages'); // First assemble lookup list of packages that are installed, replaced or provided $installed = array(); foreach ($packages as $package) { $installed[] = $package['name']; if (!empty($package['provide'])) { $installed = array_merge($installed, array_keys($package['provide'])); } if (!empty($package['replace'])) { $installed = array_merge($installed, array_keys($package['replace'])); } } // Undub and sort the install list into a sorted lookup array $installed = array_flip($installed); ksort($installed); // Init platform repo $platform = new PlatformRepository(array(), $this->getComposer()->getConfig()->get('platform') ?: array()); // Next gather all suggestions that are not in that list $suggesters = array(); $suggested = array(); foreach ($packages as $package) { $packageName = $package['name']; if ((!empty($filter) && !in_array($packageName, $filter)) || empty($package['suggest'])) { continue; } foreach ($package['suggest'] as $suggestion => $reason) { if (false === strpos('/', $suggestion) && null !== $platform->findPackage($suggestion, '*')) { continue; } if (!isset($installed[$suggestion])) { $suggesters[$packageName][$suggestion] = $reason; $suggested[$suggestion][$packageName] = $reason; } } } ksort($suggesters); ksort($suggested); // Determine output mode $mode = 0; $io = $this->getIO(); if ($input->getOption('by-package') || $io->isVerbose()) { $mode |= 1; } if ($input->getOption('by-suggestion')) { $mode |= 2; } // Simple mode if ($mode === 0) { foreach (array_keys($suggested) as $suggestion) { $io->write(sprintf('%s', $suggestion)); } return; } // Grouped by package if ($mode & 1) { foreach ($suggesters as $suggester => $suggestions) { $io->write(sprintf('%s suggests:', $suggester)); foreach ($suggestions as $suggestion => $reason) { $io->write(sprintf(' - %s: %s', $suggestion, $reason ?: '*')); } $io->write(''); } } // Grouped by suggestion if ($mode & 2) { // Improve readability in full mode if ($mode & 1) { $io->write(str_repeat('-', 78)); } foreach ($suggested as $suggestion => $suggesters) { $io->write(sprintf('%s is suggested by:', $suggestion)); foreach ($suggesters as $suggester => $reason) { $io->write(sprintf(' - %s: %s', $suggester, $reason ?: '*')); } $io->write(''); } } } } composer-1.6.3/src/Composer/Command/UpdateCommand.php000066400000000000000000000255061323436022200225430ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Installer; use Composer\IO\IOInterface; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; /** * @author Jordi Boggiano * @author Nils Adermann */ class UpdateCommand extends BaseCommand { protected function configure() { $this ->setName('update') ->setAliases(array('upgrade')) ->setDescription('Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.') ->setDefinition(array( new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Packages that should be updated, if not provided all packages are.'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('lock', null, InputOption::VALUE_NONE, 'Only updates the lock file hash to suppress warning about the lock file being out of date.'), new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'), new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'Do not show package suggestions.'), new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Add also dependencies of whitelisted packages to the whitelist, except those defined in root package.'), new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Add also all dependencies of whitelisted packages to the whitelist, including those defined in root package.'), new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump.'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'), new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'), new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'), new InputOption('interactive', 'i', InputOption::VALUE_NONE, 'Interactive interface with autocompletion to select the packages to update.'), new InputOption('root-reqs', null, InputOption::VALUE_NONE, 'Restricts the update to your first degree dependencies.'), )) ->setHelp(<<update command reads the composer.json file from the current directory, processes it, and updates, removes or installs all the dependencies. php composer.phar update To limit the update operation to a few packages, you can list the package(s) you want to update as such: php composer.phar update vendor/package1 foo/mypackage [...] You may also use an asterisk (*) pattern to limit the update operation to package(s) from a specific vendor: php composer.phar update vendor/package1 foo/* [...] To select packages names interactively with auto-completion use -i. EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $io = $this->getIO(); if ($input->getOption('no-custom-installers')) { $io->writeError('You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.'); $input->setOption('no-plugins', true); } if ($input->getOption('dev')) { $io->writeError('You are using the deprecated option "dev". Dev packages are installed by default now.'); } $composer = $this->getComposer(true, $input->getOption('no-plugins')); $packages = $input->getArgument('packages'); if ($input->getOption('interactive')) { $packages = $this->getPackagesInteractively($io, $input, $output, $composer, $packages); } if ($input->getOption('root-reqs')) { $require = array_keys($composer->getPackage()->getRequires()); if (!$input->getOption('no-dev')) { $requireDev = array_keys($composer->getPackage()->getDevRequires()); $require = array_merge($require, $requireDev); } if (!empty($packages)) { $packages = array_intersect($packages, $require); } else { $packages = $require; } } $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress')); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'update', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $install = Installer::create($io, $composer); $config = $composer->getConfig(); list($preferSource, $preferDist) = $this->getPreferredInstallOptions($config, $input); $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcu = $input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $install ->setDryRun($input->getOption('dry-run')) ->setVerbose($input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$input->getOption('no-dev')) ->setDumpAutoloader(!$input->getOption('no-autoloader')) ->setRunScripts(!$input->getOption('no-scripts')) ->setSkipSuggest($input->getOption('no-suggest')) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setUpdate(true) ->setUpdateWhitelist($input->getOption('lock') ? array('lock') : $packages) ->setWhitelistTransitiveDependencies($input->getOption('with-dependencies')) ->setWhitelistAllDependencies($input->getOption('with-all-dependencies')) ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')) ->setPreferStable($input->getOption('prefer-stable')) ->setPreferLowest($input->getOption('prefer-lowest')) ; if ($input->getOption('no-plugins')) { $install->disablePlugins(); } return $install->run(); } private function getPackagesInteractively(IOInterface $io, InputInterface $input, OutputInterface $output, Composer $composer, array $packages) { if (!$input->isInteractive()) { throw new \InvalidArgumentException('--interactive cannot be used in non-interactive terminals.'); } $requires = array_merge( $composer->getPackage()->getRequires(), $composer->getPackage()->getDevRequires() ); $autocompleterValues = array(); foreach ($requires as $require) { $target = $require->getTarget(); $autocompleterValues[strtolower($target)] = $target; } $installedPackages = $composer->getRepositoryManager()->getLocalRepository()->getPackages(); foreach ($installedPackages as $package) { $autocompleterValues[$package->getName()] = $package->getPrettyName(); } $helper = $this->getHelper('question'); $question = new Question('Enter package name: ', null); $io->writeError('Press enter without value to end submission'); do { $autocompleterValues = array_diff($autocompleterValues, $packages); $question->setAutocompleterValues($autocompleterValues); $addedPackage = $helper->ask($input, $output, $question); if (!is_string($addedPackage) || empty($addedPackage)) { break; } $addedPackage = strtolower($addedPackage); if (!in_array($addedPackage, $packages)) { $packages[] = $addedPackage; } } while (true); $packages = array_filter($packages); if (!$packages) { throw new \InvalidArgumentException('You must enter minimum one package.'); } $table = new Table($output); $table->setHeaders(array('Selected packages')); foreach ($packages as $package) { $table->addRow(array($package)); } $table->render(); if ($io->askConfirmation(sprintf( 'Would you like to continue and update the above package%s [yes]? ', 1 === count($packages) ? '' : 's' ), true)) { return $packages; } throw new \RuntimeException('Installation aborted.'); } } composer-1.6.3/src/Composer/Command/ValidateCommand.php000066400000000000000000000153531323436022200230510ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\Package\Loader\ValidatingArrayLoader; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\ConfigValidator; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * ValidateCommand * * @author Robert Schönthal * @author Jordi Boggiano */ class ValidateCommand extends BaseCommand { /** * configure */ protected function configure() { $this ->setName('validate') ->setDescription('Validates a composer.json and composer.lock.') ->setDefinition(array( new InputOption('no-check-all', null, InputOption::VALUE_NONE, 'Do not make a complete validation'), new InputOption('no-check-lock', null, InputOption::VALUE_NONE, 'Do not check if lock file is up to date'), new InputOption('no-check-publish', null, InputOption::VALUE_NONE, 'Do not check for publish errors'), new InputOption('with-dependencies', 'A', InputOption::VALUE_NONE, 'Also validate the composer.json of all installed dependencies'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code for warnings as well as errors'), new InputArgument('file', InputArgument::OPTIONAL, 'path to composer.json file'), )) ->setHelp(<<getArgument('file') ?: Factory::getComposerFile(); $io = $this->getIO(); if (!file_exists($file)) { $io->writeError('' . $file . ' not found.'); return 3; } if (!is_readable($file)) { $io->writeError('' . $file . ' is not readable.'); return 3; } $validator = new ConfigValidator($io); $checkAll = $input->getOption('no-check-all') ? 0 : ValidatingArrayLoader::CHECK_ALL; $checkPublish = !$input->getOption('no-check-publish'); $checkLock = !$input->getOption('no-check-lock'); $isStrict = $input->getOption('strict'); list($errors, $publishErrors, $warnings) = $validator->validate($file, $checkAll); $lockErrors = array(); $composer = Factory::create($io, $file); $locker = $composer->getLocker(); if ($locker->isLocked() && !$locker->isFresh()) { $lockErrors[] = 'The lock file is not up to date with the latest changes in composer.json, it is recommended that you run `composer update`.'; } $this->outputResult($io, $file, $errors, $warnings, $checkPublish, $publishErrors, $checkLock, $lockErrors, true); $exitCode = $errors || ($publishErrors && $checkPublish) || ($lockErrors && $checkLock) ? 2 : ($isStrict && $warnings ? 1 : 0); if ($input->getOption('with-dependencies')) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); foreach ($localRepo->getPackages() as $package) { $path = $composer->getInstallationManager()->getInstallPath($package); $file = $path . '/composer.json'; if (is_dir($path) && file_exists($file)) { list($errors, $publishErrors, $warnings) = $validator->validate($file, $checkAll); $this->outputResult($io, $package->getPrettyName(), $errors, $warnings, $checkPublish, $publishErrors); $depCode = $errors || ($publishErrors && $checkPublish) ? 2 : ($isStrict && $warnings ? 1 : 0); $exitCode = max($depCode, $exitCode); } } } $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'validate', $input, $output); $eventCode = $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $exitCode = max($eventCode, $exitCode); return $exitCode; } private function outputResult($io, $name, &$errors, &$warnings, $checkPublish = false, $publishErrors = array(), $checkLock = false, $lockErrors = array(), $printSchemaUrl = false) { if (!$errors && !$publishErrors && !$warnings) { $io->write('' . $name . ' is valid'); } elseif (!$errors && !$publishErrors) { $io->writeError('' . $name . ' is valid, but with a few warnings'); if ($printSchemaUrl) { $io->writeError('See https://getcomposer.org/doc/04-schema.md for details on the schema'); } } elseif (!$errors) { $io->writeError('' . $name . ' is valid for simple usage with composer but has'); $io->writeError('strict errors that make it unable to be published as a package:'); if ($printSchemaUrl) { $io->writeError('See https://getcomposer.org/doc/04-schema.md for details on the schema'); } } else { $io->writeError('' . $name . ' is invalid, the following errors/warnings were found:'); } // If checking publish errors, display them as errors, otherwise just show them as warnings if ($checkPublish) { $errors = array_merge($errors, $publishErrors); } else { $warnings = array_merge($warnings, $publishErrors); } // If checking lock errors, display them as errors, otherwise just show them as warnings if ($checkLock) { $errors = array_merge($errors, $lockErrors); } else { $warnings = array_merge($warnings, $lockErrors); } $messages = array( 'error' => $errors, 'warning' => $warnings, ); foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { $io->writeError('<' . $style . '>' . $msg . ''); } } } } composer-1.6.3/src/Composer/Compiler.php000066400000000000000000000236421323436022200202150ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Json\JsonFile; use Composer\Spdx\SpdxLicenses; use Composer\CaBundle\CaBundle; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; use Seld\PharUtils\Timestamps; /** * The Compiler class compiles composer into a phar * * @author Fabien Potencier * @author Jordi Boggiano */ class Compiler { private $version; private $branchAliasVersion = ''; private $versionDate; /** * Compiles composer into a single phar file * * @param string $pharFile The full path to the file to create * @throws \RuntimeException */ public function compile($pharFile = 'composer.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__); if ($process->run() != 0) { throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.'); } $this->version = trim($process->getOutput()); $process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__); if ($process->run() != 0) { throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.'); } $this->versionDate = new \DateTime(trim($process->getOutput())); $this->versionDate->setTimezone(new \DateTimeZone('UTC')); $process = new Process('git describe --tags --exact-match HEAD'); if ($process->run() == 0) { $this->version = trim($process->getOutput()); } else { // get branch-alias defined in composer.json for dev-master (if any) $localConfig = __DIR__.'/../../composer.json'; $file = new JsonFile($localConfig); $localConfig = $file->read(); if (isset($localConfig['extra']['branch-alias']['dev-master'])) { $this->branchAliasVersion = $localConfig['extra']['branch-alias']['dev-master']; } } $phar = new \Phar($pharFile, 0, 'composer.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finderSort = function ($a, $b) { return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/')); }; $finder = new Finder(); $finder->files() ->ignoreVCS(true) ->name('*.php') ->notName('Compiler.php') ->notName('ClassLoader.php') ->in(__DIR__.'/..') ->sort($finderSort) ; foreach ($finder as $file) { $this->addFile($phar, $file); } $this->addFile($phar, new \SplFileInfo(__DIR__ . '/Autoload/ClassLoader.php'), false); $finder = new Finder(); $finder->files() ->name('*.json') ->in(__DIR__.'/../../res') ->in(SpdxLicenses::getResourcesDir()) ->sort($finderSort) ; foreach ($finder as $file) { $this->addFile($phar, $file, false); } $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../vendor/seld/cli-prompt/res/hiddeninput.exe'), false); $finder = new Finder(); $finder->files() ->ignoreVCS(true) ->name('*.php') ->name('LICENSE') ->exclude('Tests') ->exclude('tests') ->exclude('docs') ->in(__DIR__.'/../../vendor/symfony/') ->in(__DIR__.'/../../vendor/seld/jsonlint/') ->in(__DIR__.'/../../vendor/seld/cli-prompt/') ->in(__DIR__.'/../../vendor/justinrainbow/json-schema/') ->in(__DIR__.'/../../vendor/composer/spdx-licenses/') ->in(__DIR__.'/../../vendor/composer/semver/') ->in(__DIR__.'/../../vendor/composer/ca-bundle/') ->in(__DIR__.'/../../vendor/psr/') ->sort($finderSort) ; foreach ($finder as $file) { $this->addFile($phar, $file); } $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_psr4.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_files.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php')); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_static.php')); if (file_exists(__DIR__.'/../../vendor/composer/include_paths.php')) { $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/include_paths.php')); } $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/ClassLoader.php')); $this->addFile($phar, new \SplFileInfo(CaBundle::getBundledCaBundlePath()), false); $this->addComposerBin($phar); // Stubs $phar->setStub($this->getStub()); $phar->stopBuffering(); // disabled for interoperability with systems without gzip ext // $phar->compressFiles(\Phar::GZ); $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../LICENSE'), false); unset($phar); // re-sign the phar with reproducible timestamp / signature $util = new Timestamps($pharFile); $util->updateTimestamps($this->versionDate); $util->save($pharFile, \Phar::SHA1); } /** * @param \SplFileInfo $file * @return string */ private function getRelativeFilePath($file) { $realPath = $file->getRealPath(); $pathPrefix = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR; $pos = strpos($realPath, $pathPrefix); $relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath; return strtr($relativePath, '\\', '/'); } private function addFile($phar, $file, $strip = true) { $path = $this->getRelativeFilePath($file); $content = file_get_contents($file); if ($strip) { $content = $this->stripWhitespace($content); } elseif ('LICENSE' === basename($file)) { $content = "\n".$content."\n"; } if ($path === 'src/Composer/Composer.php') { $content = str_replace('@package_version@', $this->version, $content); $content = str_replace('@package_branch_alias_version@', $this->branchAliasVersion, $content); $content = str_replace('@release_date@', $this->versionDate->format('Y-m-d H:i:s'), $content); } $phar->addFromString($path, $content); } private function addComposerBin($phar) { $content = file_get_contents(__DIR__.'/../../bin/composer'); $content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content); $phar->addFromString('bin/composer', $content); } /** * Removes whitespace from a PHP source string while preserving line numbers. * * @param string $source A PHP string * @return string The PHP string with the whitespace removed */ private function stripWhitespace($source) { if (!function_exists('token_get_all')) { return $source; } $output = ''; foreach (token_get_all($source) as $token) { if (is_string($token)) { $output .= $token; } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) { $output .= str_repeat("\n", substr_count($token[1], "\n")); } elseif (T_WHITESPACE === $token[0]) { // reduce wide spaces $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]); // normalize newlines to \n $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace); // trim leading spaces $whitespace = preg_replace('{\n +}', "\n", $whitespace); $output .= $whitespace; } else { $output .= $token[1]; } } return $output; } private function getStub() { $stub = <<<'EOF' #!/usr/bin/env php * Jordi Boggiano * * For the full copyright and license information, please view * the license that is located at the bottom of this file. */ // Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264 if (extension_loaded('apc') && ini_get('apc.enable_cli') && ini_get('apc.cache_by_default')) { if (version_compare(phpversion('apc'), '3.0.12', '>=')) { ini_set('apc.cache_by_default', 0); } else { fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL); fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL); } } Phar::mapPhar('composer.phar'); EOF; // add warning once the phar is older than 60 days if (preg_match('{^[a-f0-9]+$}', $this->version)) { $warningTime = $this->versionDate->format('U') + 60 * 86400; $stub .= "define('COMPOSER_DEV_WARNING_TIME', $warningTime);\n"; } return $stub . <<<'EOF' require 'phar://composer.phar/bin/composer'; __HALT_COMPILER(); EOF; } } composer-1.6.3/src/Composer/Composer.php000066400000000000000000000115571323436022200202340ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Package\RootPackageInterface; use Composer\Package\Locker; use Composer\Repository\RepositoryManager; use Composer\Installer\InstallationManager; use Composer\Plugin\PluginManager; use Composer\Downloader\DownloadManager; use Composer\EventDispatcher\EventDispatcher; use Composer\Autoload\AutoloadGenerator; use Composer\Package\Archiver\ArchiveManager; /** * @author Jordi Boggiano * @author Konstantin Kudryashiv * @author Nils Adermann */ class Composer { const VERSION = '1.6.3'; const BRANCH_ALIAS_VERSION = ''; const RELEASE_DATE = '2018-01-31 16:28:17'; /** * @var Package\RootPackageInterface */ private $package; /** * @var Locker */ private $locker; /** * @var Repository\RepositoryManager */ private $repositoryManager; /** * @var Downloader\DownloadManager */ private $downloadManager; /** * @var Installer\InstallationManager */ private $installationManager; /** * @var Plugin\PluginManager */ private $pluginManager; /** * @var Config */ private $config; /** * @var EventDispatcher */ private $eventDispatcher; /** * @var Autoload\AutoloadGenerator */ private $autoloadGenerator; /** * @var ArchiveManager */ private $archiveManager; /** * @param Package\RootPackageInterface $package * @return void */ public function setPackage(RootPackageInterface $package) { $this->package = $package; } /** * @return Package\RootPackageInterface */ public function getPackage() { return $this->package; } /** * @param Config $config */ public function setConfig(Config $config) { $this->config = $config; } /** * @return Config */ public function getConfig() { return $this->config; } /** * @param Package\Locker $locker */ public function setLocker(Locker $locker) { $this->locker = $locker; } /** * @return Package\Locker */ public function getLocker() { return $this->locker; } /** * @param Repository\RepositoryManager $manager */ public function setRepositoryManager(RepositoryManager $manager) { $this->repositoryManager = $manager; } /** * @return Repository\RepositoryManager */ public function getRepositoryManager() { return $this->repositoryManager; } /** * @param Downloader\DownloadManager $manager */ public function setDownloadManager(DownloadManager $manager) { $this->downloadManager = $manager; } /** * @return Downloader\DownloadManager */ public function getDownloadManager() { return $this->downloadManager; } /** * @param ArchiveManager $manager */ public function setArchiveManager(ArchiveManager $manager) { $this->archiveManager = $manager; } /** * @return ArchiveManager */ public function getArchiveManager() { return $this->archiveManager; } /** * @param Installer\InstallationManager $manager */ public function setInstallationManager(InstallationManager $manager) { $this->installationManager = $manager; } /** * @return Installer\InstallationManager */ public function getInstallationManager() { return $this->installationManager; } /** * @param Plugin\PluginManager $manager */ public function setPluginManager(PluginManager $manager) { $this->pluginManager = $manager; } /** * @return Plugin\PluginManager */ public function getPluginManager() { return $this->pluginManager; } /** * @param EventDispatcher $eventDispatcher */ public function setEventDispatcher(EventDispatcher $eventDispatcher) { $this->eventDispatcher = $eventDispatcher; } /** * @return EventDispatcher */ public function getEventDispatcher() { return $this->eventDispatcher; } /** * @param Autoload\AutoloadGenerator $autoloadGenerator */ public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator) { $this->autoloadGenerator = $autoloadGenerator; } /** * @return Autoload\AutoloadGenerator */ public function getAutoloadGenerator() { return $this->autoloadGenerator; } } composer-1.6.3/src/Composer/Config.php000066400000000000000000000362051323436022200176470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Config\ConfigSourceInterface; use Composer\Downloader\TransportException; use Composer\IO\IOInterface; use Composer\Util\Platform; /** * @author Jordi Boggiano */ class Config { const RELATIVE_PATHS = 1; public static $defaultConfig = array( 'process-timeout' => 300, 'use-include-path' => false, 'preferred-install' => 'auto', 'notify-on-install' => true, 'github-protocols' => array('https', 'ssh', 'git'), 'vendor-dir' => 'vendor', 'bin-dir' => '{$vendor-dir}/bin', 'cache-dir' => '{$home}/cache', 'data-dir' => '{$home}', 'cache-files-dir' => '{$cache-dir}/files', 'cache-repo-dir' => '{$cache-dir}/repo', 'cache-vcs-dir' => '{$cache-dir}/vcs', 'cache-ttl' => 15552000, // 6 months 'cache-files-ttl' => null, // fallback to cache-ttl 'cache-files-maxsize' => '300MiB', 'bin-compat' => 'auto', 'discard-changes' => false, 'autoloader-suffix' => null, 'sort-packages' => false, 'optimize-autoloader' => false, 'classmap-authoritative' => false, 'apcu-autoloader' => false, 'prepend-autoloader' => true, 'github-domains' => array('github.com'), 'bitbucket-expose-hostname' => true, 'disable-tls' => false, 'secure-http' => true, 'cafile' => null, 'capath' => null, 'github-expose-hostname' => true, 'gitlab-domains' => array('gitlab.com'), 'store-auths' => 'prompt', 'platform' => array(), 'archive-format' => 'tar', 'archive-dir' => '.', 'htaccess-protect' => true, // valid keys without defaults (auth config stuff): // bitbucket-oauth // github-oauth // gitlab-oauth // gitlab-token // http-basic ); public static $defaultRepositories = array( 'packagist.org' => array( 'type' => 'composer', 'url' => 'https?://packagist.org', 'allow_ssl_downgrade' => true, ), ); private $config; private $baseDir; private $repositories; /** @var ConfigSourceInterface */ private $configSource; /** @var ConfigSourceInterface */ private $authConfigSource; private $useEnvironment; private $warnedHosts = array(); /** * @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings * @param string $baseDir Optional base directory of the config */ public function __construct($useEnvironment = true, $baseDir = null) { // load defaults $this->config = static::$defaultConfig; $this->repositories = static::$defaultRepositories; $this->useEnvironment = (bool) $useEnvironment; $this->baseDir = $baseDir; } public function setConfigSource(ConfigSourceInterface $source) { $this->configSource = $source; } public function getConfigSource() { return $this->configSource; } public function setAuthConfigSource(ConfigSourceInterface $source) { $this->authConfigSource = $source; } public function getAuthConfigSource() { return $this->authConfigSource; } /** * Merges new config values with the existing ones (overriding) * * @param array $config */ public function merge($config) { // override defaults with given config if (!empty($config['config']) && is_array($config['config'])) { foreach ($config['config'] as $key => $val) { if (in_array($key, array('bitbucket-oauth', 'github-oauth', 'gitlab-oauth', 'gitlab-token', 'http-basic')) && isset($this->config[$key])) { $this->config[$key] = array_merge($this->config[$key], $val); } elseif ('preferred-install' === $key && isset($this->config[$key])) { if (is_array($val) || is_array($this->config[$key])) { if (is_string($val)) { $val = array('*' => $val); } if (is_string($this->config[$key])) { $this->config[$key] = array('*' => $this->config[$key]); } $this->config[$key] = array_merge($this->config[$key], $val); // the full match pattern needs to be last if (isset($this->config[$key]['*'])) { $wildcard = $this->config[$key]['*']; unset($this->config[$key]['*']); $this->config[$key]['*'] = $wildcard; } } else { $this->config[$key] = $val; } } else { $this->config[$key] = $val; } } } if (!empty($config['repositories']) && is_array($config['repositories'])) { $this->repositories = array_reverse($this->repositories, true); $newRepos = array_reverse($config['repositories'], true); foreach ($newRepos as $name => $repository) { // disable a repository by name if (false === $repository) { $this->disableRepoByName($name); continue; } // disable a repository with an anonymous {"name": false} repo if (is_array($repository) && 1 === count($repository) && false === current($repository)) { $this->disableRepoByName(key($repository)); continue; } // store repo if (is_int($name)) { $this->repositories[] = $repository; } else { if ($name === 'packagist') { // BC support for default "packagist" named repo $this->repositories[$name . '.org'] = $repository; } else { $this->repositories[$name] = $repository; } } } $this->repositories = array_reverse($this->repositories, true); } } /** * @return array */ public function getRepositories() { return $this->repositories; } /** * Returns a setting * * @param string $key * @param int $flags Options (see class constants) * @throws \RuntimeException * @return mixed */ public function get($key, $flags = 0) { switch ($key) { case 'vendor-dir': case 'bin-dir': case 'process-timeout': case 'data-dir': case 'cache-dir': case 'cache-files-dir': case 'cache-repo-dir': case 'cache-vcs-dir': case 'cafile': case 'capath': case 'htaccess-protect': // convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config $env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_')); $val = $this->getComposerEnv($env); $val = rtrim((string) $this->process(false !== $val ? $val : $this->config[$key], $flags), '/\\'); $val = Platform::expandPath($val); if (substr($key, -4) !== '-dir') { return $val; } return (($flags & self::RELATIVE_PATHS) == self::RELATIVE_PATHS) ? $val : $this->realpath($val); case 'cache-ttl': return (int) $this->config[$key]; case 'cache-files-maxsize': if (!preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $this->config[$key], $matches)) { throw new \RuntimeException( "Could not parse the value of 'cache-files-maxsize': {$this->config[$key]}" ); } $size = $matches[1]; if (isset($matches[2])) { switch (strtolower($matches[2])) { case 'g': $size *= 1024; // intentional fallthrough case 'm': $size *= 1024; // intentional fallthrough case 'k': $size *= 1024; break; } } return $size; case 'cache-files-ttl': if (isset($this->config[$key])) { return (int) $this->config[$key]; } return (int) $this->config['cache-ttl']; case 'home': $val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $this->config[$key]); return rtrim($this->process($val, $flags), '/\\'); case 'bin-compat': $value = $this->getComposerEnv('COMPOSER_BIN_COMPAT') ?: $this->config[$key]; if (!in_array($value, array('auto', 'full'))) { throw new \RuntimeException( "Invalid value for 'bin-compat': {$value}. Expected auto, full" ); } return $value; case 'discard-changes': if ($env = $this->getComposerEnv('COMPOSER_DISCARD_CHANGES')) { if (!in_array($env, array('stash', 'true', 'false', '1', '0'), true)) { throw new \RuntimeException( "Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash" ); } if ('stash' === $env) { return 'stash'; } // convert string value to bool return $env !== 'false' && (bool) $env; } if (!in_array($this->config[$key], array(true, false, 'stash'), true)) { throw new \RuntimeException( "Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash" ); } return $this->config[$key]; case 'github-protocols': $protos = $this->config['github-protocols']; if ($this->config['secure-http'] && false !== ($index = array_search('git', $protos))) { unset($protos[$index]); } if (reset($protos) === 'http') { throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"'); } return $protos; case 'disable-tls': return $this->config[$key] !== 'false' && (bool) $this->config[$key]; case 'secure-http': return $this->config[$key] !== 'false' && (bool) $this->config[$key]; default: if (!isset($this->config[$key])) { return null; } return $this->process($this->config[$key], $flags); } } public function all($flags = 0) { $all = array( 'repositories' => $this->getRepositories(), ); foreach (array_keys($this->config) as $key) { $all['config'][$key] = $this->get($key, $flags); } return $all; } public function raw() { return array( 'repositories' => $this->getRepositories(), 'config' => $this->config, ); } /** * Checks whether a setting exists * * @param string $key * @return bool */ public function has($key) { return array_key_exists($key, $this->config); } /** * Replaces {$refs} inside a config string * * @param string|int|null $value a config string that can contain {$refs-to-other-config} * @param int $flags Options (see class constants) * @return string|int|null */ private function process($value, $flags) { $config = $this; if (!is_string($value)) { return $value; } return preg_replace_callback('#\{\$(.+)\}#', function ($match) use ($config, $flags) { return $config->get($match[1], $flags); }, $value); } /** * Turns relative paths in absolute paths without realpath() * * Since the dirs might not exist yet we can not call realpath or it will fail. * * @param string $path * @return string */ private function realpath($path) { if (preg_match('{^(?:/|[a-z]:|[a-z0-9.]+://)}i', $path)) { return $path; } return $this->baseDir . '/' . $path; } /** * Reads the value of a Composer environment variable * * This should be used to read COMPOSER_ environment variables * that overload config values. * * @param string $var * @return string|bool */ private function getComposerEnv($var) { if ($this->useEnvironment) { return getenv($var); } return false; } private function disableRepoByName($name) { if (isset($this->repositories[$name])) { unset($this->repositories[$name]); } elseif ($name === 'packagist') { // BC support for default "packagist" named repo unset($this->repositories['packagist.org']); } } /** * Validates that the passed URL is allowed to be used by current config, or throws an exception. * * @param string $url * @param IOInterface $io */ public function prohibitUrlByConfig($url, IOInterface $io = null) { // Return right away if the URL is malformed or custom (see issue #5173) if (false === filter_var($url, FILTER_VALIDATE_URL)) { return; } // Extract scheme and throw exception on known insecure protocols $scheme = parse_url($url, PHP_URL_SCHEME); if (in_array($scheme, array('http', 'git', 'ftp', 'svn'))) { if ($this->get('secure-http')) { throw new TransportException("Your configuration does not allow connections to $url. See https://getcomposer.org/doc/06-config.md#secure-http for details."); } elseif ($io) { $host = parse_url($url, PHP_URL_HOST); if (!isset($this->warnedHosts[$host])) { $io->writeError("Warning: Accessing $host over $scheme which is an insecure protocol."); } $this->warnedHosts[$host] = true; } } } } composer-1.6.3/src/Composer/Config/000077500000000000000000000000001323436022200171305ustar00rootroot00000000000000composer-1.6.3/src/Composer/Config/ConfigSourceInterface.php000066400000000000000000000036711323436022200240570ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Config; /** * Configuration Source Interface * * @author Jordi Boggiano * @author Beau Simensen */ interface ConfigSourceInterface { /** * Add a repository * * @param string $name Name * @param array $config Configuration */ public function addRepository($name, $config); /** * Remove a repository * * @param string $name */ public function removeRepository($name); /** * Add a config setting * * @param string $name Name * @param string $value Value */ public function addConfigSetting($name, $value); /** * Remove a config setting * * @param string $name */ public function removeConfigSetting($name); /** * Add a property * * @param string $name Name * @param string $value Value */ public function addProperty($name, $value); /** * Remove a property * * @param string $name */ public function removeProperty($name); /** * Add a package link * * @param string $type Type (require, require-dev, provide, suggest, replace, conflict) * @param string $name Name * @param string $value Value */ public function addLink($type, $name, $value); /** * Remove a package link * * @param string $type Type (require, require-dev, provide, suggest, replace, conflict) * @param string $name Name */ public function removeLink($type, $name); /** * Gives a user-friendly name to this source (file path or so) * * @return string */ public function getName(); } composer-1.6.3/src/Composer/Config/JsonConfigSource.php000066400000000000000000000177231323436022200230730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Config; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Util\Silencer; /** * JSON Configuration Source * * @author Jordi Boggiano * @author Beau Simensen */ class JsonConfigSource implements ConfigSourceInterface { /** * @var JsonFile */ private $file; /** * @var bool */ private $authConfig; /** * Constructor * * @param JsonFile $file * @param bool $authConfig */ public function __construct(JsonFile $file, $authConfig = false) { $this->file = $file; $this->authConfig = $authConfig; } /** * {@inheritdoc} */ public function getName() { return $this->file->getPath(); } /** * {@inheritdoc} */ public function addRepository($name, $config) { $this->manipulateJson('addRepository', $name, $config, function (&$config, $repo, $repoConfig) { // if converting from an array format to hashmap format, and there is a {"packagist.org":false} repo, we have // to convert it to "packagist.org": false key on the hashmap otherwise it fails schema validation if (isset($config['repositories'])) { foreach ($config['repositories'] as $index => $val) { if ($index === $repo) { continue; } if (is_numeric($index) && ($val === array('packagist' => false) || $val === array('packagist.org' => false))) { unset($config['repositories'][$index]); $config['repositories']['packagist.org'] = false; break; } } } $config['repositories'][$repo] = $repoConfig; }); } /** * {@inheritdoc} */ public function removeRepository($name) { $this->manipulateJson('removeRepository', $name, function (&$config, $repo) { unset($config['repositories'][$repo]); }); } /** * {@inheritdoc} */ public function addConfigSetting($name, $value) { $authConfig = $this->authConfig; $this->manipulateJson('addConfigSetting', $name, $value, function (&$config, $key, $val) use ($authConfig) { if (preg_match('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|platform)\.}', $key)) { list($key, $host) = explode('.', $key, 2); if ($authConfig) { $config[$key][$host] = $val; } else { $config['config'][$key][$host] = $val; } } else { $config['config'][$key] = $val; } }); } /** * {@inheritdoc} */ public function removeConfigSetting($name) { $authConfig = $this->authConfig; $this->manipulateJson('removeConfigSetting', $name, function (&$config, $key) use ($authConfig) { if (preg_match('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|platform)\.}', $key)) { list($key, $host) = explode('.', $key, 2); if ($authConfig) { unset($config[$key][$host]); } else { unset($config['config'][$key][$host]); } } else { unset($config['config'][$key]); } }); } /** * {@inheritdoc} */ public function addProperty($name, $value) { $this->manipulateJson('addProperty', $name, $value, function (&$config, $key, $val) { if (substr($key, 0, 6) === 'extra.') { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config['extra']; foreach ($bits as $bit) { if (!isset($arr[$bit])) { $arr[$bit] = array(); } $arr = &$arr[$bit]; } $arr[$last] = $val; } else { $config[$key] = $val; } }); } /** * {@inheritdoc} */ public function removeProperty($name) { $authConfig = $this->authConfig; $this->manipulateJson('removeProperty', $name, function (&$config, $key) { if (substr($key, 0, 6) === 'extra.') { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config['extra']; foreach ($bits as $bit) { if (!isset($arr[$bit])) { return; } $arr = &$arr[$bit]; } unset($arr[$last]); } else { unset($config[$key]); } }); } /** * {@inheritdoc} */ public function addLink($type, $name, $value) { $this->manipulateJson('addLink', $type, $name, $value, function (&$config, $type, $name, $value) { $config[$type][$name] = $value; }); } /** * {@inheritdoc} */ public function removeLink($type, $name) { $this->manipulateJson('removeSubNode', $type, $name, function (&$config, $type, $name) { unset($config[$type][$name]); }); } protected function manipulateJson($method, $args, $fallback) { $args = func_get_args(); // remove method & fallback array_shift($args); $fallback = array_pop($args); if ($this->file->exists()) { if (!is_writable($this->file->getPath())) { throw new \RuntimeException(sprintf('The file "%s" is not writable.', $this->file->getPath())); } if (!is_readable($this->file->getPath())) { throw new \RuntimeException(sprintf('The file "%s" is not readable.', $this->file->getPath())); } $contents = file_get_contents($this->file->getPath()); } elseif ($this->authConfig) { $contents = "{\n}\n"; } else { $contents = "{\n \"config\": {\n }\n}\n"; } $manipulator = new JsonManipulator($contents); $newFile = !$this->file->exists(); // override manipulator method for auth config files if ($this->authConfig && $method === 'addConfigSetting') { $method = 'addSubNode'; list($mainNode, $name) = explode('.', $args[0], 2); $args = array($mainNode, $name, $args[1]); } elseif ($this->authConfig && $method === 'removeConfigSetting') { $method = 'removeSubNode'; list($mainNode, $name) = explode('.', $args[0], 2); $args = array($mainNode, $name); } // try to update cleanly if (call_user_func_array(array($manipulator, $method), $args)) { file_put_contents($this->file->getPath(), $manipulator->getContents()); } else { // on failed clean update, call the fallback and rewrite the whole file $config = $this->file->read(); $this->arrayUnshiftRef($args, $config); call_user_func_array($fallback, $args); $this->file->write($config); } if ($newFile) { Silencer::call('chmod', $this->file->getPath(), 0600); } } /** * Prepend a reference to an element to the beginning of an array. * * @param array $array * @param mixed $value * @return array */ private function arrayUnshiftRef(&$array, &$value) { $return = array_unshift($array, ''); $array[0] = &$value; return $return; } } composer-1.6.3/src/Composer/Console/000077500000000000000000000000001323436022200173255ustar00rootroot00000000000000composer-1.6.3/src/Composer/Console/Application.php000066400000000000000000000453441323436022200223130ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Console; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\IO\IOInterface; use Composer\IO\ConsoleIO; use Composer\Json\JsonValidationException; use Composer\Util\ErrorHandler; use Composer\EventDispatcher\ScriptExecutionException; use Composer\Exception\NoSslException; /** * The console application that handles the commands * * @author Ryan Weaver * @author Jordi Boggiano * @author François Pluchino */ class Application extends BaseApplication { /** * @var Composer */ protected $composer; /** * @var IOInterface */ protected $io; private static $logo = ' ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/ '; private $hasPluginCommands = false; private $disablePluginsByDefault = false; public function __construct() { static $shutdownRegistered = false; if (function_exists('ini_set') && extension_loaded('xdebug')) { ini_set('xdebug.show_exception_trace', false); ini_set('xdebug.scream', false); } if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(Silencer::call('date_default_timezone_get')); } if (!$shutdownRegistered) { $shutdownRegistered = true; register_shutdown_function(function () { $lastError = error_get_last(); if ($lastError && $lastError['message'] && (strpos($lastError['message'], 'Allowed memory') !== false /*Zend PHP out of memory error*/ || strpos($lastError['message'], 'exceeded memory') !== false /*HHVM out of memory errors*/)) { echo "\n". 'Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.'; } }); } parent::__construct('Composer', Composer::VERSION); } /** * {@inheritDoc} */ public function run(InputInterface $input = null, OutputInterface $output = null) { if (null === $output) { $output = Factory::createOutput(); } return parent::run($input, $output); } /** * {@inheritDoc} */ public function doRun(InputInterface $input, OutputInterface $output) { $this->disablePluginsByDefault = $input->hasParameterOption('--no-plugins'); $io = $this->io = new ConsoleIO($input, $output, $this->getHelperSet()); ErrorHandler::register($io); // switch working dir if ($newWorkDir = $this->getNewWorkingDir($input)) { $oldWorkingDir = getcwd(); chdir($newWorkDir); $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG); } // determine command name to be executed without including plugin commands $commandName = ''; if ($name = $this->getCommandName($input)) { try { $commandName = $this->find($name)->getName(); } catch (\InvalidArgumentException $e) { } } // prompt user for dir change if no composer.json is present in current dir if ($io->isInteractive() && !$newWorkDir && !in_array($commandName, array('', 'list', 'init', 'about', 'help', 'diagnose', 'self-update', 'global', 'create-project'), true) && !file_exists(Factory::getComposerFile())) { $dir = dirname(getcwd()); $home = realpath(getenv('HOME') ?: getenv('USERPROFILE') ?: '/'); // abort when we reach the home dir or top of the filesystem while (dirname($dir) !== $dir && $dir !== $home) { if (file_exists($dir.'/'.Factory::getComposerFile())) { if ($io->askConfirmation('No composer.json in current directory, do you want to use the one at '.$dir.'? [Y,n]? ', true)) { $oldWorkingDir = getcwd(); chdir($dir); } break; } $dir = dirname($dir); } } if (!$this->disablePluginsByDefault && !$this->hasPluginCommands && 'global' !== $commandName) { try { foreach ($this->getPluginCommands() as $command) { if ($this->has($command->getName())) { $io->writeError('Plugin command '.$command->getName().' ('.get_class($command).') would override a Composer command and has been skipped'); } else { $this->add($command); } } } catch (NoSslException $e) { // suppress these as they are not relevant at this point } $this->hasPluginCommands = true; } // determine command name to be executed incl plugin commands, and check if it's a proxy command $isProxyCommand = false; if ($name = $this->getCommandName($input)) { try { $command = $this->find($name); $commandName = $command->getName(); $isProxyCommand = ($command instanceof Command\BaseCommand && $command->isProxyCommand()); } catch (\InvalidArgumentException $e) { } } if (!$isProxyCommand) { $io->writeError(sprintf( 'Running %s (%s) with %s on %s', Composer::VERSION, Composer::RELEASE_DATE, defined('HHVM_VERSION') ? 'HHVM '.HHVM_VERSION : 'PHP '.PHP_VERSION, function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknown OS' ), true, IOInterface::DEBUG); if (PHP_VERSION_ID < 50302) { $io->writeError('Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.', upgrading is strongly recommended.'); } if (extension_loaded('xdebug') && !getenv('COMPOSER_DISABLE_XDEBUG_WARN')) { $io->writeError('You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug'); } if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) { $io->writeError(sprintf('Warning: This development build of composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.', $_SERVER['PHP_SELF'])); } if (getenv('COMPOSER_NO_INTERACTION')) { $input->setInteractive(false); } if (!Platform::isWindows() && function_exists('exec') && !getenv('COMPOSER_ALLOW_SUPERUSER')) { if (function_exists('posix_getuid') && posix_getuid() === 0) { if ($commandName !== 'self-update' && $commandName !== 'selfupdate') { $io->writeError('Do not run Composer as root/super user! See https://getcomposer.org/root for details'); } if ($uid = (int) getenv('SUDO_UID')) { // Silently clobber any sudo credentials on the invoking user to avoid privilege escalations later on // ref. https://github.com/composer/composer/issues/5119 Silencer::call('exec', "sudo -u \\#{$uid} sudo -K > /dev/null 2>&1"); } } // Silently clobber any remaining sudo leases on the current user as well to avoid privilege escalations Silencer::call('exec', 'sudo -K > /dev/null 2>&1'); } // Check system temp folder for usability as it can cause weird runtime issues otherwise Silencer::call(function () use ($io) { $tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime()); if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) { $io->writeError(sprintf('PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini', sys_get_temp_dir())); } }); // add non-standard scripts as own commands $file = Factory::getComposerFile(); if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) { if (isset($composer['scripts']) && is_array($composer['scripts'])) { foreach ($composer['scripts'] as $script => $dummy) { if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) { if ($this->has($script)) { $io->writeError('A script named '.$script.' would override a Composer command and has been skipped'); } else { $description = null; if (isset($composer['scripts-descriptions'][$script])) { $description = $composer['scripts-descriptions'][$script]; } $this->add(new Command\ScriptAliasCommand($script, $description)); } } } } } } try { if ($input->hasParameterOption('--profile')) { $startTime = microtime(true); $this->io->enableDebugging($startTime); } $result = parent::doRun($input, $output); if (isset($oldWorkingDir)) { chdir($oldWorkingDir); } if (isset($startTime)) { $io->writeError('Memory usage: '.round(memory_get_usage() / 1024 / 1024, 2).'MB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MB), time: '.round(microtime(true) - $startTime, 2).'s'); } restore_error_handler(); return $result; } catch (ScriptExecutionException $e) { return $e->getCode(); } catch (\Exception $e) { $this->hintCommonErrors($e); restore_error_handler(); throw $e; } } /** * @param InputInterface $input * @throws \RuntimeException * @return string */ private function getNewWorkingDir(InputInterface $input) { $workingDir = $input->getParameterOption(array('--working-dir', '-d')); if (false !== $workingDir && !is_dir($workingDir)) { throw new \RuntimeException('Invalid working directory specified, '.$workingDir.' does not exist.'); } return $workingDir; } /** * {@inheritDoc} */ private function hintCommonErrors($exception) { $io = $this->getIO(); Silencer::suppress(); try { $composer = $this->getComposer(false, true); if ($composer) { $config = $composer->getConfig(); $minSpaceFree = 1024 * 1024; if ((($df = disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree) || (($df = disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree) || (($df = disk_free_space($dir = sys_get_temp_dir())) !== false && $df < $minSpaceFree) ) { $io->writeError('The disk hosting '.$dir.' is full, this may be the cause of the following exception', true, IOInterface::QUIET); } } } catch (\Exception $e) { } Silencer::restore(); if (Platform::isWindows() && false !== strpos($exception->getMessage(), 'The system cannot find the path specified')) { $io->writeError('The following exception may be caused by a stale entry in your cmd.exe AutoRun', true, IOInterface::QUIET); $io->writeError('Check https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows- for details', true, IOInterface::QUIET); } if (false !== strpos($exception->getMessage(), 'fork failed - Cannot allocate memory')) { $io->writeError('The following exception is caused by a lack of memory or swap, or not having swap configured', true, IOInterface::QUIET); $io->writeError('Check https://getcomposer.org/doc/articles/troubleshooting.md#proc-open-fork-failed-errors for details', true, IOInterface::QUIET); } } /** * @param bool $required * @param bool|null $disablePlugins * @throws JsonValidationException * @return \Composer\Composer */ public function getComposer($required = true, $disablePlugins = null) { if (null === $disablePlugins) { $disablePlugins = $this->disablePluginsByDefault; } if (null === $this->composer) { try { $this->composer = Factory::create($this->io, null, $disablePlugins); } catch (\InvalidArgumentException $e) { if ($required) { $this->io->writeError($e->getMessage()); exit(1); } } catch (JsonValidationException $e) { $errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors()); $message = $e->getMessage() . ':' . PHP_EOL . $errors; throw new JsonValidationException($message); } } return $this->composer; } /** * Removes the cached composer instance */ public function resetComposer() { $this->composer = null; } /** * @return IOInterface */ public function getIO() { return $this->io; } public function getHelp() { return self::$logo . parent::getHelp(); } /** * Initializes all the composer commands. */ protected function getDefaultCommands() { $commands = array_merge(parent::getDefaultCommands(), array( new Command\AboutCommand(), new Command\ConfigCommand(), new Command\DependsCommand(), new Command\ProhibitsCommand(), new Command\InitCommand(), new Command\InstallCommand(), new Command\CreateProjectCommand(), new Command\UpdateCommand(), new Command\SearchCommand(), new Command\ValidateCommand(), new Command\ShowCommand(), new Command\SuggestsCommand(), new Command\RequireCommand(), new Command\DumpAutoloadCommand(), new Command\StatusCommand(), new Command\ArchiveCommand(), new Command\DiagnoseCommand(), new Command\RunScriptCommand(), new Command\LicensesCommand(), new Command\GlobalCommand(), new Command\ClearCacheCommand(), new Command\RemoveCommand(), new Command\HomeCommand(), new Command\ExecCommand(), new Command\OutdatedCommand(), new Command\CheckPlatformReqsCommand(), )); if ('phar:' === substr(__FILE__, 0, 5)) { $commands[] = new Command\SelfUpdateCommand(); } return $commands; } /** * {@inheritDoc} */ public function getLongVersion() { if (Composer::BRANCH_ALIAS_VERSION) { return sprintf( '%s version %s (%s) %s', $this->getName(), Composer::BRANCH_ALIAS_VERSION, $this->getVersion(), Composer::RELEASE_DATE ); } return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE; } /** * {@inheritDoc} */ protected function getDefaultInputDefinition() { $definition = parent::getDefaultInputDefinition(); $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information')); $definition->addOption(new InputOption('--no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.')); $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.')); return $definition; } private function getPluginCommands() { $commands = array(); $composer = $this->getComposer(false, false); if (null === $composer) { $composer = Factory::createGlobal($this->io, false); } if (null !== $composer) { $pm = $composer->getPluginManager(); foreach ($pm->getPluginCapabilities('Composer\Plugin\Capability\CommandProvider', array('composer' => $composer, 'io' => $this->io)) as $capability) { $newCommands = $capability->getCommands(); if (!is_array($newCommands)) { throw new \UnexpectedValueException('Plugin capability '.get_class($capability).' failed to return an array from getCommands'); } foreach ($newCommands as $command) { if (!$command instanceof Command\BaseCommand) { throw new \UnexpectedValueException('Plugin capability '.get_class($capability).' returned an invalid value, we expected an array of Composer\Command\BaseCommand objects'); } } $commands = array_merge($commands, $newCommands); } } return $commands; } } composer-1.6.3/src/Composer/Console/HtmlOutputFormatter.php000066400000000000000000000050011323436022200240430ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Console; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @author Jordi Boggiano */ class HtmlOutputFormatter extends OutputFormatter { private static $availableForegroundColors = array( 30 => 'black', 31 => 'red', 32 => 'green', 33 => 'yellow', 34 => 'blue', 35 => 'magenta', 36 => 'cyan', 37 => 'white', ); private static $availableBackgroundColors = array( 40 => 'black', 41 => 'red', 42 => 'green', 43 => 'yellow', 44 => 'blue', 45 => 'magenta', 46 => 'cyan', 47 => 'white', ); private static $availableOptions = array( 1 => 'bold', 4 => 'underscore', //5 => 'blink', //7 => 'reverse', //8 => 'conceal' ); /** * @param array $styles Array of "name => FormatterStyle" instances */ public function __construct(array $styles = array()) { parent::__construct(true, $styles); } public function format($message) { $formatted = parent::format($message); $clearEscapeCodes = '(?:39|49|0|22|24|25|27|28)'; return preg_replace_callback("{\033\[([0-9;]+)m(.*?)\033\[(?:".$clearEscapeCodes.";)*?".$clearEscapeCodes."m}s", array($this, 'formatHtml'), $formatted); } private function formatHtml($matches) { $out = ''.$matches[2].''; } } composer-1.6.3/src/Composer/DependencyResolver/000077500000000000000000000000001323436022200215235ustar00rootroot00000000000000composer-1.6.3/src/Composer/DependencyResolver/Decisions.php000066400000000000000000000121471323436022200241610ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * Stores decisions on installing, removing or keeping packages * * @author Nils Adermann */ class Decisions implements \Iterator, \Countable { const DECISION_LITERAL = 0; const DECISION_REASON = 1; protected $pool; protected $decisionMap; protected $decisionQueue = array(); public function __construct($pool) { $this->pool = $pool; $this->decisionMap = array(); } public function decide($literal, $level, $why) { $this->addDecision($literal, $level); $this->decisionQueue[] = array( self::DECISION_LITERAL => $literal, self::DECISION_REASON => $why, ); } public function satisfy($literal) { $packageId = abs($literal); return ( $literal > 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 || $literal < 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0 ); } public function conflict($literal) { $packageId = abs($literal); return ( (isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 && $literal < 0) || (isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0 && $literal > 0) ); } public function decided($literalOrPackageId) { return !empty($this->decisionMap[abs($literalOrPackageId)]); } public function undecided($literalOrPackageId) { return empty($this->decisionMap[abs($literalOrPackageId)]); } public function decidedInstall($literalOrPackageId) { $packageId = abs($literalOrPackageId); return isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0; } public function decisionLevel($literalOrPackageId) { $packageId = abs($literalOrPackageId); if (isset($this->decisionMap[$packageId])) { return abs($this->decisionMap[$packageId]); } return 0; } public function decisionRule($literalOrPackageId) { $packageId = abs($literalOrPackageId); foreach ($this->decisionQueue as $i => $decision) { if ($packageId === abs($decision[self::DECISION_LITERAL])) { return $decision[self::DECISION_REASON]; } } return null; } public function atOffset($queueOffset) { return $this->decisionQueue[$queueOffset]; } public function validOffset($queueOffset) { return $queueOffset >= 0 && $queueOffset < count($this->decisionQueue); } public function lastReason() { return $this->decisionQueue[count($this->decisionQueue) - 1][self::DECISION_REASON]; } public function lastLiteral() { return $this->decisionQueue[count($this->decisionQueue) - 1][self::DECISION_LITERAL]; } public function reset() { while ($decision = array_pop($this->decisionQueue)) { $this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0; } } public function resetToOffset($offset) { while (count($this->decisionQueue) > $offset + 1) { $decision = array_pop($this->decisionQueue); $this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0; } } public function revertLast() { $this->decisionMap[abs($this->lastLiteral())] = 0; array_pop($this->decisionQueue); } public function count() { return count($this->decisionQueue); } public function rewind() { end($this->decisionQueue); } public function current() { return current($this->decisionQueue); } public function key() { return key($this->decisionQueue); } public function next() { return prev($this->decisionQueue); } public function valid() { return false !== current($this->decisionQueue); } public function isEmpty() { return count($this->decisionQueue) === 0; } protected function addDecision($literal, $level) { $packageId = abs($literal); $previousDecision = isset($this->decisionMap[$packageId]) ? $this->decisionMap[$packageId] : null; if ($previousDecision != 0) { $literalString = $this->pool->literalToString($literal); $package = $this->pool->literalToPackage($literal); throw new SolverBugException( "Trying to decide $literalString on level $level, even though $package was previously decided as ".(int) $previousDecision."." ); } if ($literal > 0) { $this->decisionMap[$packageId] = $level; } else { $this->decisionMap[$packageId] = -$level; } } } composer-1.6.3/src/Composer/DependencyResolver/DefaultPolicy.php000066400000000000000000000221711323436022200250030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Package\BasePackage; use Composer\Semver\Constraint\Constraint; /** * @author Nils Adermann * @author Jordi Boggiano */ class DefaultPolicy implements PolicyInterface { private $preferStable; private $preferLowest; public function __construct($preferStable = false, $preferLowest = false) { $this->preferStable = $preferStable; $this->preferLowest = $preferLowest; } public function versionCompare(PackageInterface $a, PackageInterface $b, $operator) { if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) { return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB]; } $constraint = new Constraint($operator, $b->getVersion()); $version = new Constraint('==', $a->getVersion()); return $constraint->matchSpecific($version, true); } public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package, $mustMatchName = false) { $packages = array(); foreach ($pool->whatProvides($package->getName(), null, $mustMatchName) as $candidate) { if ($candidate !== $package) { $packages[] = $candidate; } } return $packages; } public function getPriority(Pool $pool, PackageInterface $package) { return $pool->getPriority($package->getRepository()); } public function selectPreferredPackages(Pool $pool, array $installedMap, array $literals, $requiredPackage = null) { $packages = $this->groupLiteralsByNamePreferInstalled($pool, $installedMap, $literals); foreach ($packages as &$literals) { $policy = $this; usort($literals, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) { return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true); }); } foreach ($packages as &$literals) { $literals = $this->pruneToHighestPriorityOrInstalled($pool, $installedMap, $literals); $literals = $this->pruneToBestVersion($pool, $literals); $literals = $this->pruneRemoteAliases($pool, $literals); } $selected = call_user_func_array('array_merge', $packages); // now sort the result across all packages to respect replaces across packages usort($selected, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) { return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage); }); return $selected; } protected function groupLiteralsByNamePreferInstalled(Pool $pool, array $installedMap, $literals) { $packages = array(); foreach ($literals as $literal) { $packageName = $pool->literalToPackage($literal)->getName(); if (!isset($packages[$packageName])) { $packages[$packageName] = array(); } if (isset($installedMap[abs($literal)])) { array_unshift($packages[$packageName], $literal); } else { $packages[$packageName][] = $literal; } } return $packages; } /** * @protected */ public function compareByPriorityPreferInstalled(Pool $pool, array $installedMap, PackageInterface $a, PackageInterface $b, $requiredPackage = null, $ignoreReplace = false) { if ($a->getRepository() === $b->getRepository()) { // prefer aliases to the original package if ($a->getName() === $b->getName()) { $aAliased = $a instanceof AliasPackage; $bAliased = $b instanceof AliasPackage; if ($aAliased && !$bAliased) { return -1; // use a } if (!$aAliased && $bAliased) { return 1; // use b } } if (!$ignoreReplace) { // return original, not replaced if ($this->replaces($a, $b)) { return 1; // use b } if ($this->replaces($b, $a)) { return -1; // use a } // for replacers not replacing each other, put a higher prio on replacing // packages with the same vendor as the required package if ($requiredPackage && false !== ($pos = strpos($requiredPackage, '/'))) { $requiredVendor = substr($requiredPackage, 0, $pos); $aIsSameVendor = substr($a->getName(), 0, $pos) === $requiredVendor; $bIsSameVendor = substr($b->getName(), 0, $pos) === $requiredVendor; if ($bIsSameVendor !== $aIsSameVendor) { return $aIsSameVendor ? -1 : 1; } } } // priority equal, sort by package id to make reproducible if ($a->id === $b->id) { return 0; } return ($a->id < $b->id) ? -1 : 1; } if (isset($installedMap[$a->id])) { return -1; } if (isset($installedMap[$b->id])) { return 1; } return ($this->getPriority($pool, $a) > $this->getPriority($pool, $b)) ? -1 : 1; } /** * Checks if source replaces a package with the same name as target. * * Replace constraints are ignored. This method should only be used for * prioritisation, not for actual constraint verification. * * @param PackageInterface $source * @param PackageInterface $target * @return bool */ protected function replaces(PackageInterface $source, PackageInterface $target) { foreach ($source->getReplaces() as $link) { if ($link->getTarget() === $target->getName() // && (null === $link->getConstraint() || // $link->getConstraint()->matches(new Constraint('==', $target->getVersion())))) { ) { return true; } } return false; } protected function pruneToBestVersion(Pool $pool, $literals) { $operator = $this->preferLowest ? '<' : '>'; $bestLiterals = array($literals[0]); $bestPackage = $pool->literalToPackage($literals[0]); foreach ($literals as $i => $literal) { if (0 === $i) { continue; } $package = $pool->literalToPackage($literal); if ($this->versionCompare($package, $bestPackage, $operator)) { $bestPackage = $package; $bestLiterals = array($literal); } elseif ($this->versionCompare($package, $bestPackage, '==')) { $bestLiterals[] = $literal; } } return $bestLiterals; } /** * Assumes that installed packages come first and then all highest priority packages */ protected function pruneToHighestPriorityOrInstalled(Pool $pool, array $installedMap, array $literals) { $selected = array(); $priority = null; foreach ($literals as $literal) { $package = $pool->literalToPackage($literal); if (isset($installedMap[$package->id])) { $selected[] = $literal; continue; } if (null === $priority) { $priority = $this->getPriority($pool, $package); } if ($this->getPriority($pool, $package) != $priority) { break; } $selected[] = $literal; } return $selected; } /** * Assumes that locally aliased (in root package requires) packages take priority over branch-alias ones * * If no package is a local alias, nothing happens */ protected function pruneRemoteAliases(Pool $pool, array $literals) { $hasLocalAlias = false; foreach ($literals as $literal) { $package = $pool->literalToPackage($literal); if ($package instanceof AliasPackage && $package->isRootPackageAlias()) { $hasLocalAlias = true; break; } } if (!$hasLocalAlias) { return $literals; } $selected = array(); foreach ($literals as $literal) { $package = $pool->literalToPackage($literal); if ($package instanceof AliasPackage && $package->isRootPackageAlias()) { $selected[] = $literal; } } return $selected; } } composer-1.6.3/src/Composer/DependencyResolver/GenericRule.php000066400000000000000000000041741323436022200244460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\PackageInterface; use Composer\Package\Link; /** * @author Nils Adermann */ class GenericRule extends Rule { protected $literals; /** * @param array $literals * @param int $reason A RULE_* constant describing the reason for generating this rule * @param Link|PackageInterface $reasonData * @param array $job The job this rule was created from */ public function __construct(array $literals, $reason, $reasonData, $job = null) { parent::__construct($reason, $reasonData, $job); // sort all packages ascending by id sort($literals); $this->literals = $literals; } public function getLiterals() { return $this->literals; } public function getHash() { $data = unpack('ihash', md5(implode(',', $this->literals), true)); return $data['hash']; } /** * Checks if this rule is equal to another one * * Ignores whether either of the rules is disabled. * * @param Rule $rule The rule to check against * @return bool Whether the rules are equal */ public function equals(Rule $rule) { return $this->literals === $rule->getLiterals(); } public function isAssertion() { return 1 === count($this->literals); } /** * Formats a rule as a string of the format (Literal1|Literal2|...) * * @return string */ public function __toString() { $result = ($this->isDisabled()) ? 'disabled(' : '('; foreach ($this->literals as $i => $literal) { if ($i != 0) { $result .= '|'; } $result .= $literal; } $result .= ')'; return $result; } } composer-1.6.3/src/Composer/DependencyResolver/Operation/000077500000000000000000000000001323436022200234635ustar00rootroot00000000000000composer-1.6.3/src/Composer/DependencyResolver/Operation/InstallOperation.php000066400000000000000000000025131323436022200274640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\PackageInterface; /** * Solver install operation. * * @author Konstantin Kudryashov */ class InstallOperation extends SolverOperation { protected $package; /** * Initializes operation. * * @param PackageInterface $package package instance * @param string $reason operation reason */ public function __construct(PackageInterface $package, $reason = null) { parent::__construct($reason); $this->package = $package; } /** * Returns package instance. * * @return PackageInterface */ public function getPackage() { return $this->package; } /** * Returns job type. * * @return string */ public function getJobType() { return 'install'; } /** * {@inheritDoc} */ public function __toString() { return 'Installing '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).')'; } } composer-1.6.3/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php000066400000000000000000000027611323436022200315670ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; /** * Solver install operation. * * @author Nils Adermann */ class MarkAliasInstalledOperation extends SolverOperation { protected $package; /** * Initializes operation. * * @param AliasPackage $package package instance * @param string $reason operation reason */ public function __construct(AliasPackage $package, $reason = null) { parent::__construct($reason); $this->package = $package; } /** * Returns package instance. * * @return PackageInterface */ public function getPackage() { return $this->package; } /** * Returns job type. * * @return string */ public function getJobType() { return 'markAliasInstalled'; } /** * {@inheritDoc} */ public function __toString() { return 'Marking '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).') as installed, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->formatVersion($this->package->getAliasOf()).')'; } } composer-1.6.3/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php000066400000000000000000000027671323436022200321400ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; /** * Solver install operation. * * @author Nils Adermann */ class MarkAliasUninstalledOperation extends SolverOperation { protected $package; /** * Initializes operation. * * @param AliasPackage $package package instance * @param string $reason operation reason */ public function __construct(AliasPackage $package, $reason = null) { parent::__construct($reason); $this->package = $package; } /** * Returns package instance. * * @return PackageInterface */ public function getPackage() { return $this->package; } /** * Returns job type. * * @return string */ public function getJobType() { return 'markAliasUninstalled'; } /** * {@inheritDoc} */ public function __toString() { return 'Marking '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).') as uninstalled, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->formatVersion($this->package->getAliasOf()).')'; } } composer-1.6.3/src/Composer/DependencyResolver/Operation/OperationInterface.php000066400000000000000000000014431323436022200277570ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; /** * Solver operation interface. * * @author Konstantin Kudryashov */ interface OperationInterface { /** * Returns job type. * * @return string */ public function getJobType(); /** * Returns operation reason. * * @return string */ public function getReason(); /** * Serializes the operation in a human readable format * * @return string */ public function __toString(); } composer-1.6.3/src/Composer/DependencyResolver/Operation/SolverOperation.php000066400000000000000000000017741323436022200273400ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\PackageInterface; /** * Abstract solver operation class. * * @author Konstantin Kudryashov */ abstract class SolverOperation implements OperationInterface { protected $reason; /** * Initializes operation. * * @param string $reason operation reason */ public function __construct($reason = null) { $this->reason = $reason; } /** * Returns operation reason. * * @return string */ public function getReason() { return $this->reason; } protected function formatVersion(PackageInterface $package) { return $package->getFullPrettyVersion(); } } composer-1.6.3/src/Composer/DependencyResolver/Operation/UninstallOperation.php000066400000000000000000000025231323436022200300300ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\PackageInterface; /** * Solver uninstall operation. * * @author Konstantin Kudryashov */ class UninstallOperation extends SolverOperation { protected $package; /** * Initializes operation. * * @param PackageInterface $package package instance * @param string $reason operation reason */ public function __construct(PackageInterface $package, $reason = null) { parent::__construct($reason); $this->package = $package; } /** * Returns package instance. * * @return PackageInterface */ public function getPackage() { return $this->package; } /** * Returns job type. * * @return string */ public function getJobType() { return 'uninstall'; } /** * {@inheritDoc} */ public function __toString() { return 'Uninstalling '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).')'; } } composer-1.6.3/src/Composer/DependencyResolver/Operation/UpdateOperation.php000066400000000000000000000034561323436022200273070ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\PackageInterface; /** * Solver update operation. * * @author Konstantin Kudryashov */ class UpdateOperation extends SolverOperation { protected $initialPackage; protected $targetPackage; /** * Initializes update operation. * * @param PackageInterface $initial initial package * @param PackageInterface $target target package (updated) * @param string $reason update reason */ public function __construct(PackageInterface $initial, PackageInterface $target, $reason = null) { parent::__construct($reason); $this->initialPackage = $initial; $this->targetPackage = $target; } /** * Returns initial package. * * @return PackageInterface */ public function getInitialPackage() { return $this->initialPackage; } /** * Returns target package. * * @return PackageInterface */ public function getTargetPackage() { return $this->targetPackage; } /** * Returns job type. * * @return string */ public function getJobType() { return 'update'; } /** * {@inheritDoc} */ public function __toString() { return 'Updating '.$this->initialPackage->getPrettyName().' ('.$this->formatVersion($this->initialPackage).') to '. $this->targetPackage->getPrettyName(). ' ('.$this->formatVersion($this->targetPackage).')'; } } composer-1.6.3/src/Composer/DependencyResolver/PolicyInterface.php000066400000000000000000000013521323436022200253150ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\PackageInterface; /** * @author Nils Adermann */ interface PolicyInterface { public function versionCompare(PackageInterface $a, PackageInterface $b, $operator); public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package); public function selectPreferredPackages(Pool $pool, array $installedMap, array $literals, $requiredPackage = null); } composer-1.6.3/src/Composer/DependencyResolver/Pool.php000066400000000000000000000336101323436022200231500ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\BasePackage; use Composer\Package\AliasPackage; use Composer\Package\Version\VersionParser; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\Constraint; use Composer\Semver\Constraint\EmptyConstraint; use Composer\Repository\RepositoryInterface; use Composer\Repository\CompositeRepository; use Composer\Repository\ComposerRepository; use Composer\Repository\InstalledRepositoryInterface; use Composer\Repository\PlatformRepository; use Composer\Package\PackageInterface; /** * A package pool contains repositories that provide packages. * * @author Nils Adermann * @author Jordi Boggiano */ class Pool implements \Countable { const MATCH_NAME = -1; const MATCH_NONE = 0; const MATCH = 1; const MATCH_PROVIDE = 2; const MATCH_REPLACE = 3; const MATCH_FILTERED = 4; protected $repositories = array(); protected $providerRepos = array(); protected $packages = array(); protected $packageByName = array(); protected $packageByExactName = array(); protected $acceptableStabilities; protected $stabilityFlags; protected $versionParser; protected $providerCache = array(); protected $filterRequires; protected $whitelist = null; protected $id = 1; public function __construct($minimumStability = 'stable', array $stabilityFlags = array(), array $filterRequires = array()) { $this->versionParser = new VersionParser; $this->acceptableStabilities = array(); foreach (BasePackage::$stabilities as $stability => $value) { if ($value <= BasePackage::$stabilities[$minimumStability]) { $this->acceptableStabilities[$stability] = $value; } } $this->stabilityFlags = $stabilityFlags; $this->filterRequires = $filterRequires; foreach ($filterRequires as $name => $constraint) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) { unset($this->filterRequires[$name]); } } } public function setWhitelist($whitelist) { $this->whitelist = $whitelist; $this->providerCache = array(); } /** * Adds a repository and its packages to this package pool * * @param RepositoryInterface $repo A package repository * @param array $rootAliases */ public function addRepository(RepositoryInterface $repo, $rootAliases = array()) { if ($repo instanceof CompositeRepository) { $repos = $repo->getRepositories(); } else { $repos = array($repo); } foreach ($repos as $repo) { $this->repositories[] = $repo; $exempt = $repo instanceof PlatformRepository || $repo instanceof InstalledRepositoryInterface; if ($repo instanceof ComposerRepository && $repo->hasProviders()) { $this->providerRepos[] = $repo; $repo->setRootAliases($rootAliases); $repo->resetPackageIds(); } else { foreach ($repo->getPackages() as $package) { $names = $package->getNames(); $stability = $package->getStability(); if ($exempt || $this->isPackageAcceptable($names, $stability)) { $package->setId($this->id++); $this->packages[] = $package; $this->packageByExactName[$package->getName()][$package->id] = $package; foreach ($names as $provided) { $this->packageByName[$provided][] = $package; } // handle root package aliases $name = $package->getName(); if (isset($rootAliases[$name][$package->getVersion()])) { $alias = $rootAliases[$name][$package->getVersion()]; if ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']); $aliasPackage->setRootPackageAlias(true); $aliasPackage->setId($this->id++); $package->getRepository()->addPackage($aliasPackage); $this->packages[] = $aliasPackage; $this->packageByExactName[$aliasPackage->getName()][$aliasPackage->id] = $aliasPackage; foreach ($aliasPackage->getNames() as $name) { $this->packageByName[$name][] = $aliasPackage; } } } } } } } public function getPriority(RepositoryInterface $repo) { $priority = array_search($repo, $this->repositories, true); if (false === $priority) { throw new \RuntimeException("Could not determine repository priority. The repository was not registered in the pool."); } return -$priority; } /** * Retrieves the package object for a given package id. * * @param int $id * @return PackageInterface */ public function packageById($id) { return $this->packages[$id - 1]; } /** * Returns how many packages have been loaded into the pool */ public function count() { return count($this->packages); } /** * Searches all packages providing the given package name and match the constraint * * @param string $name The package name to be searched for * @param ConstraintInterface $constraint A constraint that all returned * packages must match or null to return all * @param bool $mustMatchName Whether the name of returned packages * must match the given name * @param bool $bypassFilters If enabled, filterRequires and stability matching is ignored * @return PackageInterface[] A set of packages */ public function whatProvides($name, ConstraintInterface $constraint = null, $mustMatchName = false, $bypassFilters = false) { if ($bypassFilters) { return $this->computeWhatProvides($name, $constraint, $mustMatchName, true); } $key = ((int) $mustMatchName).$constraint; if (isset($this->providerCache[$name][$key])) { return $this->providerCache[$name][$key]; } return $this->providerCache[$name][$key] = $this->computeWhatProvides($name, $constraint, $mustMatchName, $bypassFilters); } /** * @see whatProvides */ private function computeWhatProvides($name, $constraint, $mustMatchName = false, $bypassFilters = false) { $candidates = array(); foreach ($this->providerRepos as $repo) { foreach ($repo->whatProvides($this, $name, $bypassFilters) as $candidate) { $candidates[] = $candidate; if ($candidate->id < 1) { $candidate->setId($this->id++); $this->packages[$this->id - 2] = $candidate; } } } if ($mustMatchName) { $candidates = array_filter($candidates, function ($candidate) use ($name) { return $candidate->getName() == $name; }); if (isset($this->packageByExactName[$name])) { $candidates = array_merge($candidates, $this->packageByExactName[$name]); } } elseif (isset($this->packageByName[$name])) { $candidates = array_merge($candidates, $this->packageByName[$name]); } $matches = $provideMatches = array(); $nameMatch = false; foreach ($candidates as $candidate) { $aliasOfCandidate = null; // alias packages are not white listed, make sure that the package // being aliased is white listed if ($candidate instanceof AliasPackage) { $aliasOfCandidate = $candidate->getAliasOf(); } if ($this->whitelist !== null && !$bypassFilters && ( (!($candidate instanceof AliasPackage) && !isset($this->whitelist[$candidate->id])) || ($candidate instanceof AliasPackage && !isset($this->whitelist[$aliasOfCandidate->id])) )) { continue; } switch ($this->match($candidate, $name, $constraint, $bypassFilters)) { case self::MATCH_NONE: break; case self::MATCH_NAME: $nameMatch = true; break; case self::MATCH: $nameMatch = true; $matches[] = $candidate; break; case self::MATCH_PROVIDE: $provideMatches[] = $candidate; break; case self::MATCH_REPLACE: $matches[] = $candidate; break; case self::MATCH_FILTERED: break; default: throw new \UnexpectedValueException('Unexpected match type'); } } // if a package with the required name exists, we ignore providers if ($nameMatch) { return $matches; } return array_merge($matches, $provideMatches); } public function literalToPackage($literal) { $packageId = abs($literal); return $this->packageById($packageId); } public function literalToPrettyString($literal, $installedMap) { $package = $this->literalToPackage($literal); if (isset($installedMap[$package->id])) { $prefix = ($literal > 0 ? 'keep' : 'remove'); } else { $prefix = ($literal > 0 ? 'install' : 'don\'t install'); } return $prefix.' '.$package->getPrettyString(); } public function isPackageAcceptable($name, $stability) { foreach ((array) $name as $n) { // allow if package matches the global stability requirement and has no exception if (!isset($this->stabilityFlags[$n]) && isset($this->acceptableStabilities[$stability])) { return true; } // allow if package matches the package-specific stability flag if (isset($this->stabilityFlags[$n]) && BasePackage::$stabilities[$stability] <= $this->stabilityFlags[$n]) { return true; } } return false; } /** * Checks if the package matches the given constraint directly or through * provided or replaced packages * * @param array|PackageInterface $candidate * @param string $name Name of the package to be matched * @param ConstraintInterface $constraint The constraint to verify * @return int One of the MATCH* constants of this class or 0 if there is no match */ private function match($candidate, $name, ConstraintInterface $constraint = null, $bypassFilters) { $candidateName = $candidate->getName(); $candidateVersion = $candidate->getVersion(); $isDev = $candidate->getStability() === 'dev'; $isAlias = $candidate instanceof AliasPackage; if (!$bypassFilters && !$isDev && !$isAlias && isset($this->filterRequires[$name])) { $requireFilter = $this->filterRequires[$name]; } else { $requireFilter = new EmptyConstraint; } if ($candidateName === $name) { $pkgConstraint = new Constraint('==', $candidateVersion); if ($constraint === null || $constraint->matches($pkgConstraint)) { return $requireFilter->matches($pkgConstraint) ? self::MATCH : self::MATCH_FILTERED; } return self::MATCH_NAME; } $provides = $candidate->getProvides(); $replaces = $candidate->getReplaces(); // aliases create multiple replaces/provides for one target so they can not use the shortcut below if (isset($replaces[0]) || isset($provides[0])) { foreach ($provides as $link) { if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) { return $requireFilter->matches($link->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED; } } foreach ($replaces as $link) { if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) { return $requireFilter->matches($link->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED; } } return self::MATCH_NONE; } if (isset($provides[$name]) && ($constraint === null || $constraint->matches($provides[$name]->getConstraint()))) { return $requireFilter->matches($provides[$name]->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED; } if (isset($replaces[$name]) && ($constraint === null || $constraint->matches($replaces[$name]->getConstraint()))) { return $requireFilter->matches($replaces[$name]->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED; } return self::MATCH_NONE; } } composer-1.6.3/src/Composer/DependencyResolver/Problem.php000066400000000000000000000227121323436022200236400ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\CompletePackageInterface; /** * Represents a problem detected while solving dependencies * * @author Nils Adermann */ class Problem { /** * A map containing the id of each rule part of this problem as a key * @var array */ protected $reasonSeen; /** * A set of reasons for the problem, each is a rule or a job and a rule * @var array */ protected $reasons = array(); protected $section = 0; protected $pool; public function __construct(Pool $pool) { $this->pool = $pool; } /** * Add a rule as a reason * * @param Rule $rule A rule which is a reason for this problem */ public function addRule(Rule $rule) { $this->addReason(spl_object_hash($rule), array( 'rule' => $rule, 'job' => $rule->getJob(), )); } /** * Retrieve all reasons for this problem * * @return array The problem's reasons */ public function getReasons() { return $this->reasons; } /** * A human readable textual representation of the problem's reasons * * @param array $installedMap A map of all installed packages * @return string */ public function getPrettyString(array $installedMap = array()) { $reasons = call_user_func_array('array_merge', array_reverse($this->reasons)); if (count($reasons) === 1) { reset($reasons); $reason = current($reasons); $rule = $reason['rule']; $job = $reason['job']; if (isset($job['constraint'])) { $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); } else { $packages = array(); } if ($job && $job['cmd'] === 'install' && empty($packages)) { // handle php/hhvm if ($job['packageName'] === 'php' || $job['packageName'] === 'php-64bit' || $job['packageName'] === 'hhvm') { $version = phpversion(); $available = $this->pool->whatProvides($job['packageName']); if (count($available)) { $firstAvailable = reset($available); $version = $firstAvailable->getPrettyVersion(); $extra = $firstAvailable->getExtra(); if ($firstAvailable instanceof CompletePackageInterface && isset($extra['config.platform']) && $extra['config.platform'] === true) { $version .= '; ' . $firstAvailable->getDescription(); } } $msg = "\n - This package requires ".$job['packageName'].$this->constraintToText($job['constraint']).' but '; if (defined('HHVM_VERSION')) { return $msg . 'your HHVM version does not satisfy that requirement.'; } if ($job['packageName'] === 'hhvm') { return $msg . 'you are running this with PHP and not HHVM.'; } return $msg . 'your PHP version ('. $version .') does not satisfy that requirement.'; } // handle php extensions if (0 === stripos($job['packageName'], 'ext-')) { if (false !== strpos($job['packageName'], ' ')) { return "\n - The requested PHP extension ".$job['packageName'].' should be required as '.str_replace(' ', '-', $job['packageName']).'.'; } $ext = substr($job['packageName'], 4); $error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system'; return "\n - The requested PHP extension ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error.'. Install or enable PHP\'s '.$ext.' extension.'; } // handle linked libs if (0 === stripos($job['packageName'], 'lib-')) { if (strtolower($job['packageName']) === 'lib-icu') { $error = extension_loaded('intl') ? 'has the wrong version installed, try upgrading the intl extension.' : 'is missing from your system, make sure the intl extension is loaded.'; return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error; } return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' has the wrong version installed or is missing from your system, make sure to load the extension providing it.'; } if (!preg_match('{^[A-Za-z0-9_./-]+$}', $job['packageName'])) { $illegalChars = preg_replace('{[A-Za-z0-9_./-]+}', '', $job['packageName']); return "\n - The requested package ".$job['packageName'].' could not be found, it looks like its name is invalid, "'.$illegalChars.'" is not allowed in package names.'; } if ($providers = $this->pool->whatProvides($job['packageName'], $job['constraint'], true, true)) { return "\n - The requested package ".$job['packageName'].$this->constraintToText($job['constraint']).' is satisfiable by '.$this->getPackageList($providers).' but these conflict with your requirements or minimum-stability.'; } if ($providers = $this->pool->whatProvides($job['packageName'], null, true, true)) { return "\n - The requested package ".$job['packageName'].$this->constraintToText($job['constraint']).' exists as '.$this->getPackageList($providers).' but these are rejected by your constraint.'; } return "\n - The requested package ".$job['packageName'].' could not be found in any version, there may be a typo in the package name.'; } } $messages = array(); foreach ($reasons as $reason) { $rule = $reason['rule']; $job = $reason['job']; if ($job) { $messages[] = $this->jobToText($job); } elseif ($rule) { if ($rule instanceof Rule) { $messages[] = $rule->getPrettyString($this->pool, $installedMap); } } } return "\n - ".implode("\n - ", $messages); } /** * Store a reason descriptor but ignore duplicates * * @param string $id A canonical identifier for the reason * @param string $reason The reason descriptor */ protected function addReason($id, $reason) { if (!isset($this->reasonSeen[$id])) { $this->reasonSeen[$id] = true; $this->reasons[$this->section][] = $reason; } } public function nextSection() { $this->section++; } /** * Turns a job into a human readable description * * @param array $job * @return string */ protected function jobToText($job) { switch ($job['cmd']) { case 'install': $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); if (!$packages) { return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']); } return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.'; case 'update': return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.'; case 'remove': return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).''; } if (isset($job['constraint'])) { $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); } else { $packages = array(); } return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])'; } protected function getPackageList($packages) { $prepared = array(); foreach ($packages as $package) { $prepared[$package->getName()]['name'] = $package->getPrettyName(); $prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion(); } foreach ($prepared as $name => $package) { $prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']'; } return implode(', ', $prepared); } /** * Turns a constraint into text usable in a sentence describing a job * * @param \Composer\Semver\Constraint\ConstraintInterface $constraint * @return string */ protected function constraintToText($constraint) { return ($constraint) ? ' '.$constraint->getPrettyString() : ''; } } composer-1.6.3/src/Composer/DependencyResolver/Request.php000066400000000000000000000036411323436022200236700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Semver\Constraint\ConstraintInterface; /** * @author Nils Adermann */ class Request { protected $jobs; public function __construct() { $this->jobs = array(); } public function install($packageName, ConstraintInterface $constraint = null) { $this->addJob($packageName, 'install', $constraint); } public function update($packageName, ConstraintInterface $constraint = null) { $this->addJob($packageName, 'update', $constraint); } public function remove($packageName, ConstraintInterface $constraint = null) { $this->addJob($packageName, 'remove', $constraint); } /** * Mark an existing package as being installed and having to remain installed * * These jobs will not be tempered with by the solver * * @param string $packageName * @param ConstraintInterface|null $constraint */ public function fix($packageName, ConstraintInterface $constraint = null) { $this->addJob($packageName, 'install', $constraint, true); } protected function addJob($packageName, $cmd, ConstraintInterface $constraint = null, $fixed = false) { $packageName = strtolower($packageName); $this->jobs[] = array( 'cmd' => $cmd, 'packageName' => $packageName, 'constraint' => $constraint, 'fixed' => $fixed, ); } public function updateAll() { $this->jobs[] = array('cmd' => 'update-all'); } public function getJobs() { return $this->jobs; } } composer-1.6.3/src/Composer/DependencyResolver/Rule.php000066400000000000000000000217641323436022200231550ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\CompletePackage; use Composer\Package\Link; use Composer\Package\PackageInterface; /** * @author Nils Adermann * @author Ruben Gonzalez */ abstract class Rule { // reason constants const RULE_INTERNAL_ALLOW_UPDATE = 1; const RULE_JOB_INSTALL = 2; const RULE_JOB_REMOVE = 3; const RULE_PACKAGE_CONFLICT = 6; const RULE_PACKAGE_REQUIRES = 7; const RULE_PACKAGE_OBSOLETES = 8; const RULE_INSTALLED_PACKAGE_OBSOLETES = 9; const RULE_PACKAGE_SAME_NAME = 10; const RULE_PACKAGE_IMPLICIT_OBSOLETES = 11; const RULE_LEARNED = 12; const RULE_PACKAGE_ALIAS = 13; // bitfield defs const BITFIELD_TYPE = 0; const BITFIELD_REASON = 8; const BITFIELD_DISABLED = 16; protected $bitfield; protected $reasonData; /** * @param int $reason A RULE_* constant describing the reason for generating this rule * @param Link|PackageInterface $reasonData * @param array $job The job this rule was created from */ public function __construct($reason, $reasonData, $job = null) { $this->reasonData = $reasonData; if ($job) { $this->job = $job; } $this->bitfield = (0 << self::BITFIELD_DISABLED) | ($reason << self::BITFIELD_REASON) | (255 << self::BITFIELD_TYPE); } abstract public function getLiterals(); abstract public function getHash(); public function getJob() { return isset($this->job) ? $this->job : null; } abstract public function equals(Rule $rule); public function getReason() { return ($this->bitfield & (255 << self::BITFIELD_REASON)) >> self::BITFIELD_REASON; } public function getReasonData() { return $this->reasonData; } public function getRequiredPackage() { if ($this->getReason() === self::RULE_JOB_INSTALL) { return $this->reasonData; } if ($this->getReason() === self::RULE_PACKAGE_REQUIRES) { return $this->reasonData->getTarget(); } } public function setType($type) { $this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_TYPE)) | ((255 & $type) << self::BITFIELD_TYPE); } public function getType() { return ($this->bitfield & (255 << self::BITFIELD_TYPE)) >> self::BITFIELD_TYPE; } public function disable() { $this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_DISABLED)) | (1 << self::BITFIELD_DISABLED); } public function enable() { $this->bitfield = $this->bitfield & ~(255 << self::BITFIELD_DISABLED); } public function isDisabled() { return (bool) (($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED); } public function isEnabled() { return !(($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED); } abstract public function isAssertion(); public function getPrettyString(Pool $pool, array $installedMap = array()) { $literals = $this->getLiterals(); $ruleText = ''; foreach ($literals as $i => $literal) { if ($i != 0) { $ruleText .= '|'; } $ruleText .= $pool->literalToPrettyString($literal, $installedMap); } switch ($this->getReason()) { case self::RULE_INTERNAL_ALLOW_UPDATE: return $ruleText; case self::RULE_JOB_INSTALL: return "Install command rule ($ruleText)"; case self::RULE_JOB_REMOVE: return "Remove command rule ($ruleText)"; case self::RULE_PACKAGE_CONFLICT: $package1 = $pool->literalToPackage($literals[0]); $package2 = $pool->literalToPackage($literals[1]); return $package1->getPrettyString().' conflicts with '.$this->formatPackagesUnique($pool, array($package2)).'.'; case self::RULE_PACKAGE_REQUIRES: $sourceLiteral = array_shift($literals); $sourcePackage = $pool->literalToPackage($sourceLiteral); $requires = array(); foreach ($literals as $literal) { $requires[] = $pool->literalToPackage($literal); } $text = $this->reasonData->getPrettyString($sourcePackage); if ($requires) { $text .= ' -> satisfiable by ' . $this->formatPackagesUnique($pool, $requires) . '.'; } else { $targetName = $this->reasonData->getTarget(); if ($targetName === 'php' || $targetName === 'php-64bit' || $targetName === 'hhvm') { // handle php/hhvm if (defined('HHVM_VERSION')) { return $text . ' -> your HHVM version does not satisfy that requirement.'; } if ($targetName === 'hhvm') { return $text . ' -> you are running this with PHP and not HHVM.'; } $packages = $pool->whatProvides($targetName); $package = count($packages) ? current($packages) : phpversion(); if (!($package instanceof CompletePackage)) { return $text . ' -> your PHP version ('.phpversion().') does not satisfy that requirement.'; } $extra = $package->getExtra(); if (!empty($extra['config.platform'])) { $text .= ' -> your PHP version ('.phpversion().') overridden by "config.platform.php" version ('.$package->getPrettyVersion().') does not satisfy that requirement.'; } else { $text .= ' -> your PHP version ('.$package->getPrettyVersion().') does not satisfy that requirement.'; } return $text; } if (0 === strpos($targetName, 'ext-')) { // handle php extensions $ext = substr($targetName, 4); $error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system'; return $text . ' -> the requested PHP extension '.$ext.' '.$error.'.'; } if (0 === strpos($targetName, 'lib-')) { // handle linked libs $lib = substr($targetName, 4); return $text . ' -> the requested linked library '.$lib.' has the wrong version installed or is missing from your system, make sure to have the extension providing it.'; } if ($providers = $pool->whatProvides($targetName, $this->reasonData->getConstraint(), true, true)) { return $text . ' -> satisfiable by ' . $this->formatPackagesUnique($pool, $providers) .' but these conflict with your requirements or minimum-stability.'; } return $text . ' -> no matching package found.'; } return $text; case self::RULE_PACKAGE_OBSOLETES: return $ruleText; case self::RULE_INSTALLED_PACKAGE_OBSOLETES: return $ruleText; case self::RULE_PACKAGE_SAME_NAME: return 'Can only install one of: ' . $this->formatPackagesUnique($pool, $literals) . '.'; case self::RULE_PACKAGE_IMPLICIT_OBSOLETES: return $ruleText; case self::RULE_LEARNED: return 'Conclusion: '.$ruleText; case self::RULE_PACKAGE_ALIAS: return $ruleText; default: return '('.$ruleText.')'; } } /** * @param Pool $pool * @param array $packages * * @return string */ protected function formatPackagesUnique($pool, array $packages) { $prepared = array(); foreach ($packages as $package) { if (!is_object($package)) { $package = $pool->literalToPackage($package); } $prepared[$package->getName()]['name'] = $package->getPrettyName(); $prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion(); } foreach ($prepared as $name => $package) { $prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']'; } return implode(', ', $prepared); } } composer-1.6.3/src/Composer/DependencyResolver/Rule2Literals.php000066400000000000000000000047021323436022200247300ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\PackageInterface; use Composer\Package\Link; /** * @author Nils Adermann */ class Rule2Literals extends Rule { protected $literal1; protected $literal2; /** * @param int $literal1 * @param int $literal2 * @param int $reason A RULE_* constant describing the reason for generating this rule * @param Link|PackageInterface $reasonData * @param array $job The job this rule was created from */ public function __construct($literal1, $literal2, $reason, $reasonData, $job = null) { parent::__construct($reason, $reasonData, $job); if ($literal1 < $literal2) { $this->literal1 = $literal1; $this->literal2 = $literal2; } else { $this->literal1 = $literal2; $this->literal2 = $literal1; } } public function getLiterals() { return array($this->literal1, $this->literal2); } public function getHash() { $data = unpack('ihash', md5($this->literal1.','.$this->literal2, true)); return $data['hash']; } /** * Checks if this rule is equal to another one * * Ignores whether either of the rules is disabled. * * @param Rule $rule The rule to check against * @return bool Whether the rules are equal */ public function equals(Rule $rule) { $literals = $rule->getLiterals(); if (2 != count($literals)) { return false; } if ($this->literal1 !== $literals[0]) { return false; } if ($this->literal2 !== $literals[1]) { return false; } return true; } public function isAssertion() { return false; } /** * Formats a rule as a string of the format (Literal1|Literal2|...) * * @return string */ public function __toString() { $result = ($this->isDisabled()) ? 'disabled(' : '('; $result .= $this->literal1 . '|' . $this->literal2 . ')'; return $result; } } composer-1.6.3/src/Composer/DependencyResolver/RuleSet.php000066400000000000000000000100741323436022200236210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * @author Nils Adermann */ class RuleSet implements \IteratorAggregate, \Countable { // highest priority => lowest number const TYPE_PACKAGE = 0; const TYPE_JOB = 1; const TYPE_LEARNED = 4; /** * READ-ONLY: Lookup table for rule id to rule object * * @var Rule[] */ public $ruleById; protected static $types = array( 255 => 'UNKNOWN', self::TYPE_PACKAGE => 'PACKAGE', self::TYPE_JOB => 'JOB', self::TYPE_LEARNED => 'LEARNED', ); protected $rules; protected $nextRuleId; protected $rulesByHash; public function __construct() { $this->nextRuleId = 0; foreach ($this->getTypes() as $type) { $this->rules[$type] = array(); } $this->rulesByHash = array(); } public function add(Rule $rule, $type) { if (!isset(self::$types[$type])) { throw new \OutOfBoundsException('Unknown rule type: ' . $type); } $hash = $rule->getHash(); // Do not add if rule already exists if (isset($this->rulesByHash[$hash])) { $potentialDuplicates = $this->rulesByHash[$hash]; if (is_array($potentialDuplicates)) { foreach ($potentialDuplicates as $potentialDuplicate) { if ($rule->equals($potentialDuplicate)) { return; } } } else { if ($rule->equals($potentialDuplicates)) { return; } } } if (!isset($this->rules[$type])) { $this->rules[$type] = array(); } $this->rules[$type][] = $rule; $this->ruleById[$this->nextRuleId] = $rule; $rule->setType($type); $this->nextRuleId++; if (!isset($this->rulesByHash[$hash])) { $this->rulesByHash[$hash] = $rule; } elseif (is_array($this->rulesByHash[$hash])) { $this->rulesByHash[$hash][] = $rule; } else { $originalRule = $this->rulesByHash[$hash]; $this->rulesByHash[$hash] = array($originalRule, $rule); } } public function count() { return $this->nextRuleId; } public function ruleById($id) { return $this->ruleById[$id]; } public function getRules() { return $this->rules; } public function getIterator() { return new RuleSetIterator($this->getRules()); } public function getIteratorFor($types) { if (!is_array($types)) { $types = array($types); } $allRules = $this->getRules(); $rules = array(); foreach ($types as $type) { $rules[$type] = $allRules[$type]; } return new RuleSetIterator($rules); } public function getIteratorWithout($types) { if (!is_array($types)) { $types = array($types); } $rules = $this->getRules(); foreach ($types as $type) { unset($rules[$type]); } return new RuleSetIterator($rules); } public function getTypes() { $types = self::$types; unset($types[255]); return array_keys($types); } public function getPrettyString(Pool $pool = null) { $string = "\n"; foreach ($this->rules as $type => $rules) { $string .= str_pad(self::$types[$type], 8, ' ') . ": "; foreach ($rules as $rule) { $string .= ($pool ? $rule->getPrettyString($pool) : $rule)."\n"; } $string .= "\n\n"; } return $string; } public function __toString() { return $this->getPrettyString(null); } } composer-1.6.3/src/Composer/DependencyResolver/RuleSetGenerator.php000066400000000000000000000306411323436022200254720ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Repository\PlatformRepository; /** * @author Nils Adermann */ class RuleSetGenerator { protected $policy; protected $pool; protected $rules; protected $jobs; protected $installedMap; protected $whitelistedMap; protected $addedMap; public function __construct(PolicyInterface $policy, Pool $pool) { $this->policy = $policy; $this->pool = $pool; } /** * Creates a new rule for the requirements of a package * * This rule is of the form (-A|B|C), where B and C are the providers of * one requirement of the package A. * * @param PackageInterface $package The package with a requirement * @param array $providers The providers of the requirement * @param int $reason A RULE_* constant describing the * reason for generating this rule * @param mixed $reasonData Any data, e.g. the requirement name, * that goes with the reason * @return Rule The generated rule or null if tautological */ protected function createRequireRule(PackageInterface $package, array $providers, $reason, $reasonData = null) { $literals = array(-$package->id); foreach ($providers as $provider) { // self fulfilling rule? if ($provider === $package) { return null; } $literals[] = $provider->id; } return new GenericRule($literals, $reason, $reasonData); } /** * Creates a rule to install at least one of a set of packages * * The rule is (A|B|C) with A, B and C different packages. If the given * set of packages is empty an impossible rule is generated. * * @param array $packages The set of packages to choose from * @param int $reason A RULE_* constant describing the reason for * generating this rule * @param array $job The job this rule was created from * @return Rule The generated rule */ protected function createInstallOneOfRule(array $packages, $reason, $job) { $literals = array(); foreach ($packages as $package) { $literals[] = $package->id; } return new GenericRule($literals, $reason, $job['packageName'], $job); } /** * Creates a rule to remove a package * * The rule for a package A is (-A). * * @param PackageInterface $package The package to be removed * @param int $reason A RULE_* constant describing the * reason for generating this rule * @param array $job The job this rule was created from * @return Rule The generated rule */ protected function createRemoveRule(PackageInterface $package, $reason, $job) { return new GenericRule(array(-$package->id), $reason, $job['packageName'], $job); } /** * Creates a rule for two conflicting packages * * The rule for conflicting packages A and B is (-A|-B). A is called the issuer * and B the provider. * * @param PackageInterface $issuer The package declaring the conflict * @param PackageInterface $provider The package causing the conflict * @param int $reason A RULE_* constant describing the * reason for generating this rule * @param mixed $reasonData Any data, e.g. the package name, that * goes with the reason * @return Rule The generated rule */ protected function createRule2Literals(PackageInterface $issuer, PackageInterface $provider, $reason, $reasonData = null) { // ignore self conflict if ($issuer === $provider) { return null; } return new Rule2Literals(-$issuer->id, -$provider->id, $reason, $reasonData); } /** * Adds a rule unless it duplicates an existing one of any type * * To be able to directly pass in the result of one of the rule creation * methods null is allowed which will not insert a rule. * * @param int $type A TYPE_* constant defining the rule type * @param Rule $newRule The rule about to be added */ private function addRule($type, Rule $newRule = null) { if (!$newRule) { return; } $this->rules->add($newRule, $type); } protected function whitelistFromPackage(PackageInterface $package) { $workQueue = new \SplQueue; $workQueue->enqueue($package); while (!$workQueue->isEmpty()) { $package = $workQueue->dequeue(); if (isset($this->whitelistedMap[$package->id])) { continue; } $this->whitelistedMap[$package->id] = true; foreach ($package->getRequires() as $link) { $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint(), true); foreach ($possibleRequires as $require) { $workQueue->enqueue($require); } } $obsoleteProviders = $this->pool->whatProvides($package->getName(), null, true); foreach ($obsoleteProviders as $provider) { if ($provider === $package) { continue; } if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) { $workQueue->enqueue($provider); } } } } protected function addRulesForPackage(PackageInterface $package, $ignorePlatformReqs) { $workQueue = new \SplQueue; $workQueue->enqueue($package); while (!$workQueue->isEmpty()) { $package = $workQueue->dequeue(); if (isset($this->addedMap[$package->id])) { continue; } $this->addedMap[$package->id] = true; foreach ($package->getRequires() as $link) { if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) { continue; } $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint()); $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link)); foreach ($possibleRequires as $require) { $workQueue->enqueue($require); } } foreach ($package->getConflicts() as $link) { $possibleConflicts = $this->pool->whatProvides($link->getTarget(), $link->getConstraint()); foreach ($possibleConflicts as $conflict) { $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link)); } } // check obsoletes and implicit obsoletes of a package $isInstalled = (isset($this->installedMap[$package->id])); foreach ($package->getReplaces() as $link) { $obsoleteProviders = $this->pool->whatProvides($link->getTarget(), $link->getConstraint()); foreach ($obsoleteProviders as $provider) { if ($provider === $package) { continue; } if (!$this->obsoleteImpossibleForAlias($package, $provider)) { $reason = ($isInstalled) ? Rule::RULE_INSTALLED_PACKAGE_OBSOLETES : Rule::RULE_PACKAGE_OBSOLETES; $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $provider, $reason, $link)); } } } $obsoleteProviders = $this->pool->whatProvides($package->getName(), null); foreach ($obsoleteProviders as $provider) { if ($provider === $package) { continue; } if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) { $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package)); } elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) { $reason = ($package->getName() == $provider->getName()) ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES; $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRule2Literals($package, $provider, $reason, $package)); } } } } protected function obsoleteImpossibleForAlias($package, $provider) { $packageIsAlias = $package instanceof AliasPackage; $providerIsAlias = $provider instanceof AliasPackage; $impossible = ( ($packageIsAlias && $package->getAliasOf() === $provider) || ($providerIsAlias && $provider->getAliasOf() === $package) || ($packageIsAlias && $providerIsAlias && $provider->getAliasOf() === $package->getAliasOf()) ); return $impossible; } protected function whitelistFromJobs() { foreach ($this->jobs as $job) { switch ($job['cmd']) { case 'install': $packages = $this->pool->whatProvides($job['packageName'], $job['constraint'], true); foreach ($packages as $package) { $this->whitelistFromPackage($package); } break; } } } protected function addRulesForJobs($ignorePlatformReqs) { foreach ($this->jobs as $job) { switch ($job['cmd']) { case 'install': if (!$job['fixed'] && $ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $job['packageName'])) { break; } $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); if ($packages) { foreach ($packages as $package) { if (!isset($this->installedMap[$package->id])) { $this->addRulesForPackage($package, $ignorePlatformReqs); } } $rule = $this->createInstallOneOfRule($packages, Rule::RULE_JOB_INSTALL, $job); $this->addRule(RuleSet::TYPE_JOB, $rule); } break; case 'remove': // remove all packages with this name including uninstalled // ones to make sure none of them are picked as replacements $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); foreach ($packages as $package) { $rule = $this->createRemoveRule($package, Rule::RULE_JOB_REMOVE, $job); $this->addRule(RuleSet::TYPE_JOB, $rule); } break; } } } public function getRulesFor($jobs, $installedMap, $ignorePlatformReqs = false) { $this->jobs = $jobs; $this->rules = new RuleSet; $this->installedMap = $installedMap; $this->whitelistedMap = array(); foreach ($this->installedMap as $package) { $this->whitelistFromPackage($package); } $this->whitelistFromJobs(); $this->pool->setWhitelist($this->whitelistedMap); $this->addedMap = array(); foreach ($this->installedMap as $package) { $this->addRulesForPackage($package, $ignorePlatformReqs); } $this->addRulesForJobs($ignorePlatformReqs); return $this->rules; } } composer-1.6.3/src/Composer/DependencyResolver/RuleSetIterator.php000066400000000000000000000044351323436022200253370ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * @author Nils Adermann */ class RuleSetIterator implements \Iterator { protected $rules; protected $types; protected $currentOffset; protected $currentType; protected $currentTypeOffset; public function __construct(array $rules) { $this->rules = $rules; $this->types = array_keys($rules); sort($this->types); $this->rewind(); } public function current() { return $this->rules[$this->currentType][$this->currentOffset]; } public function key() { return $this->currentType; } public function next() { $this->currentOffset++; if (!isset($this->rules[$this->currentType])) { return; } if ($this->currentOffset >= count($this->rules[$this->currentType])) { $this->currentOffset = 0; do { $this->currentTypeOffset++; if (!isset($this->types[$this->currentTypeOffset])) { $this->currentType = -1; break; } $this->currentType = $this->types[$this->currentTypeOffset]; } while (isset($this->types[$this->currentTypeOffset]) && !count($this->rules[$this->currentType])); } } public function rewind() { $this->currentOffset = 0; $this->currentTypeOffset = -1; $this->currentType = -1; do { $this->currentTypeOffset++; if (!isset($this->types[$this->currentTypeOffset])) { $this->currentType = -1; break; } $this->currentType = $this->types[$this->currentTypeOffset]; } while (isset($this->types[$this->currentTypeOffset]) && !count($this->rules[$this->currentType])); } public function valid() { return isset($this->rules[$this->currentType]) && isset($this->rules[$this->currentType][$this->currentOffset]); } } composer-1.6.3/src/Composer/DependencyResolver/RuleWatchChain.php000066400000000000000000000025721323436022200251030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * An extension of SplDoublyLinkedList with seek and removal of current element * * SplDoublyLinkedList only allows deleting a particular offset and has no * method to set the internal iterator to a particular offset. * * @author Nils Adermann */ class RuleWatchChain extends \SplDoublyLinkedList { protected $offset = 0; /** * Moves the internal iterator to the specified offset * * @param int $offset The offset to seek to. */ public function seek($offset) { $this->rewind(); for ($i = 0; $i < $offset; $i++, $this->next()); } /** * Removes the current element from the list * * As SplDoublyLinkedList only allows deleting a particular offset and * incorrectly sets the internal iterator if you delete the current value * this method sets the internal iterator back to the following element * using the seek method. */ public function remove() { $offset = $this->key(); $this->offsetUnset($offset); $this->seek($offset); } } composer-1.6.3/src/Composer/DependencyResolver/RuleWatchGraph.php000066400000000000000000000123151323436022200251160ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * The RuleWatchGraph efficiently propagates decisions to other rules * * All rules generated for solving a SAT problem should be inserted into the * graph. When a decision on a literal is made, the graph can be used to * propagate the decision to all other rules involving the literal, leading to * other trivial decisions resulting from unit clauses. * * @author Nils Adermann */ class RuleWatchGraph { protected $watchChains = array(); /** * Inserts a rule node into the appropriate chains within the graph * * The node is prepended to the watch chains for each of the two literals it * watches. * * Assertions are skipped because they only depend on a single package and * have no alternative literal that could be true, so there is no need to * watch changes in any literals. * * @param RuleWatchNode $node The rule node to be inserted into the graph */ public function insert(RuleWatchNode $node) { if ($node->getRule()->isAssertion()) { return; } foreach (array($node->watch1, $node->watch2) as $literal) { if (!isset($this->watchChains[$literal])) { $this->watchChains[$literal] = new RuleWatchChain; } $this->watchChains[$literal]->unshift($node); } } /** * Propagates a decision on a literal to all rules watching the literal * * If a decision, e.g. +A has been made, then all rules containing -A, e.g. * (-A|+B|+C) now need to satisfy at least one of the other literals, so * that the rule as a whole becomes true, since with +A applied the rule * is now (false|+B|+C) so essentially (+B|+C). * * This means that all rules watching the literal -A need to be updated to * watch 2 other literals which can still be satisfied instead. So literals * that conflict with previously made decisions are not an option. * * Alternatively it can occur that a unit clause results: e.g. if in the * above example the rule was (-A|+B), then A turning true means that * B must now be decided true as well. * * @param int $decidedLiteral The literal which was decided (A in our example) * @param int $level The level at which the decision took place and at which * all resulting decisions should be made. * @param Decisions $decisions Used to check previous decisions and to * register decisions resulting from propagation * @return Rule|null If a conflict is found the conflicting rule is returned */ public function propagateLiteral($decidedLiteral, $level, $decisions) { // we invert the decided literal here, example: // A was decided => (-A|B) now requires B to be true, so we look for // rules which are fulfilled by -A, rather than A. $literal = -$decidedLiteral; if (!isset($this->watchChains[$literal])) { return null; } $chain = $this->watchChains[$literal]; $chain->rewind(); while ($chain->valid()) { $node = $chain->current(); $otherWatch = $node->getOtherWatch($literal); if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) { $ruleLiterals = $node->getRule()->getLiterals(); $alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions) { return $literal !== $ruleLiteral && $otherWatch !== $ruleLiteral && !$decisions->conflict($ruleLiteral); }); if ($alternativeLiterals) { reset($alternativeLiterals); $this->moveWatch($literal, current($alternativeLiterals), $node); continue; } if ($decisions->conflict($otherWatch)) { return $node->getRule(); } $decisions->decide($otherWatch, $level, $node->getRule()); } $chain->next(); } return null; } /** * Moves a rule node from one watch chain to another * * The rule node's watched literals are updated accordingly. * * @param $fromLiteral mixed A literal the node used to watch * @param $toLiteral mixed A literal the node should watch now * @param $node mixed The rule node to be moved */ protected function moveWatch($fromLiteral, $toLiteral, $node) { if (!isset($this->watchChains[$toLiteral])) { $this->watchChains[$toLiteral] = new RuleWatchChain; } $node->moveWatch($fromLiteral, $toLiteral); $this->watchChains[$fromLiteral]->remove(); $this->watchChains[$toLiteral]->unshift($node); } } composer-1.6.3/src/Composer/DependencyResolver/RuleWatchNode.php000066400000000000000000000052701323436022200247440ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * Wrapper around a Rule which keeps track of the two literals it watches * * Used by RuleWatchGraph to store rules in two RuleWatchChains. * * @author Nils Adermann */ class RuleWatchNode { public $watch1; public $watch2; protected $rule; /** * Creates a new node watching the first and second literals of the rule. * * @param Rule $rule The rule to wrap */ public function __construct($rule) { $this->rule = $rule; $literals = $rule->getLiterals(); $this->watch1 = count($literals) > 0 ? $literals[0] : 0; $this->watch2 = count($literals) > 1 ? $literals[1] : 0; } /** * Places the second watch on the rule's literal, decided at the highest level * * Useful for learned rules where the literal for the highest rule is most * likely to quickly lead to further decisions. * * @param Decisions $decisions The decisions made so far by the solver */ public function watch2OnHighest(Decisions $decisions) { $literals = $this->rule->getLiterals(); // if there are only 2 elements, both are being watched anyway if (count($literals) < 3) { return; } $watchLevel = 0; foreach ($literals as $literal) { $level = $decisions->decisionLevel($literal); if ($level > $watchLevel) { $this->watch2 = $literal; $watchLevel = $level; } } } /** * Returns the rule this node wraps * * @return Rule */ public function getRule() { return $this->rule; } /** * Given one watched literal, this method returns the other watched literal * * @param int $literal The watched literal that should not be returned * @return int A literal */ public function getOtherWatch($literal) { if ($this->watch1 == $literal) { return $this->watch2; } return $this->watch1; } /** * Moves a watch from one literal to another * * @param int $from The previously watched literal * @param int $to The literal to be watched now */ public function moveWatch($from, $to) { if ($this->watch1 == $from) { $this->watch1 = $to; } else { $this->watch2 = $to; } } } composer-1.6.3/src/Composer/DependencyResolver/Solver.php000066400000000000000000000642301323436022200235130ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\IO\IOInterface; use Composer\Repository\RepositoryInterface; use Composer\Repository\PlatformRepository; /** * @author Nils Adermann */ class Solver { const BRANCH_LITERALS = 0; const BRANCH_LEVEL = 1; /** @var PolicyInterface */ protected $policy; /** @var Pool */ protected $pool; /** @var RepositoryInterface */ protected $installed; /** @var Ruleset */ protected $rules; /** @var RuleSetGenerator */ protected $ruleSetGenerator; /** @var array */ protected $jobs; /** @var int[] */ protected $updateMap = array(); /** @var RuleWatchGraph */ protected $watchGraph; /** @var Decisions */ protected $decisions; /** @var int[] */ protected $installedMap; /** @var int */ protected $propagateIndex; /** @var array[] */ protected $branches = array(); /** @var Problem[] */ protected $problems = array(); /** @var array */ protected $learnedPool = array(); /** @var array */ protected $learnedWhy = array(); /** @var IOInterface */ protected $io; /** * @param PolicyInterface $policy * @param Pool $pool * @param RepositoryInterface $installed * @param IOInterface $io */ public function __construct(PolicyInterface $policy, Pool $pool, RepositoryInterface $installed, IOInterface $io) { $this->io = $io; $this->policy = $policy; $this->pool = $pool; $this->installed = $installed; $this->ruleSetGenerator = new RuleSetGenerator($policy, $pool); } /** * @return int */ public function getRuleSetSize() { return count($this->rules); } // aka solver_makeruledecisions private function makeAssertionRuleDecisions() { $decisionStart = count($this->decisions) - 1; $rulesCount = count($this->rules); for ($ruleIndex = 0; $ruleIndex < $rulesCount; $ruleIndex++) { $rule = $this->rules->ruleById[$ruleIndex]; if (!$rule->isAssertion() || $rule->isDisabled()) { continue; } $literals = $rule->getLiterals(); $literal = $literals[0]; if (!$this->decisions->decided(abs($literal))) { $this->decisions->decide($literal, 1, $rule); continue; } if ($this->decisions->satisfy($literal)) { continue; } // found a conflict if (RuleSet::TYPE_LEARNED === $rule->getType()) { $rule->disable(); continue; } $conflict = $this->decisions->decisionRule($literal); if ($conflict && RuleSet::TYPE_PACKAGE === $conflict->getType()) { $problem = new Problem($this->pool); $problem->addRule($rule); $problem->addRule($conflict); $this->disableProblem($rule); $this->problems[] = $problem; continue; } // conflict with another job $problem = new Problem($this->pool); $problem->addRule($rule); $problem->addRule($conflict); // push all of our rules (can only be job rules) // asserting this literal on the problem stack foreach ($this->rules->getIteratorFor(RuleSet::TYPE_JOB) as $assertRule) { if ($assertRule->isDisabled() || !$assertRule->isAssertion()) { continue; } $assertRuleLiterals = $assertRule->getLiterals(); $assertRuleLiteral = $assertRuleLiterals[0]; if (abs($literal) !== abs($assertRuleLiteral)) { continue; } $problem->addRule($assertRule); $this->disableProblem($assertRule); } $this->problems[] = $problem; $this->decisions->resetToOffset($decisionStart); $ruleIndex = -1; } } protected function setupInstalledMap() { $this->installedMap = array(); foreach ($this->installed->getPackages() as $package) { $this->installedMap[$package->id] = $package; } } /** * @param bool $ignorePlatformReqs */ protected function checkForRootRequireProblems($ignorePlatformReqs) { foreach ($this->jobs as $job) { switch ($job['cmd']) { case 'update': $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']); foreach ($packages as $package) { if (isset($this->installedMap[$package->id])) { $this->updateMap[$package->id] = true; } } break; case 'update-all': foreach ($this->installedMap as $package) { $this->updateMap[$package->id] = true; } break; case 'install': if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $job['packageName'])) { break; } if (!$this->pool->whatProvides($job['packageName'], $job['constraint'])) { $problem = new Problem($this->pool); $problem->addRule(new GenericRule(array(), null, null, $job)); $this->problems[] = $problem; } break; } } } /** * @param Request $request * @param bool $ignorePlatformReqs * @return array */ public function solve(Request $request, $ignorePlatformReqs = false) { $this->jobs = $request->getJobs(); $this->setupInstalledMap(); $this->rules = $this->ruleSetGenerator->getRulesFor($this->jobs, $this->installedMap, $ignorePlatformReqs); $this->checkForRootRequireProblems($ignorePlatformReqs); $this->decisions = new Decisions($this->pool); $this->watchGraph = new RuleWatchGraph; foreach ($this->rules as $rule) { $this->watchGraph->insert(new RuleWatchNode($rule)); } /* make decisions based on job/update assertions */ $this->makeAssertionRuleDecisions(); $this->io->writeError('Resolving dependencies through SAT', true, IOInterface::DEBUG); $before = microtime(true); $this->runSat(true); $this->io->writeError(sprintf('Dependency resolution completed in %.3f seconds', microtime(true) - $before), true, IOInterface::VERBOSE); // decide to remove everything that's installed and undecided foreach ($this->installedMap as $packageId => $void) { if ($this->decisions->undecided($packageId)) { $this->decisions->decide(-$packageId, 1, null); } } if ($this->problems) { throw new SolverProblemsException($this->problems, $this->installedMap); } $transaction = new Transaction($this->policy, $this->pool, $this->installedMap, $this->decisions); return $transaction->getOperations(); } /** * Makes a decision and propagates it to all rules. * * Evaluates each term affected by the decision (linked through watches) * If we find unit rules we make new decisions based on them * * @param int $level * @return Rule|null A rule on conflict, otherwise null. */ protected function propagate($level) { while ($this->decisions->validOffset($this->propagateIndex)) { $decision = $this->decisions->atOffset($this->propagateIndex); $conflict = $this->watchGraph->propagateLiteral( $decision[Decisions::DECISION_LITERAL], $level, $this->decisions ); $this->propagateIndex++; if ($conflict) { return $conflict; } } return null; } /** * Reverts a decision at the given level. * * @param int $level */ private function revert($level) { while (!$this->decisions->isEmpty()) { $literal = $this->decisions->lastLiteral(); if ($this->decisions->undecided($literal)) { break; } $decisionLevel = $this->decisions->decisionLevel($literal); if ($decisionLevel <= $level) { break; } $this->decisions->revertLast(); $this->propagateIndex = count($this->decisions); } while (!empty($this->branches) && $this->branches[count($this->branches) - 1][self::BRANCH_LEVEL] >= $level) { array_pop($this->branches); } } /** * setpropagatelearn * * add free decision (a positive literal) to decision queue * increase level and propagate decision * return if no conflict. * * in conflict case, analyze conflict rule, add resulting * rule to learnt rule set, make decision from learnt * rule (always unit) and re-propagate. * * returns the new solver level or 0 if unsolvable * * @param int $level * @param string|int $literal * @param bool $disableRules * @param Rule $rule * @return int */ private function setPropagateLearn($level, $literal, $disableRules, Rule $rule) { $level++; $this->decisions->decide($literal, $level, $rule); while (true) { $rule = $this->propagate($level); if (!$rule) { break; } if ($level == 1) { return $this->analyzeUnsolvable($rule, $disableRules); } // conflict list($learnLiteral, $newLevel, $newRule, $why) = $this->analyze($level, $rule); if ($newLevel <= 0 || $newLevel >= $level) { throw new SolverBugException( "Trying to revert to invalid level ".(int) $newLevel." from level ".(int) $level."." ); } elseif (!$newRule) { throw new SolverBugException( "No rule was learned from analyzing $rule at level $level." ); } $level = $newLevel; $this->revert($level); $this->rules->add($newRule, RuleSet::TYPE_LEARNED); $this->learnedWhy[spl_object_hash($newRule)] = $why; $ruleNode = new RuleWatchNode($newRule); $ruleNode->watch2OnHighest($this->decisions); $this->watchGraph->insert($ruleNode); $this->decisions->decide($learnLiteral, $level, $newRule); } return $level; } /** * @param int $level * @param array $decisionQueue * @param bool $disableRules * @param Rule $rule * @return int */ private function selectAndInstall($level, array $decisionQueue, $disableRules, Rule $rule) { // choose best package to install from decisionQueue $literals = $this->policy->selectPreferredPackages($this->pool, $this->installedMap, $decisionQueue, $rule->getRequiredPackage()); $selectedLiteral = array_shift($literals); // if there are multiple candidates, then branch if (count($literals)) { $this->branches[] = array($literals, $level); } return $this->setPropagateLearn($level, $selectedLiteral, $disableRules, $rule); } /** * @param int $level * @param Rule $rule * @return array */ protected function analyze($level, Rule $rule) { $analyzedRule = $rule; $ruleLevel = 1; $num = 0; $l1num = 0; $seen = array(); $learnedLiterals = array(null); $decisionId = count($this->decisions); $this->learnedPool[] = array(); while (true) { $this->learnedPool[count($this->learnedPool) - 1][] = $rule; foreach ($rule->getLiterals() as $literal) { // skip the one true literal if ($this->decisions->satisfy($literal)) { continue; } if (isset($seen[abs($literal)])) { continue; } $seen[abs($literal)] = true; $l = $this->decisions->decisionLevel($literal); if (1 === $l) { $l1num++; } elseif ($level === $l) { $num++; } else { // not level1 or conflict level, add to new rule $learnedLiterals[] = $literal; if ($l > $ruleLevel) { $ruleLevel = $l; } } } $l1retry = true; while ($l1retry) { $l1retry = false; if (!$num && !--$l1num) { // all level 1 literals done break 2; } while (true) { if ($decisionId <= 0) { throw new SolverBugException( "Reached invalid decision id $decisionId while looking through $rule for a literal present in the analyzed rule $analyzedRule." ); } $decisionId--; $decision = $this->decisions->atOffset($decisionId); $literal = $decision[Decisions::DECISION_LITERAL]; if (isset($seen[abs($literal)])) { break; } } unset($seen[abs($literal)]); if ($num && 0 === --$num) { $learnedLiterals[0] = -abs($literal); if (!$l1num) { break 2; } foreach ($learnedLiterals as $i => $learnedLiteral) { if ($i !== 0) { unset($seen[abs($learnedLiteral)]); } } // only level 1 marks left $l1num++; $l1retry = true; } } $decision = $this->decisions->atOffset($decisionId); $rule = $decision[Decisions::DECISION_REASON]; } $why = count($this->learnedPool) - 1; if (!$learnedLiterals[0]) { throw new SolverBugException( "Did not find a learnable literal in analyzed rule $analyzedRule." ); } $newRule = new GenericRule($learnedLiterals, Rule::RULE_LEARNED, $why); return array($learnedLiterals[0], $ruleLevel, $newRule, $why); } /** * @param Problem $problem * @param Rule $conflictRule */ private function analyzeUnsolvableRule(Problem $problem, Rule $conflictRule) { $why = spl_object_hash($conflictRule); if ($conflictRule->getType() == RuleSet::TYPE_LEARNED) { $learnedWhy = $this->learnedWhy[$why]; $problemRules = $this->learnedPool[$learnedWhy]; foreach ($problemRules as $problemRule) { $this->analyzeUnsolvableRule($problem, $problemRule); } return; } if ($conflictRule->getType() == RuleSet::TYPE_PACKAGE) { // package rules cannot be part of a problem return; } $problem->nextSection(); $problem->addRule($conflictRule); } /** * @param Rule $conflictRule * @param bool $disableRules * @return int */ private function analyzeUnsolvable(Rule $conflictRule, $disableRules) { $problem = new Problem($this->pool); $problem->addRule($conflictRule); $this->analyzeUnsolvableRule($problem, $conflictRule); $this->problems[] = $problem; $seen = array(); $literals = $conflictRule->getLiterals(); foreach ($literals as $literal) { // skip the one true literal if ($this->decisions->satisfy($literal)) { continue; } $seen[abs($literal)] = true; } foreach ($this->decisions as $decision) { $literal = $decision[Decisions::DECISION_LITERAL]; // skip literals that are not in this rule if (!isset($seen[abs($literal)])) { continue; } $why = $decision[Decisions::DECISION_REASON]; $problem->addRule($why); $this->analyzeUnsolvableRule($problem, $why); $literals = $why->getLiterals(); foreach ($literals as $literal) { // skip the one true literal if ($this->decisions->satisfy($literal)) { continue; } $seen[abs($literal)] = true; } } if ($disableRules) { foreach ($this->problems[count($this->problems) - 1] as $reason) { $this->disableProblem($reason['rule']); } $this->resetSolver(); return 1; } return 0; } /** * @param Rule $why */ private function disableProblem(Rule $why) { $job = $why->getJob(); if (!$job) { $why->disable(); return; } // disable all rules of this job foreach ($this->rules as $rule) { /** @var Rule $rule */ if ($job === $rule->getJob()) { $rule->disable(); } } } private function resetSolver() { $this->decisions->reset(); $this->propagateIndex = 0; $this->branches = array(); $this->enableDisableLearnedRules(); $this->makeAssertionRuleDecisions(); } /** * enable/disable learnt rules * * we have enabled or disabled some of our rules. We now re-enable all * of our learnt rules except the ones that were learnt from rules that * are now disabled. */ private function enableDisableLearnedRules() { foreach ($this->rules->getIteratorFor(RuleSet::TYPE_LEARNED) as $rule) { $why = $this->learnedWhy[spl_object_hash($rule)]; $problemRules = $this->learnedPool[$why]; $foundDisabled = false; foreach ($problemRules as $problemRule) { if ($problemRule->isDisabled()) { $foundDisabled = true; break; } } if ($foundDisabled && $rule->isEnabled()) { $rule->disable(); } elseif (!$foundDisabled && $rule->isDisabled()) { $rule->enable(); } } } /** * @param bool $disableRules */ private function runSat($disableRules = true) { $this->propagateIndex = 0; /* * here's the main loop: * 1) propagate new decisions (only needed once) * 2) fulfill jobs * 3) fulfill all unresolved rules * 4) minimalize solution if we had choices * if we encounter a problem, we rewind to a safe level and restart * with step 1 */ $decisionQueue = array(); $decisionSupplementQueue = array(); /** * @todo this makes $disableRules always false; determine the rationale and possibly remove dead code? */ $disableRules = array(); $level = 1; $systemLevel = $level + 1; $installedPos = 0; while (true) { if (1 === $level) { $conflictRule = $this->propagate($level); if (null !== $conflictRule) { if ($this->analyzeUnsolvable($conflictRule, $disableRules)) { continue; } return; } } // handle job rules if ($level < $systemLevel) { $iterator = $this->rules->getIteratorFor(RuleSet::TYPE_JOB); foreach ($iterator as $rule) { if ($rule->isEnabled()) { $decisionQueue = array(); $noneSatisfied = true; foreach ($rule->getLiterals() as $literal) { if ($this->decisions->satisfy($literal)) { $noneSatisfied = false; break; } if ($literal > 0 && $this->decisions->undecided($literal)) { $decisionQueue[] = $literal; } } if ($noneSatisfied && count($decisionQueue)) { // prune all update packages until installed version // except for requested updates if (count($this->installed) != count($this->updateMap)) { $prunedQueue = array(); foreach ($decisionQueue as $literal) { if (isset($this->installedMap[abs($literal)])) { $prunedQueue[] = $literal; if (isset($this->updateMap[abs($literal)])) { $prunedQueue = $decisionQueue; break; } } } $decisionQueue = $prunedQueue; } } if ($noneSatisfied && count($decisionQueue)) { $oLevel = $level; $level = $this->selectAndInstall($level, $decisionQueue, $disableRules, $rule); if (0 === $level) { return; } if ($level <= $oLevel) { break; } } } } $systemLevel = $level + 1; // jobs left $iterator->next(); if ($iterator->valid()) { continue; } } if ($level < $systemLevel) { $systemLevel = $level; } $rulesCount = count($this->rules); for ($i = 0, $n = 0; $n < $rulesCount; $i++, $n++) { if ($i == $rulesCount) { $i = 0; } $rule = $this->rules->ruleById[$i]; $literals = $rule->getLiterals(); if ($rule->isDisabled()) { continue; } $decisionQueue = array(); // make sure that // * all negative literals are installed // * no positive literal is installed // i.e. the rule is not fulfilled and we // just need to decide on the positive literals // foreach ($literals as $literal) { if ($literal <= 0) { if (!$this->decisions->decidedInstall(abs($literal))) { continue 2; // next rule } } else { if ($this->decisions->decidedInstall(abs($literal))) { continue 2; // next rule } if ($this->decisions->undecided(abs($literal))) { $decisionQueue[] = $literal; } } } // need to have at least 2 item to pick from if (count($decisionQueue) < 2) { continue; } $level = $this->selectAndInstall($level, $decisionQueue, $disableRules, $rule); if (0 === $level) { return; } // something changed, so look at all rules again $rulesCount = count($this->rules); $n = -1; } if ($level < $systemLevel) { continue; } // minimization step if (count($this->branches)) { $lastLiteral = null; $lastLevel = null; $lastBranchIndex = 0; $lastBranchOffset = 0; for ($i = count($this->branches) - 1; $i >= 0; $i--) { list($literals, $l) = $this->branches[$i]; foreach ($literals as $offset => $literal) { if ($literal && $literal > 0 && $this->decisions->decisionLevel($literal) > $l + 1) { $lastLiteral = $literal; $lastBranchIndex = $i; $lastBranchOffset = $offset; $lastLevel = $l; } } } if ($lastLiteral) { unset($this->branches[$lastBranchIndex][self::BRANCH_LITERALS][$lastBranchOffset]); $level = $lastLevel; $this->revert($level); $why = $this->decisions->lastReason(); $level = $this->setPropagateLearn($level, $lastLiteral, $disableRules, $why); if ($level == 0) { return; } continue; } } break; } } } composer-1.6.3/src/Composer/DependencyResolver/SolverBugException.php000066400000000000000000000013651323436022200260300ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * @author Nils Adermann */ class SolverBugException extends \RuntimeException { public function __construct($message) { parent::__construct( $message."\nThis exception was most likely caused by a bug in Composer.\n". "Please report the command you ran, the exact error you received, and your composer.json on https://github.com/composer/composer/issues - thank you!\n"); } } composer-1.6.3/src/Composer/DependencyResolver/SolverProblemsException.php000066400000000000000000000053051323436022200270740ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Util\IniHelper; /** * @author Nils Adermann */ class SolverProblemsException extends \RuntimeException { protected $problems; protected $installedMap; public function __construct(array $problems, array $installedMap) { $this->problems = $problems; $this->installedMap = $installedMap; parent::__construct($this->createMessage(), 2); } protected function createMessage() { $text = "\n"; $hasExtensionProblems = false; foreach ($this->problems as $i => $problem) { $text .= " Problem ".($i + 1).$problem->getPrettyString($this->installedMap)."\n"; if (!$hasExtensionProblems && $this->hasExtensionProblems($problem->getReasons())) { $hasExtensionProblems = true; } } if (strpos($text, 'could not be found') || strpos($text, 'no matching package found')) { $text .= "\nPotential causes:\n - A typo in the package name\n - The package is not available in a stable-enough version according to your minimum-stability setting\n see for more details.\n - It's a private package and you forgot to add a custom repository to find it\n\nRead for further common problems."; } if ($hasExtensionProblems) { $text .= $this->createExtensionHint(); } return $text; } public function getProblems() { return $this->problems; } private function createExtensionHint() { $paths = IniHelper::getAll(); if (count($paths) === 1 && empty($paths[0])) { return ''; } $text = "\n To enable extensions, verify that they are enabled in your .ini files:\n - "; $text .= implode("\n - ", $paths); $text .= "\n You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode."; return $text; } private function hasExtensionProblems(array $reasonSets) { foreach ($reasonSets as $reasonSet) { foreach ($reasonSet as $reason) { if (isset($reason["rule"]) && 0 === strpos($reason["rule"]->getRequiredPackage(), 'ext-')) { return true; } } } return false; } } composer-1.6.3/src/Composer/DependencyResolver/Transaction.php000066400000000000000000000170571323436022200245330ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Package\AliasPackage; /** * @author Nils Adermann */ class Transaction { protected $policy; protected $pool; protected $installedMap; protected $decisions; protected $transaction; public function __construct($policy, $pool, $installedMap, $decisions) { $this->policy = $policy; $this->pool = $pool; $this->installedMap = $installedMap; $this->decisions = $decisions; $this->transaction = array(); } public function getOperations() { $installMeansUpdateMap = $this->findUpdates(); $updateMap = array(); $installMap = array(); $uninstallMap = array(); foreach ($this->decisions as $i => $decision) { $literal = $decision[Decisions::DECISION_LITERAL]; $reason = $decision[Decisions::DECISION_REASON]; $package = $this->pool->literalToPackage($literal); // wanted & installed || !wanted & !installed if (($literal > 0) == (isset($this->installedMap[$package->id]))) { continue; } if ($literal > 0) { if (isset($installMeansUpdateMap[abs($literal)]) && !$package instanceof AliasPackage) { $source = $installMeansUpdateMap[abs($literal)]; $updateMap[$package->id] = array( 'package' => $package, 'source' => $source, 'reason' => $reason, ); // avoid updates to one package from multiple origins unset($installMeansUpdateMap[abs($literal)]); $ignoreRemove[$source->id] = true; } else { $installMap[$package->id] = array( 'package' => $package, 'reason' => $reason, ); } } } foreach ($this->decisions as $i => $decision) { $literal = $decision[Decisions::DECISION_LITERAL]; $reason = $decision[Decisions::DECISION_REASON]; $package = $this->pool->literalToPackage($literal); if ($literal <= 0 && isset($this->installedMap[$package->id]) && !isset($ignoreRemove[$package->id])) { $uninstallMap[$package->id] = array( 'package' => $package, 'reason' => $reason, ); } } $this->transactionFromMaps($installMap, $updateMap, $uninstallMap); return $this->transaction; } protected function transactionFromMaps($installMap, $updateMap, $uninstallMap) { $queue = array_map( function ($operation) { return $operation['package']; }, $this->findRootPackages($installMap, $updateMap) ); $visited = array(); while (!empty($queue)) { $package = array_pop($queue); $packageId = $package->id; if (!isset($visited[$packageId])) { $queue[] = $package; if ($package instanceof AliasPackage) { $queue[] = $package->getAliasOf(); } else { foreach ($package->getRequires() as $link) { $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint()); foreach ($possibleRequires as $require) { $queue[] = $require; } } } $visited[$package->id] = true; } else { if (isset($installMap[$packageId])) { $this->install( $installMap[$packageId]['package'], $installMap[$packageId]['reason'] ); unset($installMap[$packageId]); } if (isset($updateMap[$packageId])) { $this->update( $updateMap[$packageId]['source'], $updateMap[$packageId]['package'], $updateMap[$packageId]['reason'] ); unset($updateMap[$packageId]); } } } foreach ($uninstallMap as $uninstall) { $this->uninstall($uninstall['package'], $uninstall['reason']); } } protected function findRootPackages($installMap, $updateMap) { $packages = $installMap + $updateMap; $roots = $packages; foreach ($packages as $packageId => $operation) { $package = $operation['package']; if (!isset($roots[$packageId])) { continue; } foreach ($package->getRequires() as $link) { $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint()); foreach ($possibleRequires as $require) { if ($require !== $package) { unset($roots[$require->id]); } } } } return $roots; } protected function findUpdates() { $installMeansUpdateMap = array(); foreach ($this->decisions as $i => $decision) { $literal = $decision[Decisions::DECISION_LITERAL]; $package = $this->pool->literalToPackage($literal); if ($package instanceof AliasPackage) { continue; } // !wanted & installed if ($literal <= 0 && isset($this->installedMap[$package->id])) { $updates = $this->policy->findUpdatePackages($this->pool, $this->installedMap, $package); $literals = array($package->id); foreach ($updates as $update) { $literals[] = $update->id; } foreach ($literals as $updateLiteral) { if ($updateLiteral !== $literal) { $installMeansUpdateMap[abs($updateLiteral)] = $package; } } } } return $installMeansUpdateMap; } protected function install($package, $reason) { if ($package instanceof AliasPackage) { return $this->markAliasInstalled($package, $reason); } $this->transaction[] = new Operation\InstallOperation($package, $reason); } protected function update($from, $to, $reason) { $this->transaction[] = new Operation\UpdateOperation($from, $to, $reason); } protected function uninstall($package, $reason) { if ($package instanceof AliasPackage) { return $this->markAliasUninstalled($package, $reason); } $this->transaction[] = new Operation\UninstallOperation($package, $reason); } protected function markAliasInstalled($package, $reason) { $this->transaction[] = new Operation\MarkAliasInstalledOperation($package, $reason); } protected function markAliasUninstalled($package, $reason) { $this->transaction[] = new Operation\MarkAliasUninstalledOperation($package, $reason); } } composer-1.6.3/src/Composer/Downloader/000077500000000000000000000000001323436022200200215ustar00rootroot00000000000000composer-1.6.3/src/Composer/Downloader/ArchiveDownloader.php000066400000000000000000000106551323436022200241410ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Symfony\Component\Finder\Finder; use Composer\IO\IOInterface; /** * Base downloader for archives * * @author Kirill chEbba Chebunin * @author Jordi Boggiano * @author François Pluchino */ abstract class ArchiveDownloader extends FileDownloader { /** * {@inheritDoc} */ public function download(PackageInterface $package, $path, $output = true) { $temporaryDir = $this->config->get('vendor-dir').'/composer/'.substr(md5(uniqid('', true)), 0, 8); $retries = 3; while ($retries--) { $fileName = parent::download($package, $path, $output); $this->io->writeError(' Extracting archive', false, IOInterface::VERBOSE); try { $this->filesystem->ensureDirectoryExists($temporaryDir); try { $this->extract($fileName, $temporaryDir); } catch (\Exception $e) { // remove cache if the file was corrupted parent::clearLastCacheWrite($package); throw $e; } $this->filesystem->unlink($fileName); $contentDir = $this->getFolderContent($temporaryDir); // only one dir in the archive, extract its contents out of it if (1 === count($contentDir) && is_dir(reset($contentDir))) { $contentDir = $this->getFolderContent((string) reset($contentDir)); } // move files back out of the temp dir foreach ($contentDir as $file) { $file = (string) $file; $this->filesystem->rename($file, $path . '/' . basename($file)); } $this->filesystem->removeDirectory($temporaryDir); if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir').'/composer/')) { $this->filesystem->removeDirectory($this->config->get('vendor-dir').'/composer/'); } if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir'))) { $this->filesystem->removeDirectory($this->config->get('vendor-dir')); } } catch (\Exception $e) { // clean up $this->filesystem->removeDirectory($path); $this->filesystem->removeDirectory($temporaryDir); // retry downloading if we have an invalid zip file if ($retries && $e instanceof \UnexpectedValueException && class_exists('ZipArchive') && $e->getCode() === \ZipArchive::ER_NOZIP) { $this->io->writeError(''); if ($this->io->isDebug()) { $this->io->writeError(' Invalid zip file ('.$e->getMessage().'), retrying...'); } else { $this->io->writeError(' Invalid zip file, retrying...'); } usleep(500000); continue; } throw $e; } break; } } /** * {@inheritdoc} */ protected function getFileName(PackageInterface $package, $path) { return rtrim($path.'/'.md5($path.spl_object_hash($package)).'.'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_EXTENSION), '.'); } /** * Extract file to directory * * @param string $file Extracted file * @param string $path Directory * * @throws \UnexpectedValueException If can not extract downloaded file to path */ abstract protected function extract($file, $path); /** * Returns the folder content, excluding dotfiles * * @param string $dir Directory * @return \SplFileInfo[] */ private function getFolderContent($dir) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->notName('.DS_Store') ->depth(0) ->in($dir); return iterator_to_array($finder); } } composer-1.6.3/src/Composer/Downloader/ChangeReportInterface.php000066400000000000000000000013761323436022200247430ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * ChangeReport interface. * * @author Sascha Egerer */ interface ChangeReportInterface { /** * Checks for changes to the local copy * * @param PackageInterface $package package instance * @param string $path package directory * @return string|null changes or null */ public function getLocalChanges(PackageInterface $package, $path); } composer-1.6.3/src/Composer/Downloader/DownloadManager.php000066400000000000000000000244501323436022200236010ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Composer\IO\IOInterface; use Composer\Util\Filesystem; /** * Downloaders manager. * * @author Konstantin Kudryashov */ class DownloadManager { private $io; private $preferDist = false; private $preferSource = false; private $packagePreferences = array(); private $filesystem; private $downloaders = array(); /** * Initializes download manager. * * @param IOInterface $io The Input Output Interface * @param bool $preferSource prefer downloading from source * @param Filesystem|null $filesystem custom Filesystem object */ public function __construct(IOInterface $io, $preferSource = false, Filesystem $filesystem = null) { $this->io = $io; $this->preferSource = $preferSource; $this->filesystem = $filesystem ?: new Filesystem(); } /** * Makes downloader prefer source installation over the dist. * * @param bool $preferSource prefer downloading from source * @return DownloadManager */ public function setPreferSource($preferSource) { $this->preferSource = $preferSource; return $this; } /** * Makes downloader prefer dist installation over the source. * * @param bool $preferDist prefer downloading from dist * @return DownloadManager */ public function setPreferDist($preferDist) { $this->preferDist = $preferDist; return $this; } /** * Sets fine tuned preference settings for package level source/dist selection. * * @param array $preferences array of preferences by package patterns * @return DownloadManager */ public function setPreferences(array $preferences) { $this->packagePreferences = $preferences; return $this; } /** * Sets whether to output download progress information for all registered * downloaders * * @param bool $outputProgress * @return DownloadManager */ public function setOutputProgress($outputProgress) { foreach ($this->downloaders as $downloader) { $downloader->setOutputProgress($outputProgress); } return $this; } /** * Sets installer downloader for a specific installation type. * * @param string $type installation type * @param DownloaderInterface $downloader downloader instance * @return DownloadManager */ public function setDownloader($type, DownloaderInterface $downloader) { $type = strtolower($type); $this->downloaders[$type] = $downloader; return $this; } /** * Returns downloader for a specific installation type. * * @param string $type installation type * @throws \InvalidArgumentException if downloader for provided type is not registered * @return DownloaderInterface */ public function getDownloader($type) { $type = strtolower($type); if (!isset($this->downloaders[$type])) { throw new \InvalidArgumentException(sprintf('Unknown downloader type: %s. Available types: %s.', $type, implode(', ', array_keys($this->downloaders)))); } return $this->downloaders[$type]; } /** * Returns downloader for already installed package. * * @param PackageInterface $package package instance * @throws \InvalidArgumentException if package has no installation source specified * @throws \LogicException if specific downloader used to load package with * wrong type * @return DownloaderInterface|null */ public function getDownloaderForInstalledPackage(PackageInterface $package) { $installationSource = $package->getInstallationSource(); if ('metapackage' === $package->getType()) { return; } if ('dist' === $installationSource) { $downloader = $this->getDownloader($package->getDistType()); } elseif ('source' === $installationSource) { $downloader = $this->getDownloader($package->getSourceType()); } else { throw new \InvalidArgumentException( 'Package '.$package.' seems not been installed properly' ); } if ($installationSource !== $downloader->getInstallationSource()) { throw new \LogicException(sprintf( 'Downloader "%s" is a %s type downloader and can not be used to download %s for package %s', get_class($downloader), $downloader->getInstallationSource(), $installationSource, $package )); } return $downloader; } /** * Downloads package into target dir. * * @param PackageInterface $package package instance * @param string $targetDir target dir * @param bool $preferSource prefer installation from source * * @throws \InvalidArgumentException if package have no urls to download from * @throws \RuntimeException */ public function download(PackageInterface $package, $targetDir, $preferSource = null) { $preferSource = null !== $preferSource ? $preferSource : $this->preferSource; $sourceType = $package->getSourceType(); $distType = $package->getDistType(); $sources = array(); if ($sourceType) { $sources[] = 'source'; } if ($distType) { $sources[] = 'dist'; } if (empty($sources)) { throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified'); } if (!$preferSource && ($this->preferDist || 'dist' === $this->resolvePackageInstallPreference($package))) { $sources = array_reverse($sources); } $this->filesystem->ensureDirectoryExists($targetDir); foreach ($sources as $i => $source) { if (isset($e)) { $this->io->writeError(' Now trying to download from ' . $source . ''); } $package->setInstallationSource($source); try { $downloader = $this->getDownloaderForInstalledPackage($package); if ($downloader) { $downloader->download($package, $targetDir); } break; } catch (\RuntimeException $e) { if ($i === count($sources) - 1) { throw $e; } $this->io->writeError( ' Failed to download '. $package->getPrettyName(). ' from ' . $source . ': '. $e->getMessage().'' ); } } } /** * Updates package from initial to target version. * * @param PackageInterface $initial initial package version * @param PackageInterface $target target package version * @param string $targetDir target dir * * @throws \InvalidArgumentException if initial package is not installed */ public function update(PackageInterface $initial, PackageInterface $target, $targetDir) { $downloader = $this->getDownloaderForInstalledPackage($initial); if (!$downloader) { return; } $installationSource = $initial->getInstallationSource(); if ('dist' === $installationSource) { $initialType = $initial->getDistType(); $targetType = $target->getDistType(); } else { $initialType = $initial->getSourceType(); $targetType = $target->getSourceType(); } // upgrading from a dist stable package to a dev package, force source reinstall if ($target->isDev() && 'dist' === $installationSource) { $downloader->remove($initial, $targetDir); $this->download($target, $targetDir); return; } if ($initialType === $targetType) { $target->setInstallationSource($installationSource); try { $downloader->update($initial, $target, $targetDir); return; } catch (\RuntimeException $e) { if (!$this->io->isInteractive()) { throw $e; } $this->io->writeError(' Update failed ('.$e->getMessage().')'); if (!$this->io->askConfirmation(' Would you like to try reinstalling the package instead [yes]? ', true)) { throw $e; } } } $downloader->remove($initial, $targetDir); $this->download($target, $targetDir, 'source' === $installationSource); } /** * Removes package from target dir. * * @param PackageInterface $package package instance * @param string $targetDir target dir */ public function remove(PackageInterface $package, $targetDir) { $downloader = $this->getDownloaderForInstalledPackage($package); if ($downloader) { $downloader->remove($package, $targetDir); } } /** * Determines the install preference of a package * * @param PackageInterface $package package instance * * @return string */ protected function resolvePackageInstallPreference(PackageInterface $package) { foreach ($this->packagePreferences as $pattern => $preference) { $pattern = '{^'.str_replace('\\*', '.*', preg_quote($pattern)).'$}i'; if (preg_match($pattern, $package->getName())) { if ('dist' === $preference || (!$package->isDev() && 'auto' === $preference)) { return 'dist'; } return 'source'; } } return $package->isDev() ? 'source' : 'dist'; } } composer-1.6.3/src/Composer/Downloader/DownloaderInterface.php000066400000000000000000000033651323436022200244600ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * Downloader interface. * * @author Konstantin Kudryashov * @author Jordi Boggiano */ interface DownloaderInterface { /** * Returns installation source (either source or dist). * * @return string "source" or "dist" */ public function getInstallationSource(); /** * Downloads specific package into specific folder. * * @param PackageInterface $package package instance * @param string $path download path */ public function download(PackageInterface $package, $path); /** * Updates specific package in specific folder from initial to target version. * * @param PackageInterface $initial initial package * @param PackageInterface $target updated package * @param string $path download path */ public function update(PackageInterface $initial, PackageInterface $target, $path); /** * Removes specific package from specific folder. * * @param PackageInterface $package package instance * @param string $path download path */ public function remove(PackageInterface $package, $path); /** * Sets whether to output download progress information or not * * @param bool $outputProgress * @return DownloaderInterface */ public function setOutputProgress($outputProgress); } composer-1.6.3/src/Composer/Downloader/DvcsDownloaderInterface.php000066400000000000000000000014161323436022200252730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * DVCS Downloader interface. * * @author James Titcumb */ interface DvcsDownloaderInterface { /** * Checks for unpushed changes to a current branch * * @param PackageInterface $package package directory * @param string $path package directory * @return string|null changes or null */ public function getUnpushedChanges(PackageInterface $package, $path); } composer-1.6.3/src/Composer/Downloader/FileDownloader.php000066400000000000000000000235461323436022200234420ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Cache; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Plugin\PluginEvents; use Composer\Plugin\PreFileDownloadEvent; use Composer\EventDispatcher\EventDispatcher; use Composer\Util\Filesystem; use Composer\Util\RemoteFilesystem; use Composer\Util\Url as UrlUtil; /** * Base downloader for files * * @author Kirill chEbba Chebunin * @author Jordi Boggiano * @author François Pluchino * @author Nils Adermann */ class FileDownloader implements DownloaderInterface { protected $io; protected $config; protected $rfs; protected $filesystem; protected $cache; protected $outputProgress = true; private $lastCacheWrites = array(); private $eventDispatcher; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The config * @param EventDispatcher $eventDispatcher The event dispatcher * @param Cache $cache Optional cache instance * @param RemoteFilesystem $rfs The remote filesystem * @param Filesystem $filesystem The filesystem */ public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, RemoteFilesystem $rfs = null, Filesystem $filesystem = null) { $this->io = $io; $this->config = $config; $this->eventDispatcher = $eventDispatcher; $this->rfs = $rfs ?: Factory::createRemoteFilesystem($this->io, $config); $this->filesystem = $filesystem ?: new Filesystem(); $this->cache = $cache; if ($this->cache && $this->cache->gcIsNecessary()) { $this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize')); } } /** * {@inheritDoc} */ public function getInstallationSource() { return 'dist'; } /** * {@inheritDoc} */ public function download(PackageInterface $package, $path, $output = true) { if (!$package->getDistUrl()) { throw new \InvalidArgumentException('The given package is missing url information'); } if ($output) { $this->io->writeError(" - Installing " . $package->getName() . " (" . $package->getFullPrettyVersion() . "): ", false); } $urls = $package->getDistUrls(); while ($url = array_shift($urls)) { try { $fileName = $this->doDownload($package, $path, $url); break; } catch (\Exception $e) { if ($this->io->isDebug()) { $this->io->writeError(''); $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage()); } elseif (count($urls)) { $this->io->writeError(''); $this->io->writeError(' Failed, trying the next URL ('.$e->getCode().': '.$e->getMessage().')', false); } if (!count($urls)) { throw $e; } } } if ($output) { $this->io->writeError(''); } return $fileName; } protected function doDownload(PackageInterface $package, $path, $url) { $this->filesystem->emptyDirectory($path); $fileName = $this->getFileName($package, $path); $processedUrl = $this->processUrl($package, $url); $hostname = parse_url($processedUrl, PHP_URL_HOST); $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl); if ($this->eventDispatcher) { $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent); } $rfs = $preFileDownloadEvent->getRemoteFilesystem(); try { $checksum = $package->getDistSha1Checksum(); $cacheKey = $this->getCacheKey($package, $processedUrl); // download if we don't have it in cache or the cache is invalidated if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) { if (!$this->outputProgress) { $this->io->writeError('Downloading', false); } // try to download 3 times then fail hard $retries = 3; while ($retries--) { try { $rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions()); break; } catch (TransportException $e) { // if we got an http response with a proper code, then requesting again will probably not help, abort if ((0 !== $e->getCode() && !in_array($e->getCode(), array(500, 502, 503, 504))) || !$retries) { throw $e; } $this->io->writeError(''); $this->io->writeError(' Download failed, retrying...', true, IOInterface::VERBOSE); usleep(500000); } } if (!$this->outputProgress) { $this->io->writeError(' (100%)', false); } if ($this->cache) { $this->lastCacheWrites[$package->getName()] = $cacheKey; $this->cache->copyFrom($cacheKey, $fileName); } } else { $this->io->writeError('Loading from cache', false); } if (!file_exists($fileName)) { throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the' .' directory is writable and you have internet connectivity'); } if ($checksum && hash_file('sha1', $fileName) !== $checksum) { throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')'); } } catch (\Exception $e) { // clean up $this->filesystem->removeDirectory($path); $this->clearLastCacheWrite($package); throw $e; } return $fileName; } /** * {@inheritDoc} */ public function setOutputProgress($outputProgress) { $this->outputProgress = $outputProgress; return $this; } protected function clearLastCacheWrite(PackageInterface $package) { if ($this->cache && isset($this->lastCacheWrites[$package->getName()])) { $this->cache->remove($this->lastCacheWrites[$package->getName()]); unset($this->lastCacheWrites[$package->getName()]); } } /** * {@inheritDoc} */ public function update(PackageInterface $initial, PackageInterface $target, $path) { $name = $target->getName(); $from = $initial->getPrettyVersion(); $to = $target->getPrettyVersion(); $this->io->writeError(" - Updating " . $name . " (" . $from . " => " . $to . "): ", false); $this->remove($initial, $path, false); $this->download($target, $path, false); $this->io->writeError(''); } /** * {@inheritDoc} */ public function remove(PackageInterface $package, $path, $output = true) { if ($output) { $this->io->writeError(" - Removing " . $package->getName() . " (" . $package->getFullPrettyVersion() . ")"); } if (!$this->filesystem->removeDirectory($path)) { throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); } } /** * Gets file name for specific package * * @param PackageInterface $package package instance * @param string $path download path * @return string file name */ protected function getFileName(PackageInterface $package, $path) { return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME); } /** * Process the download url * * @param PackageInterface $package package the url is coming from * @param string $url download url * @throws \RuntimeException If any problem with the url * @return string url */ protected function processUrl(PackageInterface $package, $url) { if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) { throw new \RuntimeException('You must enable the openssl extension to download files via https'); } if ($package->getDistReference()) { $url = UrlUtil::updateDistReference($this->config, $url, $package->getDistReference()); } return $url; } private function getCacheKey(PackageInterface $package, $processedUrl) { // we use the complete download url here to avoid conflicting entries // from different packages, which would potentially allow a given package // in a third party repo to pre-populate the cache for the same package in // packagist for example. $cacheKey = sha1($processedUrl); return $package->getName().'/'.$cacheKey.'.'.$package->getDistType(); } } composer-1.6.3/src/Composer/Downloader/FilesystemException.php000066400000000000000000000012401323436022200245320ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; /** * Exception thrown when issues exist on local filesystem * * @author Javier Spagnoletti */ class FilesystemException extends \Exception { public function __construct($message = '', $code = 0, \Exception $previous = null) { parent::__construct("Filesystem exception: \n".$message, $code, $previous); } } composer-1.6.3/src/Composer/Downloader/FossilDownloader.php000066400000000000000000000076101323436022200240140ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Composer\Util\ProcessExecutor; /** * @author BohwaZ */ class FossilDownloader extends VcsDownloader { /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); $url = ProcessExecutor::escape($url); $ref = ProcessExecutor::escape($package->getSourceReference()); $repoFile = $path . '.fossil'; $this->io->writeError("Cloning ".$package->getSourceReference()); $command = sprintf('fossil clone %s %s', $url, ProcessExecutor::escape($repoFile)); if (0 !== $this->process->execute($command, $ignoredOutput)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $command = sprintf('fossil open %s', ProcessExecutor::escape($repoFile)); if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $command = sprintf('fossil update %s', $ref); if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } } /** * {@inheritDoc} */ public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); $url = ProcessExecutor::escape($url); $ref = ProcessExecutor::escape($target->getSourceReference()); $this->io->writeError(" Updating to ".$target->getSourceReference()); if (!$this->hasMetadataRepository($path)) { throw new \RuntimeException('The .fslckout file is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); } $command = sprintf('fossil pull && fossil up %s', $ref); if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } } /** * {@inheritDoc} */ public function getLocalChanges(PackageInterface $package, $path) { if (!$this->hasMetadataRepository($path)) { return null; } $this->process->execute('fossil changes', $output, realpath($path)); return trim($output) ?: null; } /** * {@inheritDoc} */ protected function getCommitLogs($fromReference, $toReference, $path) { $command = sprintf('fossil timeline -t ci -W 0 -n 0 before %s', $toReference); if (0 !== $this->process->execute($command, $output, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $log = ''; $match = '/\d\d:\d\d:\d\d\s+\[' . $toReference . '\]/'; foreach ($this->process->splitLines($output) as $line) { if (preg_match($match, $line)) { break; } $log .= $line; } return $log; } /** * {@inheritDoc} */ protected function hasMetadataRepository($path) { return is_file($path . '/.fslckout') || is_file($path . '/_FOSSIL_'); } } composer-1.6.3/src/Composer/Downloader/GitDownloader.php000066400000000000000000000466211323436022200233050ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Util\Filesystem; use Composer\Util\Git as GitUtil; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; /** * @author Jordi Boggiano */ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface { private $hasStashedChanges = false; private $hasDiscardedChanges = false; private $gitUtil; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null) { parent::__construct($io, $config, $process, $fs); $this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem); } /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); $cachePath = $this->config->get('cache-vcs-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $url).'/'; $ref = $package->getSourceReference(); $flag = Platform::isWindows() ? '/D ' : ''; // --dissociate option is only available since git 2.3.0-rc0 $gitVersion = $this->gitUtil->getVersion(); $msg = "Cloning ".$this->getShortHash($ref); $command = 'git clone --no-checkout %url% %path% && cd '.$flag.'%path% && git remote add composer %url% && git fetch composer'; if ($gitVersion && version_compare($gitVersion, '2.3.0-rc0', '>=')) { $this->io->writeError('', true, IOInterface::DEBUG); $this->io->writeError(sprintf(' Cloning to cache at %s', ProcessExecutor::escape($cachePath)), true, IOInterface::DEBUG); try { $this->gitUtil->fetchRefOrSyncMirror($url, $cachePath, $ref); if (is_dir($cachePath)) { $command = 'git clone --no-checkout %cachePath% %path% --dissociate --reference %cachePath% ' . '&& cd '.$flag.'%path% ' . '&& git remote set-url origin %url% && git remote add composer %url%'; $msg = "Cloning ".$this->getShortHash($ref).' from cache'; } } catch (\RuntimeException $e) { } } $this->io->writeError($msg); $commandCallable = function ($url) use ($path, $command, $cachePath) { return str_replace( array('%url%', '%path%', '%cachePath%'), array( ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($cachePath), ), $command ); }; $this->gitUtil->runCommand($commandCallable, $url, $path, true); if ($url !== $package->getSourceUrl()) { $this->updateOriginUrl($path, $package->getSourceUrl()); } else { $this->setPushUrl($path, $url); } if ($newRef = $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate())) { if ($package->getDistReference() === $package->getSourceReference()) { $package->setDistReference($newRef); } $package->setSourceReference($newRef); } } /** * {@inheritDoc} */ public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) { GitUtil::cleanEnv(); if (!$this->hasMetadataRepository($path)) { throw new \RuntimeException('The .git directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); } $updateOriginUrl = false; if ( 0 === $this->process->execute('git remote -v', $output, $path) && preg_match('{^origin\s+(?P\S+)}m', $output, $originMatch) && preg_match('{^composer\s+(?P\S+)}m', $output, $composerMatch) ) { if ($originMatch['url'] === $composerMatch['url'] && $composerMatch['url'] !== $target->getSourceUrl()) { $updateOriginUrl = true; } } $ref = $target->getSourceReference(); $this->io->writeError(" Checking out ".$this->getShortHash($ref)); $command = 'git remote set-url composer %s && git rev-parse --quiet --verify %s || (git fetch composer && git fetch --tags composer)'; $commandCallable = function ($url) use ($command, $ref) { return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($ref.'^{commit}')); }; $this->gitUtil->runCommand($commandCallable, $url, $path); if ($newRef = $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate())) { if ($target->getDistReference() === $target->getSourceReference()) { $target->setDistReference($newRef); } $target->setSourceReference($newRef); } if ($updateOriginUrl) { $this->updateOriginUrl($path, $target->getSourceUrl()); } } /** * {@inheritDoc} */ public function getLocalChanges(PackageInterface $package, $path) { GitUtil::cleanEnv(); if (!$this->hasMetadataRepository($path)) { return; } $command = 'git status --porcelain --untracked-files=no'; if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } return trim($output) ?: null; } public function getUnpushedChanges(PackageInterface $package, $path) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); if (!$this->hasMetadataRepository($path)) { return; } $command = 'git show-ref --head -d'; if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $refs = trim($output); if (!preg_match('{^([a-f0-9]+) HEAD$}mi', $refs, $match)) { // could not match the HEAD for some reason return; } $headRef = $match[1]; if (!preg_match_all('{^'.$headRef.' refs/heads/(.+)$}mi', $refs, $matches)) { // not on a branch, we are either on a not-modified tag or some sort of detached head, so skip this return; } // use the first match as branch name for now $branch = $matches[1][0]; $unpushedChanges = null; // do two passes, as if we find anything we want to fetch and then re-try for ($i = 0; $i <= 1; $i++) { // try to find the a matching branch name in the composer remote foreach ($matches[1] as $candidate) { if (preg_match('{^[a-f0-9]+ refs/remotes/((?:composer|origin)/'.preg_quote($candidate).')$}mi', $refs, $match)) { $branch = $candidate; $remoteBranch = $match[1]; break; } } // if it doesn't exist, then we assume it is an unpushed branch // this is bad as we have no reference point to do a diff so we just bail listing // the branch as being unpushed if (!isset($remoteBranch)) { $unpushedChanges = 'Branch ' . $branch . ' could not be found on the origin remote and appears to be unpushed'; } else { $command = sprintf('git diff --name-status %s...%s --', $remoteBranch, $branch); if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $unpushedChanges = trim($output) ?: null; } // first pass and we found unpushed changes, fetch from both remotes to make sure we have up to date // remotes and then try again as outdated remotes can sometimes cause false-positives if ($unpushedChanges && $i === 0) { $this->process->execute('git fetch composer && git fetch origin', $output, $path); } // abort after first pass if we didn't find anything if (!$unpushedChanges) { break; } } return $unpushedChanges; } /** * {@inheritDoc} */ protected function cleanChanges(PackageInterface $package, $path, $update) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); $unpushed = $this->getUnpushedChanges($package, $path); if ($unpushed && ($this->io->isInteractive() || $this->config->get('discard-changes') !== true)) { throw new \RuntimeException('Source directory ' . $path . ' has unpushed changes on the current branch: '."\n".$unpushed); } if (!$changes = $this->getLocalChanges($package, $path)) { return; } if (!$this->io->isInteractive()) { $discardChanges = $this->config->get('discard-changes'); if (true === $discardChanges) { return $this->discardChanges($path); } if ('stash' === $discardChanges) { if (!$update) { return parent::cleanChanges($package, $path, $update); } return $this->stashChanges($path); } return parent::cleanChanges($package, $path, $update); } $changes = array_map(function ($elem) { return ' '.$elem; }, preg_split('{\s*\r?\n\s*}', $changes)); $this->io->writeError(' The package has modified files:'); $this->io->writeError(array_slice($changes, 0, 10)); if (count($changes) > 10) { $this->io->writeError(' ' . (count($changes) - 10) . ' more files modified, choose "v" to view the full list'); } while (true) { switch ($this->io->ask(' Discard changes [y,n,v,d,'.($update ? 's,' : '').'?]? ', '?')) { case 'y': $this->discardChanges($path); break 2; case 's': if (!$update) { goto help; } $this->stashChanges($path); break 2; case 'n': throw new \RuntimeException('Update aborted'); case 'v': $this->io->writeError($changes); break; case 'd': $this->viewDiff($path); break; case '?': default: help: $this->io->writeError(array( ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'), ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up', ' v - view modified files', ' d - view local modifications (diff)', )); if ($update) { $this->io->writeError(' s - stash changes and try to reapply them after the update'); } $this->io->writeError(' ? - print help'); break; } } } /** * {@inheritDoc} */ protected function reapplyChanges($path) { $path = $this->normalizePath($path); if ($this->hasStashedChanges) { $this->hasStashedChanges = false; $this->io->writeError(' Re-applying stashed changes'); if (0 !== $this->process->execute('git stash pop', $output, $path)) { throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput()); } } $this->hasDiscardedChanges = false; } /** * Updates the given path to the given commit ref * * @param string $path * @param string $reference * @param string $branch * @param \DateTime $date * @throws \RuntimeException * @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found */ protected function updateToCommit($path, $reference, $branch, $date) { $force = $this->hasDiscardedChanges || $this->hasStashedChanges ? '-f ' : ''; // This uses the "--" sequence to separate branch from file parameters. // // Otherwise git tries the branch name as well as file name. // If the non-existent branch is actually the name of a file, the file // is checked out. $template = 'git checkout '.$force.'%s -- && git reset --hard %1$s --'; $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch); $branches = null; if (0 === $this->process->execute('git branch -r', $output, $path)) { $branches = $output; } // check whether non-commitish are branches or tags, and fetch branches with the remote name $gitRef = $reference; if (!preg_match('{^[a-f0-9]{40}$}', $reference) && $branches && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $branches) ) { $command = sprintf('git checkout '.$force.'-B %s %s -- && git reset --hard %2$s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$reference)); if (0 === $this->process->execute($command, $output, $path)) { return; } } // try to checkout branch by name and then reset it so it's on the proper branch name if (preg_match('{^[a-f0-9]{40}$}', $reference)) { // add 'v' in front of the branch if it was stripped when generating the pretty name if (!preg_match('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && preg_match('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) { $branch = 'v' . $branch; } $command = sprintf('git checkout %s --', ProcessExecutor::escape($branch)); $fallbackCommand = sprintf('git checkout '.$force.'-B %s %s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$branch)); if (0 === $this->process->execute($command, $output, $path) || 0 === $this->process->execute($fallbackCommand, $output, $path) ) { $command = sprintf('git reset --hard %s --', ProcessExecutor::escape($reference)); if (0 === $this->process->execute($command, $output, $path)) { return; } } } $command = sprintf($template, ProcessExecutor::escape($gitRef)); if (0 === $this->process->execute($command, $output, $path)) { return; } // reference was not found (prints "fatal: reference is not a tree: $ref") if (false !== strpos($this->process->getErrorOutput(), $reference)) { $this->io->writeError(' '.$reference.' is gone (history was rewritten?)'); } throw new \RuntimeException(GitUtil::sanitizeUrl('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput())); } protected function updateOriginUrl($path, $url) { $this->process->execute(sprintf('git remote set-url origin %s', ProcessExecutor::escape($url)), $output, $path); $this->setPushUrl($path, $url); } protected function setPushUrl($path, $url) { // set push url for github projects if (preg_match('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) { $protocols = $this->config->get('github-protocols'); $pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git'; if (!in_array('ssh', $protocols, true)) { $pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git'; } $cmd = sprintf('git remote set-url --push origin %s', ProcessExecutor::escape($pushUrl)); $this->process->execute($cmd, $ignoredOutput, $path); } } /** * {@inheritDoc} */ protected function getCommitLogs($fromReference, $toReference, $path) { $path = $this->normalizePath($path); $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference); if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } return $output; } /** * @param $path * @throws \RuntimeException */ protected function discardChanges($path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git reset --hard', $output, $path)) { throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput()); } $this->hasDiscardedChanges = true; } /** * @param $path * @throws \RuntimeException */ protected function stashChanges($path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git stash --include-untracked', $output, $path)) { throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput()); } $this->hasStashedChanges = true; } /** * @param $path * @throws \RuntimeException */ protected function viewDiff($path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git diff HEAD', $output, $path)) { throw new \RuntimeException("Could not view diff\n\n:".$this->process->getErrorOutput()); } $this->io->writeError($output); } protected function normalizePath($path) { if (Platform::isWindows() && strlen($path) > 0) { $basePath = $path; $removed = array(); while (!is_dir($basePath) && $basePath !== '\\') { array_unshift($removed, basename($basePath)); $basePath = dirname($basePath); } if ($basePath === '\\') { return $path; } $path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/'); } return $path; } /** * {@inheritDoc} */ protected function hasMetadataRepository($path) { $path = $this->normalizePath($path); return is_dir($path.'/.git'); } protected function getShortHash($reference) { if (!$this->io->isVerbose() && preg_match('{^[0-9a-f]{40}$}', $reference)) { return substr($reference, 0, 10); } return $reference; } } composer-1.6.3/src/Composer/Downloader/GzipDownloader.php000066400000000000000000000050521323436022200234640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Cache; use Composer\EventDispatcher\EventDispatcher; use Composer\Package\PackageInterface; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\IO\IOInterface; /** * GZip archive downloader. * * @author Pavel Puchkin */ class GzipDownloader extends ArchiveDownloader { protected $process; public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null, RemoteFilesystem $rfs = null) { $this->process = $process ?: new ProcessExecutor($io); parent::__construct($io, $config, $eventDispatcher, $cache, $rfs); } protected function extract($file, $path) { $targetFilepath = $path . DIRECTORY_SEPARATOR . basename(substr($file, 0, -3)); // Try to use gunzip on *nix if (!Platform::isWindows()) { $command = 'gzip -cd ' . ProcessExecutor::escape($file) . ' > ' . ProcessExecutor::escape($targetFilepath); if (0 === $this->process->execute($command, $ignoredOutput)) { return; } if (extension_loaded('zlib')) { // Fallback to using the PHP extension. $this->extractUsingExt($file, $targetFilepath); return; } $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(); throw new \RuntimeException($processError); } // Windows version of PHP has built-in support of gzip functions $this->extractUsingExt($file, $targetFilepath); } /** * {@inheritdoc} */ protected function getFileName(PackageInterface $package, $path) { return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME); } private function extractUsingExt($file, $targetFilepath) { $archiveFile = gzopen($file, 'rb'); $targetFile = fopen($targetFilepath, 'wb'); while ($string = gzread($archiveFile, 4096)) { fwrite($targetFile, $string, Platform::strlen($string)); } gzclose($archiveFile); fclose($targetFile); } } composer-1.6.3/src/Composer/Downloader/HgDownloader.php000066400000000000000000000063461323436022200231200ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Composer\Util\ProcessExecutor; /** * @author Per Bernhardt */ class HgDownloader extends VcsDownloader { /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); $url = ProcessExecutor::escape($url); $ref = ProcessExecutor::escape($package->getSourceReference()); $this->io->writeError("Cloning ".$package->getSourceReference()); $command = sprintf('hg clone %s %s', $url, ProcessExecutor::escape($path)); if (0 !== $this->process->execute($command, $ignoredOutput)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } $command = sprintf('hg up %s', $ref); if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } } /** * {@inheritDoc} */ public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); $url = ProcessExecutor::escape($url); $ref = ProcessExecutor::escape($target->getSourceReference()); $this->io->writeError(" Updating to ".$target->getSourceReference()); if (!$this->hasMetadataRepository($path)) { throw new \RuntimeException('The .hg directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); } $command = sprintf('hg pull %s && hg up %s', $url, $ref); if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } } /** * {@inheritDoc} */ public function getLocalChanges(PackageInterface $package, $path) { if (!is_dir($path.'/.hg')) { return null; } $this->process->execute('hg st', $output, realpath($path)); return trim($output) ?: null; } /** * {@inheritDoc} */ protected function getCommitLogs($fromReference, $toReference, $path) { $command = sprintf('hg log -r %s:%s --style compact', $fromReference, $toReference); if (0 !== $this->process->execute($command, $output, realpath($path))) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } return $output; } /** * {@inheritDoc} */ protected function hasMetadataRepository($path) { return is_dir($path . '/.hg'); } } composer-1.6.3/src/Composer/Downloader/PathDownloader.php000066400000000000000000000156561323436022200234620ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\Archiver\ArchivableFilesFinder; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem as ComposerFilesystem; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; /** * Download a package from a local path. * * @author Samuel Roze * @author Johann Reinke */ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInterface { const STRATEGY_SYMLINK = 10; const STRATEGY_MIRROR = 20; /** * {@inheritdoc} */ public function download(PackageInterface $package, $path, $output = true) { $url = $package->getDistUrl(); $realUrl = realpath($url); if (false === $realUrl || !file_exists($realUrl) || !is_dir($realUrl)) { throw new \RuntimeException(sprintf( 'Source path "%s" is not found for package %s', $url, $package->getName() )); } if (strpos(realpath($path) . DIRECTORY_SEPARATOR, $realUrl . DIRECTORY_SEPARATOR) === 0) { // IMPORTANT NOTICE: If you wish to change this, don't. You are wasting your time and ours. // // Please see https://github.com/composer/composer/pull/5974 and https://github.com/composer/composer/pull/6174 // for previous attempts that were shut down because they did not work well enough or introduced too many risks. throw new \RuntimeException(sprintf( 'Package %s cannot install to "%s" inside its source at "%s"', $package->getName(), realpath($path), $realUrl )); } // Get the transport options with default values $transportOptions = $package->getTransportOptions() + array('symlink' => null); // When symlink transport option is null, both symlink and mirror are allowed $currentStrategy = self::STRATEGY_SYMLINK; $allowedStrategies = array(self::STRATEGY_SYMLINK, self::STRATEGY_MIRROR); $mirrorPathRepos = getenv('COMPOSER_MIRROR_PATH_REPOS'); if ($mirrorPathRepos) { $currentStrategy = self::STRATEGY_MIRROR; } if (true === $transportOptions['symlink']) { $currentStrategy = self::STRATEGY_SYMLINK; $allowedStrategies = array(self::STRATEGY_SYMLINK); } elseif (false === $transportOptions['symlink']) { $currentStrategy = self::STRATEGY_MIRROR; $allowedStrategies = array(self::STRATEGY_MIRROR); } $fileSystem = new Filesystem(); $this->filesystem->removeDirectory($path); if ($output) { $this->io->writeError(sprintf( ' - Installing %s (%s): ', $package->getName(), $package->getFullPrettyVersion() ), false); } $isFallback = false; if (self::STRATEGY_SYMLINK == $currentStrategy) { try { if (Platform::isWindows()) { // Implement symlinks as NTFS junctions on Windows $this->io->writeError(sprintf('Junctioning from %s', $url), false); $this->filesystem->junction($realUrl, $path); } else { $absolutePath = $path; if (!$this->filesystem->isAbsolutePath($absolutePath)) { $absolutePath = getcwd() . DIRECTORY_SEPARATOR . $path; } $shortestPath = $this->filesystem->findShortestPath($absolutePath, $realUrl); $path = rtrim($path, "/"); $this->io->writeError(sprintf('Symlinking from %s', $url), false); $fileSystem->symlink($shortestPath, $path); } } catch (IOException $e) { if (in_array(self::STRATEGY_MIRROR, $allowedStrategies)) { $this->io->writeError(''); $this->io->writeError(' Symlink failed, fallback to use mirroring!'); $currentStrategy = self::STRATEGY_MIRROR; $isFallback = true; } else { throw new \RuntimeException(sprintf('Symlink from "%s" to "%s" failed!', $realUrl, $path)); } } } // Fallback if symlink failed or if symlink is not allowed for the package if (self::STRATEGY_MIRROR == $currentStrategy) { $fs = new ComposerFilesystem(); $realUrl = $fs->normalizePath($realUrl); $this->io->writeError(sprintf('%sMirroring from %s', $isFallback ? ' ' : '', $url), false); $iterator = new ArchivableFilesFinder($realUrl, array()); $fileSystem->mirror($realUrl, $path, $iterator); } $this->io->writeError(''); } /** * {@inheritDoc} */ public function remove(PackageInterface $package, $path, $output = true) { /** * For junctions don't blindly rely on Filesystem::removeDirectory as it may be overzealous. If a process * inadvertently locks the file the removal will fail, but it would fall back to recursive delete which * is disastrous within a junction. So in that case we have no other real choice but to fail hard. */ if (Platform::isWindows() && $this->filesystem->isJunction($path)) { if ($output) { $this->io->writeError(" - Removing junction for " . $package->getName() . " (" . $package->getFullPrettyVersion() . ")"); } if (!$this->filesystem->removeJunction($path)) { $this->io->writeError(" Could not remove junction at " . $path . " - is another process locking it?"); throw new \RuntimeException('Could not reliably remove junction for package ' . $package->getName()); } } else { parent::remove($package, $path, $output); } } /** * {@inheritDoc} */ public function getVcsReference(PackageInterface $package, $path) { $parser = new VersionParser; $guesser = new VersionGuesser($this->config, new ProcessExecutor($this->io), $parser); $dumper = new ArrayDumper; $packageConfig = $dumper->dump($package); if ($packageVersion = $guesser->guessVersion($packageConfig, $path)) { return $packageVersion['commit']; } } } composer-1.6.3/src/Composer/Downloader/PearPackageExtractor.php000066400000000000000000000266221323436022200246010ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Util\Filesystem; /** * Extractor for pear packages. * * Composer cannot rely on tar files structure when place it inside package target dir. Correct source files * disposition must be read from package.xml * This extract pear package source files to target dir. * * @author Alexey Prilipko */ class PearPackageExtractor { private static $rolesWithoutPackageNamePrefix = array('php', 'script', 'www'); /** @var Filesystem */ private $filesystem; private $file; public function __construct($file) { if (!is_file($file)) { throw new \UnexpectedValueException('PEAR package file is not found at '.$file); } $this->filesystem = new Filesystem(); $this->file = $file; } /** * Installs PEAR source files according to package.xml definitions and removes extracted files * * @param string $target target install location. all source installation would be performed relative to target path. * @param array $roles types of files to install. default role for PEAR source files are 'php'. * @param array $vars used for replacement tasks * @throws \RuntimeException * @throws \UnexpectedValueException */ public function extractTo($target, array $roles = array('php' => '/', 'script' => '/bin'), $vars = array()) { $extractionPath = $target.'/tarball'; try { $archive = new \PharData($this->file); $archive->extractTo($extractionPath, null, true); if (!is_file($this->combine($extractionPath, '/package.xml'))) { throw new \RuntimeException('Invalid PEAR package. It must contain package.xml file.'); } $fileCopyActions = $this->buildCopyActions($extractionPath, $roles, $vars); $this->copyFiles($fileCopyActions, $extractionPath, $target, $roles, $vars); $this->filesystem->removeDirectory($extractionPath); } catch (\Exception $exception) { throw new \UnexpectedValueException(sprintf('Failed to extract PEAR package %s to %s. Reason: %s', $this->file, $target, $exception->getMessage()), 0, $exception); } } /** * Perform copy actions on files * * @param array $files array of copy actions ('from', 'to') with relative paths * @param $source string path to source dir. * @param $target string path to destination dir * @param array $roles array [role => roleRoot] relative root for files having that role * @param array $vars list of values can be used for replacement tasks */ private function copyFiles($files, $source, $target, $roles, $vars) { foreach ($files as $file) { $from = $this->combine($source, $file['from']); $to = $this->combine($target, $roles[$file['role']]); $to = $this->combine($to, $file['to']); $tasks = $file['tasks']; $this->copyFile($from, $to, $tasks, $vars); } } private function copyFile($from, $to, $tasks, $vars) { if (!is_file($from)) { throw new \RuntimeException('Invalid PEAR package. package.xml defines file that is not located inside tarball.'); } $this->filesystem->ensureDirectoryExists(dirname($to)); if (0 == count($tasks)) { $copied = copy($from, $to); } else { $content = file_get_contents($from); $replacements = array(); foreach ($tasks as $task) { $pattern = $task['from']; $varName = $task['to']; if (isset($vars[$varName])) { if ($varName === 'php_bin' && false === strpos($to, '.bat')) { $replacements[$pattern] = preg_replace('{\.bat$}', '', $vars[$varName]); } else { $replacements[$pattern] = $vars[$varName]; } } } $content = strtr($content, $replacements); $copied = file_put_contents($to, $content); } if (false === $copied) { throw new \RuntimeException(sprintf('Failed to copy %s to %s', $from, $to)); } } /** * Builds list of copy and list of remove actions that would transform extracted PEAR tarball into installed package. * * @param string $source string path to extracted files * @param array $roles array [role => roleRoot] relative root for files having that role * @param array $vars list of values can be used for replacement tasks * @throws \RuntimeException * @return array array of 'source' => 'target', where source is location of file in the tarball (relative to source * path, and target is destination of file (also relative to $source path) */ private function buildCopyActions($source, array $roles, $vars) { /** @var $package \SimpleXmlElement */ $package = simplexml_load_string(file_get_contents($this->combine($source, 'package.xml'))); if (false === $package) { throw new \RuntimeException('Package definition file is not valid.'); } $packageSchemaVersion = $package['version']; if ('1.0' == $packageSchemaVersion) { $children = $package->release->filelist->children(); $packageName = (string) $package->name; $packageVersion = (string) $package->release->version; $sourceDir = $packageName . '-' . $packageVersion; $result = $this->buildSourceList10($children, $roles, $sourceDir, '', null, $packageName); } elseif ('2.0' == $packageSchemaVersion || '2.1' == $packageSchemaVersion) { $children = $package->contents->children(); $packageName = (string) $package->name; $packageVersion = (string) $package->version->release; $sourceDir = $packageName . '-' . $packageVersion; $result = $this->buildSourceList20($children, $roles, $sourceDir, '', null, $packageName); $namespaces = $package->getNamespaces(); $package->registerXPathNamespace('ns', $namespaces['']); $releaseNodes = $package->xpath('ns:phprelease'); $this->applyRelease($result, $releaseNodes, $vars); } else { throw new \RuntimeException('Unsupported schema version of package definition file.'); } return $result; } private function applyRelease(&$actions, $releaseNodes, $vars) { foreach ($releaseNodes as $releaseNode) { $requiredOs = $releaseNode->installconditions && $releaseNode->installconditions->os && $releaseNode->installconditions->os->name ? (string) $releaseNode->installconditions->os->name : ''; if ($requiredOs && $vars['os'] != $requiredOs) { continue; } if ($releaseNode->filelist) { foreach ($releaseNode->filelist->children() as $action) { if ('install' == $action->getName()) { $name = (string) $action['name']; $as = (string) $action['as']; if (isset($actions[$name])) { $actions[$name]['to'] = $as; } } elseif ('ignore' == $action->getName()) { $name = (string) $action['name']; unset($actions[$name]); } else { // unknown action } } } break; } } private function buildSourceList10($children, $targetRoles, $source, $target, $role, $packageName) { $result = array(); // enumerating files foreach ($children as $child) { /** @var $child \SimpleXMLElement */ if ($child->getName() == 'dir') { $dirSource = $this->combine($source, (string) $child['name']); $dirTarget = $child['baseinstalldir'] ?: $target; $dirRole = $child['role'] ?: $role; $dirFiles = $this->buildSourceList10($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName); $result = array_merge($result, $dirFiles); } elseif ($child->getName() == 'file') { $fileRole = (string) $child['role'] ?: $role; if (isset($targetRoles[$fileRole])) { $fileName = (string) ($child['name'] ?: $child[0]); // $child[0] means text content $fileSource = $this->combine($source, $fileName); $fileTarget = $this->combine((string) $child['baseinstalldir'] ?: $target, $fileName); if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) { $fileTarget = $packageName . '/' . $fileTarget; } $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => array()); } } } return $result; } private function buildSourceList20($children, $targetRoles, $source, $target, $role, $packageName) { $result = array(); // enumerating files foreach ($children as $child) { /** @var $child \SimpleXMLElement */ if ('dir' == $child->getName()) { $dirSource = $this->combine($source, $child['name']); $dirTarget = $child['baseinstalldir'] ?: $target; $dirRole = $child['role'] ?: $role; $dirFiles = $this->buildSourceList20($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName); $result = array_merge($result, $dirFiles); } elseif ('file' == $child->getName()) { $fileRole = (string) $child['role'] ?: $role; if (isset($targetRoles[$fileRole])) { $fileSource = $this->combine($source, (string) $child['name']); $fileTarget = $this->combine((string) ($child['baseinstalldir'] ?: $target), (string) $child['name']); $fileTasks = array(); foreach ($child->children('http://pear.php.net/dtd/tasks-1.0') as $taskNode) { if ('replace' == $taskNode->getName()) { $fileTasks[] = array('from' => (string) $taskNode->attributes()->from, 'to' => (string) $taskNode->attributes()->to); } } if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) { $fileTarget = $packageName . '/' . $fileTarget; } $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => $fileTasks); } } } return $result; } private function combine($left, $right) { return rtrim($left, '/') . '/' . ltrim($right, '/'); } } composer-1.6.3/src/Composer/Downloader/PerforceDownloader.php000066400000000000000000000054441323436022200243250ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Composer\Repository\VcsRepository; use Composer\Util\Perforce; /** * @author Matt Whittom */ class PerforceDownloader extends VcsDownloader { /** @var Perforce */ protected $perforce; /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { $ref = $package->getSourceReference(); $label = $this->getLabelFromSourceReference($ref); $this->io->writeError('Cloning ' . $ref); $this->initPerforce($package, $path, $url); $this->perforce->setStream($ref); $this->perforce->p4Login(); $this->perforce->writeP4ClientSpec(); $this->perforce->connectClient(); $this->perforce->syncCodeBase($label); $this->perforce->cleanupClientSpec(); } private function getLabelFromSourceReference($ref) { $pos = strpos($ref, '@'); if (false !== $pos) { return substr($ref, $pos + 1); } return null; } public function initPerforce(PackageInterface $package, $path, $url) { if (!empty($this->perforce)) { $this->perforce->initializePath($path); return; } $repository = $package->getRepository(); $repoConfig = null; if ($repository instanceof VcsRepository) { $repoConfig = $this->getRepoConfig($repository); } $this->perforce = Perforce::create($repoConfig, $url, $path, $this->process, $this->io); } private function getRepoConfig(VcsRepository $repository) { return $repository->getRepoConfig(); } /** * {@inheritDoc} */ public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) { $this->doDownload($target, $path, $url); } /** * {@inheritDoc} */ public function getLocalChanges(PackageInterface $package, $path) { $this->io->writeError('Perforce driver does not check for local changes before overriding', true); return; } /** * {@inheritDoc} */ protected function getCommitLogs($fromReference, $toReference, $path) { return $this->perforce->getCommitLogs($fromReference, $toReference); } public function setPerforce($perforce) { $this->perforce = $perforce; } /** * {@inheritDoc} */ protected function hasMetadataRepository($path) { return true; } } composer-1.6.3/src/Composer/Downloader/PharDownloader.php000066400000000000000000000016511323436022200234460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; /** * Downloader for phar files * * @author Kirill chEbba Chebunin */ class PharDownloader extends ArchiveDownloader { /** * {@inheritDoc} */ protected function extract($file, $path) { // Can throw an UnexpectedValueException $archive = new \Phar($file); $archive->extractTo($path, null, true); /* TODO: handle openssl signed phars * https://github.com/composer/composer/pull/33#issuecomment-2250768 * https://github.com/koto/phar-util * http://blog.kotowicz.net/2010/08/hardening-php-how-to-securely-include.html */ } } composer-1.6.3/src/Composer/Downloader/RarDownloader.php000066400000000000000000000054461323436022200233060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Cache; use Composer\EventDispatcher\EventDispatcher; use Composer\Util\IniHelper; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\IO\IOInterface; use RarArchive; /** * RAR archive downloader. * * Based on previous work by Jordi Boggiano ({@see ZipDownloader}). * * @author Derrick Nelson */ class RarDownloader extends ArchiveDownloader { protected $process; public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null, RemoteFilesystem $rfs = null) { $this->process = $process ?: new ProcessExecutor($io); parent::__construct($io, $config, $eventDispatcher, $cache, $rfs); } protected function extract($file, $path) { $processError = null; // Try to use unrar on *nix if (!Platform::isWindows()) { $command = 'unrar x ' . ProcessExecutor::escape($file) . ' ' . ProcessExecutor::escape($path) . ' >/dev/null && chmod -R u+w ' . ProcessExecutor::escape($path); if (0 === $this->process->execute($command, $ignoredOutput)) { return; } $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(); } if (!class_exists('RarArchive')) { // php.ini path is added to the error message to help users find the correct file $iniMessage = IniHelper::getMessage(); $error = "Could not decompress the archive, enable the PHP rar extension or install unrar.\n" . $iniMessage . "\n" . $processError; if (!Platform::isWindows()) { $error = "Could not decompress the archive, enable the PHP rar extension.\n" . $iniMessage; } throw new \RuntimeException($error); } $rarArchive = RarArchive::open($file); if (false === $rarArchive) { throw new \UnexpectedValueException('Could not open RAR archive: ' . $file); } $entries = $rarArchive->getEntries(); if (false === $entries) { throw new \RuntimeException('Could not retrieve RAR archive entries'); } foreach ($entries as $entry) { if (false === $entry->extract($path)) { throw new \RuntimeException('Could not extract entry'); } } $rarArchive->close(); } } composer-1.6.3/src/Composer/Downloader/SvnDownloader.php000066400000000000000000000173211323436022200233230ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; use Composer\Util\Svn as SvnUtil; use Composer\Repository\VcsRepository; use Composer\Util\ProcessExecutor; /** * @author Ben Bieker * @author Till Klampaeckel */ class SvnDownloader extends VcsDownloader { protected $cacheCredentials = true; /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { SvnUtil::cleanEnv(); $ref = $package->getSourceReference(); $repo = $package->getRepository(); if ($repo instanceof VcsRepository) { $repoConfig = $repo->getRepoConfig(); if (array_key_exists('svn-cache-credentials', $repoConfig)) { $this->cacheCredentials = (bool) $repoConfig['svn-cache-credentials']; } } $this->io->writeError(" Checking out ".$package->getSourceReference()); $this->execute($url, "svn co", sprintf("%s/%s", $url, $ref), null, $path); } /** * {@inheritDoc} */ public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) { SvnUtil::cleanEnv(); $ref = $target->getSourceReference(); if (!$this->hasMetadataRepository($path)) { throw new \RuntimeException('The .svn directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); } $flags = ""; if (0 === $this->process->execute('svn --version', $output)) { if (preg_match('{(\d+(?:\.\d+)+)}', $output, $match) && version_compare($match[1], '1.7.0', '>=')) { $flags .= ' --ignore-ancestry'; } } $this->io->writeError(" Checking out " . $ref); $this->execute($url, "svn switch" . $flags, sprintf("%s/%s", $url, $ref), $path); } /** * {@inheritDoc} */ public function getLocalChanges(PackageInterface $package, $path) { if (!$this->hasMetadataRepository($path)) { return null; } $this->process->execute('svn status --ignore-externals', $output, $path); return preg_match('{^ *[^X ] +}m', $output) ? $output : null; } /** * Execute an SVN command and try to fix up the process with credentials * if necessary. * * @param string $baseUrl Base URL of the repository * @param string $command SVN command to run * @param string $url SVN url * @param string $cwd Working directory * @param string $path Target for a checkout * @throws \RuntimeException * @return string */ protected function execute($baseUrl, $command, $url, $cwd = null, $path = null) { $util = new SvnUtil($baseUrl, $this->io, $this->config); $util->setCacheCredentials($this->cacheCredentials); try { return $util->execute($command, $url, $cwd, $path, $this->io->isVerbose()); } catch (\RuntimeException $e) { throw new \RuntimeException( 'Package could not be downloaded, '.$e->getMessage() ); } } /** * {@inheritDoc} */ protected function cleanChanges(PackageInterface $package, $path, $update) { if (!$changes = $this->getLocalChanges($package, $path)) { return; } if (!$this->io->isInteractive()) { if (true === $this->config->get('discard-changes')) { return $this->discardChanges($path); } return parent::cleanChanges($package, $path, $update); } $changes = array_map(function ($elem) { return ' '.$elem; }, preg_split('{\s*\r?\n\s*}', $changes)); $countChanges = count($changes); $this->io->writeError(sprintf(' The package has modified file%s:', $countChanges === 1 ? '' : 's')); $this->io->writeError(array_slice($changes, 0, 10)); if ($countChanges > 10) { $remaingChanges = $countChanges - 10; $this->io->writeError( sprintf( ' '.$remaingChanges.' more file%s modified, choose "v" to view the full list', $remaingChanges === 1 ? '' : 's' ) ); } while (true) { switch ($this->io->ask(' Discard changes [y,n,v,?]? ', '?')) { case 'y': $this->discardChanges($path); break 2; case 'n': throw new \RuntimeException('Update aborted'); case 'v': $this->io->writeError($changes); break; case '?': default: $this->io->writeError(array( ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'), ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up', ' v - view modified files', ' ? - print help', )); break; } } } /** * {@inheritDoc} */ protected function getCommitLogs($fromReference, $toReference, $path) { if (preg_match('{.*@(\d+)$}', $fromReference) && preg_match('{.*@(\d+)$}', $toReference)) { // retrieve the svn base url from the checkout folder $command = sprintf('svn info --non-interactive --xml %s', ProcessExecutor::escape($path)); if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException( 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput() ); } $urlPattern = '#(.*)#'; if (preg_match($urlPattern, $output, $matches)) { $baseUrl = $matches[1]; } else { throw new \RuntimeException( 'Unable to determine svn url for path '. $path ); } // strip paths from references and only keep the actual revision $fromRevision = preg_replace('{.*@(\d+)$}', '$1', $fromReference); $toRevision = preg_replace('{.*@(\d+)$}', '$1', $toReference); $command = sprintf('svn log -r%s:%s --incremental', $fromRevision, $toRevision); $util = new SvnUtil($baseUrl, $this->io, $this->config); $util->setCacheCredentials($this->cacheCredentials); try { return $util->executeLocal($command, $path, null, $this->io->isVerbose()); } catch (\RuntimeException $e) { throw new \RuntimeException( 'Failed to execute ' . $command . "\n\n".$e->getMessage() ); } } return "Could not retrieve changes between $fromReference and $toReference due to missing revision information"; } protected function discardChanges($path) { if (0 !== $this->process->execute('svn revert -R .', $output, $path)) { throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput()); } } /** * {@inheritDoc} */ protected function hasMetadataRepository($path) { return is_dir($path.'/.svn'); } } composer-1.6.3/src/Composer/Downloader/TarDownloader.php000066400000000000000000000012711323436022200233000ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; /** * Downloader for tar files: tar, tar.gz or tar.bz2 * * @author Kirill chEbba Chebunin */ class TarDownloader extends ArchiveDownloader { /** * {@inheritDoc} */ protected function extract($file, $path) { // Can throw an UnexpectedValueException $archive = new \PharData($file); $archive->extractTo($path, null, true); } } composer-1.6.3/src/Composer/Downloader/TransportException.php000066400000000000000000000017611323436022200244120ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; /** * @author Jordi Boggiano */ class TransportException extends \RuntimeException { protected $headers; protected $response; protected $statusCode; public function setHeaders($headers) { $this->headers = $headers; } public function getHeaders() { return $this->headers; } public function setResponse($response) { $this->response = $response; } public function getResponse() { return $this->response; } public function setStatusCode($statusCode) { $this->statusCode = $statusCode; } public function getStatusCode() { return $this->statusCode; } } composer-1.6.3/src/Composer/Downloader/VcsCapableDownloaderInterface.php000066400000000000000000000014331323436022200263760ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * VCS Capable Downloader interface. * * @author Steve Buzonas */ interface VcsCapableDownloaderInterface { /** * Gets the VCS Reference for the package at path * * @param PackageInterface $package package directory * @param string $path package directory * @return string|null reference or null */ public function getVcsReference(PackageInterface $package, $path); } composer-1.6.3/src/Composer/Downloader/VcsDownloader.php000066400000000000000000000244111323436022200233060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Util\ProcessExecutor; use Composer\IO\IOInterface; use Composer\Util\Filesystem; /** * @author Jordi Boggiano */ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterface, VcsCapableDownloaderInterface { /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var Filesystem */ protected $filesystem; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->filesystem = $fs ?: new Filesystem($this->process); } /** * {@inheritDoc} */ public function getInstallationSource() { return 'source'; } /** * {@inheritDoc} */ public function download(PackageInterface $package, $path) { if (!$package->getSourceReference()) { throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information'); } $this->io->writeError(" - Installing " . $package->getName() . " (" . $package->getFullPrettyVersion() . "): ", false); $this->filesystem->emptyDirectory($path); $urls = $package->getSourceUrls(); while ($url = array_shift($urls)) { try { if (Filesystem::isLocalPath($url)) { // realpath() below will not understand // url that starts with "file://" $needle = 'file://'; $isFileProtocol = false; if (0 === strpos($url, $needle)) { $url = substr($url, strlen($needle)); $isFileProtocol = true; } // realpath() below will not understand %20 spaces etc. if (false !== strpos($url, '%')) { $url = rawurldecode($url); } $url = realpath($url); if ($isFileProtocol) { $url = $needle . $url; } } $this->doDownload($package, $path, $url); break; } catch (\Exception $e) { // rethrow phpunit exceptions to avoid hard to debug bug failures if ($e instanceof \PHPUnit_Framework_Exception) { throw $e; } if ($this->io->isDebug()) { $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getMessage()); } elseif (count($urls)) { $this->io->writeError(' Failed, trying the next URL'); } if (!count($urls)) { throw $e; } } } } /** * {@inheritDoc} */ public function update(PackageInterface $initial, PackageInterface $target, $path) { if (!$target->getSourceReference()) { throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information'); } $name = $target->getName(); if ($initial->getPrettyVersion() == $target->getPrettyVersion()) { if ($target->getSourceType() === 'svn') { $from = $initial->getSourceReference(); $to = $target->getSourceReference(); } else { $from = substr($initial->getSourceReference(), 0, 7); $to = substr($target->getSourceReference(), 0, 7); } $name .= ' '.$initial->getPrettyVersion(); } else { $from = $initial->getFullPrettyVersion(); $to = $target->getFullPrettyVersion(); } $this->io->writeError(" - Updating " . $name . " (" . $from . " => " . $to . "): ", false); $this->cleanChanges($initial, $path, true); $urls = $target->getSourceUrls(); $exception = null; while ($url = array_shift($urls)) { try { if (Filesystem::isLocalPath($url)) { $url = realpath($url); } $this->doUpdate($initial, $target, $path, $url); $exception = null; break; } catch (\Exception $exception) { // rethrow phpunit exceptions to avoid hard to debug bug failures if ($exception instanceof \PHPUnit_Framework_Exception) { throw $exception; } if ($this->io->isDebug()) { $this->io->writeError('Failed: ['.get_class($exception).'] '.$exception->getMessage()); } elseif (count($urls)) { $this->io->writeError(' Failed, trying the next URL'); } } } $this->reapplyChanges($path); // print the commit logs if in verbose mode and VCS metadata is present // because in case of missing metadata code would trigger another exception if (!$exception && $this->io->isVerbose() && $this->hasMetadataRepository($path)) { $message = 'Pulling in changes:'; $logs = $this->getCommitLogs($initial->getSourceReference(), $target->getSourceReference(), $path); if (!trim($logs)) { $message = 'Rolling back changes:'; $logs = $this->getCommitLogs($target->getSourceReference(), $initial->getSourceReference(), $path); } if (trim($logs)) { $logs = implode("\n", array_map(function ($line) { return ' ' . $line; }, explode("\n", $logs))); // escape angle brackets for proper output in the console $logs = str_replace('<', '\<', $logs); $this->io->writeError(' '.$message); $this->io->writeError($logs); } } if (!$urls && $exception) { throw $exception; } } /** * {@inheritDoc} */ public function remove(PackageInterface $package, $path) { $this->io->writeError(" - Removing " . $package->getName() . " (" . $package->getPrettyVersion() . ")"); $this->cleanChanges($package, $path, false); if (!$this->filesystem->removeDirectory($path)) { throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); } } /** * Download progress information is not available for all VCS downloaders. * {@inheritDoc} */ public function setOutputProgress($outputProgress) { return $this; } /** * {@inheritDoc} */ public function getVcsReference(PackageInterface $package, $path) { $parser = new VersionParser; $guesser = new VersionGuesser($this->config, $this->process, $parser); $dumper = new ArrayDumper; $packageConfig = $dumper->dump($package); if ($packageVersion = $guesser->guessVersion($packageConfig, $path)) { return $packageVersion['commit']; } } /** * Prompt the user to check if changes should be stashed/removed or the operation aborted * * @param PackageInterface $package * @param string $path * @param bool $update if true (update) the changes can be stashed and reapplied after an update, * if false (remove) the changes should be assumed to be lost if the operation is not aborted * @throws \RuntimeException in case the operation must be aborted */ protected function cleanChanges(PackageInterface $package, $path, $update) { // the default implementation just fails if there are any changes, override in child classes to provide stash-ability if (null !== $this->getLocalChanges($package, $path)) { throw new \RuntimeException('Source directory ' . $path . ' has uncommitted changes.'); } } /** * Guarantee that no changes have been made to the local copy * * @param string $path * @throws \RuntimeException in case the operation must be aborted or the patch does not apply cleanly */ protected function reapplyChanges($path) { } /** * Downloads specific package into specific folder. * * @param PackageInterface $package package instance * @param string $path download path * @param string $url package url */ abstract protected function doDownload(PackageInterface $package, $path, $url); /** * Updates specific package in specific folder from initial to target version. * * @param PackageInterface $initial initial package * @param PackageInterface $target updated package * @param string $path download path * @param string $url package url */ abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url); /** * Fetches the commit logs between two commits * * @param string $fromReference the source reference * @param string $toReference the target reference * @param string $path the package path * @return string */ abstract protected function getCommitLogs($fromReference, $toReference, $path); /** * Checks if VCS metadata repository has been initialized * repository example: .git|.svn|.hg * * @param string $path * @return bool */ abstract protected function hasMetadataRepository($path); } composer-1.6.3/src/Composer/Downloader/XzDownloader.php000066400000000000000000000032631323436022200231560ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Cache; use Composer\EventDispatcher\EventDispatcher; use Composer\Package\PackageInterface; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\IO\IOInterface; /** * Xz archive downloader. * * @author Pavel Puchkin * @author Pierre Rudloff */ class XzDownloader extends ArchiveDownloader { protected $process; public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null, RemoteFilesystem $rfs = null) { $this->process = $process ?: new ProcessExecutor($io); parent::__construct($io, $config, $eventDispatcher, $cache, $rfs); } protected function extract($file, $path) { $command = 'tar -xJf ' . ProcessExecutor::escape($file) . ' -C ' . ProcessExecutor::escape($path); if (0 === $this->process->execute($command, $ignoredOutput)) { return; } $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(); throw new \RuntimeException($processError); } /** * {@inheritdoc} */ protected function getFileName(PackageInterface $package, $path) { return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME); } } composer-1.6.3/src/Composer/Downloader/ZipDownloader.php000066400000000000000000000176441323436022200233270ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Config; use Composer\Cache; use Composer\EventDispatcher\EventDispatcher; use Composer\Package\PackageInterface; use Composer\Util\IniHelper; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\IO\IOInterface; use Symfony\Component\Process\ExecutableFinder; use ZipArchive; /** * @author Jordi Boggiano */ class ZipDownloader extends ArchiveDownloader { protected static $hasSystemUnzip; private static $hasZipArchive; private static $isWindows; protected $process; private $zipArchiveObject; public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null, RemoteFilesystem $rfs = null) { $this->process = $process ?: new ProcessExecutor($io); parent::__construct($io, $config, $eventDispatcher, $cache, $rfs); } /** * {@inheritDoc} */ public function download(PackageInterface $package, $path, $output = true) { if (null === self::$hasSystemUnzip) { $finder = new ExecutableFinder; self::$hasSystemUnzip = (bool) $finder->find('unzip'); } if (null === self::$hasZipArchive) { self::$hasZipArchive = class_exists('ZipArchive'); } if (null === self::$isWindows) { self::$isWindows = Platform::isWindows(); } if (!self::$hasZipArchive && !self::$hasSystemUnzip) { // php.ini path is added to the error message to help users find the correct file $iniMessage = IniHelper::getMessage(); $error = "The zip extension and unzip command are both missing, skipping.\n" . $iniMessage; throw new \RuntimeException($error); } return parent::download($package, $path, $output); } /** * extract $file to $path with "unzip" command * * @param string $file File to extract * @param string $path Path where to extract file * @param bool $isLastChance If true it is called as a fallback and should throw an exception * @return bool Success status */ protected function extractWithSystemUnzip($file, $path, $isLastChance) { if (!self::$hasZipArchive) { // Force Exception throwing if the Other alternative is not available $isLastChance = true; } if (!self::$hasSystemUnzip && !$isLastChance) { // This was call as the favorite extract way, but is not available // We switch to the alternative return $this->extractWithZipArchive($file, $path, true); } $processError = null; // When called after a ZipArchive failed, perhaps there is some files to overwrite $overwrite = $isLastChance ? '-o' : ''; $command = 'unzip -qq '.$overwrite.' '.ProcessExecutor::escape($file).' -d '.ProcessExecutor::escape($path); try { if (0 === $this->process->execute($command, $ignoredOutput)) { return true; } $processError = new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } catch (\Exception $e) { $processError = $e; } if ($isLastChance) { throw $processError; } $this->io->writeError(' '.$processError->getMessage()); $this->io->writeError(' The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems)'); $this->io->writeError(' Unzip with unzip command failed, falling back to ZipArchive class'); return $this->extractWithZipArchive($file, $path, true); } /** * extract $file to $path with ZipArchive * * @param string $file File to extract * @param string $path Path where to extract file * @param bool $isLastChance If true it is called as a fallback and should throw an exception * @return bool Success status */ protected function extractWithZipArchive($file, $path, $isLastChance) { if (!self::$hasSystemUnzip) { // Force Exception throwing if the Other alternative is not available $isLastChance = true; } if (!self::$hasZipArchive && !$isLastChance) { // This was call as the favorite extract way, but is not available // We switch to the alternative return $this->extractWithSystemUnzip($file, $path, true); } $processError = null; $zipArchive = $this->zipArchiveObject ?: new ZipArchive(); try { if (true === ($retval = $zipArchive->open($file))) { $extractResult = $zipArchive->extractTo($path); if (true === $extractResult) { $zipArchive->close(); return true; } $processError = new \RuntimeException(rtrim("There was an error extracting the ZIP file, it is either corrupted or using an invalid format.\n")); } else { $processError = new \UnexpectedValueException(rtrim($this->getErrorMessage($retval, $file)."\n"), $retval); } } catch (\ErrorException $e) { $processError = new \RuntimeException('The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems): '.$e->getMessage(), 0, $e); } catch (\Exception $e) { $processError = $e; } if ($isLastChance) { throw $processError; } $this->io->writeError(' '.$processError->getMessage()); $this->io->writeError(' Unzip with ZipArchive class failed, falling back to unzip command'); return $this->extractWithSystemUnzip($file, $path, true); } /** * extract $file to $path * * @param string $file File to extract * @param string $path Path where to extract file */ public function extract($file, $path) { // Each extract calls its alternative if not available or fails if (self::$isWindows) { $this->extractWithZipArchive($file, $path, false); } else { $this->extractWithSystemUnzip($file, $path, false); } } /** * Give a meaningful error message to the user. * * @param int $retval * @param string $file * @return string */ protected function getErrorMessage($retval, $file) { switch ($retval) { case ZipArchive::ER_EXISTS: return sprintf("File '%s' already exists.", $file); case ZipArchive::ER_INCONS: return sprintf("Zip archive '%s' is inconsistent.", $file); case ZipArchive::ER_INVAL: return sprintf("Invalid argument (%s)", $file); case ZipArchive::ER_MEMORY: return sprintf("Malloc failure (%s)", $file); case ZipArchive::ER_NOENT: return sprintf("No such zip file: '%s'", $file); case ZipArchive::ER_NOZIP: return sprintf("'%s' is not a zip archive.", $file); case ZipArchive::ER_OPEN: return sprintf("Can't open zip file: %s", $file); case ZipArchive::ER_READ: return sprintf("Zip read error (%s)", $file); case ZipArchive::ER_SEEK: return sprintf("Zip seek error (%s)", $file); default: return sprintf("'%s' is not a valid zip archive, got error code: %s", $file, $retval); } } } composer-1.6.3/src/Composer/EventDispatcher/000077500000000000000000000000001323436022200210135ustar00rootroot00000000000000composer-1.6.3/src/Composer/EventDispatcher/Event.php000066400000000000000000000041461323436022200226120ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\EventDispatcher; /** * The base event class * * @author Nils Adermann */ class Event { /** * @var string This event's name */ protected $name; /** * @var array Arguments passed by the user, these will be forwarded to CLI script handlers */ protected $args; /** * @var array Flags usable in PHP script handlers */ protected $flags; /** * @var bool Whether the event should not be passed to more listeners */ private $propagationStopped = false; /** * Constructor. * * @param string $name The event name * @param array $args Arguments passed by the user * @param array $flags Optional flags to pass data not as argument */ public function __construct($name, array $args = array(), array $flags = array()) { $this->name = $name; $this->args = $args; $this->flags = $flags; } /** * Returns the event's name. * * @return string The event name */ public function getName() { return $this->name; } /** * Returns the event's arguments. * * @return array The event arguments */ public function getArguments() { return $this->args; } /** * Returns the event's flags. * * @return array The event flags */ public function getFlags() { return $this->flags; } /** * Checks if stopPropagation has been called * * @return bool Whether propagation has been stopped */ public function isPropagationStopped() { return $this->propagationStopped; } /** * Prevents the event from being passed to further listeners */ public function stopPropagation() { $this->propagationStopped = true; } } composer-1.6.3/src/Composer/EventDispatcher/EventDispatcher.php000066400000000000000000000502421323436022200246170ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\EventDispatcher; use Composer\DependencyResolver\PolicyInterface; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Request; use Composer\Installer\InstallerEvent; use Composer\IO\IOInterface; use Composer\Composer; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\Repository\CompositeRepository; use Composer\Script; use Composer\Installer\PackageEvent; use Composer\Installer\BinaryInstaller; use Composer\Util\ProcessExecutor; use Composer\Script\Event as ScriptEvent; use Symfony\Component\Process\PhpExecutableFinder; /** * The Event Dispatcher. * * Example in command: * $dispatcher = new EventDispatcher($this->getComposer(), $this->getApplication()->getIO()); * // ... * $dispatcher->dispatch(ScriptEvents::POST_INSTALL_CMD); * // ... * * @author François Pluchino * @author Jordi Boggiano * @author Nils Adermann */ class EventDispatcher { protected $composer; protected $io; protected $loader; protected $process; protected $listeners; private $eventStack; /** * Constructor. * * @param Composer $composer The composer instance * @param IOInterface $io The IOInterface instance * @param ProcessExecutor $process */ public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null) { $this->composer = $composer; $this->io = $io; $this->process = $process ?: new ProcessExecutor($io); $this->eventStack = array(); } /** * Dispatch an event * * @param string $eventName An event name * @param Event $event * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatch($eventName, Event $event = null) { if (null === $event) { $event = new Event($eventName); } return $this->doDispatch($event); } /** * Dispatch a script event. * * @param string $eventName The constant in ScriptEvents * @param bool $devMode * @param array $additionalArgs Arguments passed by the user * @param array $flags Optional flags to pass data not as argument * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array()) { return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags)); } /** * Dispatch a package event. * * @param string $eventName The constant in PackageEvents * @param bool $devMode Whether or not we are in dev mode * @param PolicyInterface $policy The policy * @param Pool $pool The pool * @param CompositeRepository $installedRepo The installed repository * @param Request $request The request * @param array $operations The list of operations * @param OperationInterface $operation The package being installed/updated/removed * * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchPackageEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation) { return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations, $operation)); } /** * Dispatch a installer event. * * @param string $eventName The constant in InstallerEvents * @param bool $devMode Whether or not we are in dev mode * @param PolicyInterface $policy The policy * @param Pool $pool The pool * @param CompositeRepository $installedRepo The installed repository * @param Request $request The request * @param array $operations The list of operations * * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchInstallerEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array()) { return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations)); } /** * Triggers the listeners of an event. * * @param Event $event The event object to pass to the event handlers/listeners. * @throws \RuntimeException|\Exception * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ protected function doDispatch(Event $event) { $pathStr = 'PATH'; if (!isset($_SERVER[$pathStr]) && isset($_SERVER['Path'])) { $pathStr = 'Path'; } // add the bin dir to the PATH to make local binaries of deps usable in scripts $binDir = $this->composer->getConfig()->get('bin-dir'); if (is_dir($binDir)) { $binDir = realpath($binDir); if (isset($_SERVER[$pathStr]) && !preg_match('{(^|'.PATH_SEPARATOR.')'.preg_quote($binDir).'($|'.PATH_SEPARATOR.')}', $_SERVER[$pathStr])) { $_SERVER[$pathStr] = $binDir.PATH_SEPARATOR.getenv($pathStr); putenv($pathStr.'='.$_SERVER[$pathStr]); } } $listeners = $this->getListeners($event); $this->pushEvent($event); $return = 0; foreach ($listeners as $callable) { if (!is_string($callable) && is_callable($callable)) { $event = $this->checkListenerExpectedEvent($callable, $event); $return = false === call_user_func($callable, $event) ? 1 : 0; } elseif ($this->isComposerScript($callable)) { $this->io->writeError(sprintf('> %s: %s', $event->getName(), $callable), true, IOInterface::VERBOSE); $scriptName = substr($callable, 1); $args = $event->getArguments(); $flags = $event->getFlags(); if (substr($callable, 0, 10) === '@composer ') { $exec = $this->getPhpExecCommand() . ' ' . ProcessExecutor::escape(getenv('COMPOSER_BINARY')) . substr($callable, 9); if (0 !== ($exitCode = $this->process->execute($exec))) { $this->io->writeError(sprintf('Script %s handling the %s event returned with error code '.$exitCode.'', $callable, $event->getName()), true, IOInterface::QUIET); throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode); } } else { if (!$this->getListeners(new Event($scriptName))) { $this->io->writeError(sprintf('You made a reference to a non-existent script %s', $callable), true, IOInterface::QUIET); } $return = $this->dispatch($scriptName, new Script\Event($scriptName, $event->getComposer(), $event->getIO(), $event->isDevMode(), $args, $flags)); } } elseif ($this->isPhpScript($callable)) { $className = substr($callable, 0, strpos($callable, '::')); $methodName = substr($callable, strpos($callable, '::') + 2); if (!class_exists($className)) { $this->io->writeError('Class '.$className.' is not autoloadable, can not call '.$event->getName().' script', true, IOInterface::QUIET); continue; } if (!is_callable($callable)) { $this->io->writeError('Method '.$callable.' is not callable, can not call '.$event->getName().' script', true, IOInterface::QUIET); continue; } try { $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0; } catch (\Exception $e) { $message = "Script %s handling the %s event terminated with an exception"; $this->io->writeError(''.sprintf($message, $callable, $event->getName()).'', true, IOInterface::QUIET); throw $e; } } else { $args = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), $event->getArguments())); $exec = $callable . ($args === '' ? '' : ' '.$args); if ($this->io->isVerbose()) { $this->io->writeError(sprintf('> %s: %s', $event->getName(), $exec)); } else { $this->io->writeError(sprintf('> %s', $exec)); } $possibleLocalBinaries = $this->composer->getPackage()->getBinaries(); if ($possibleLocalBinaries) { foreach ($possibleLocalBinaries as $localExec) { if (preg_match('{\b'.preg_quote($callable).'$}', $localExec)) { $caller = BinaryInstaller::determineBinaryCaller($localExec); $exec = preg_replace('{^'.preg_quote($callable).'}', $caller . ' ' . $localExec, $exec); break; } } } if (substr($exec, 0, 5) === '@php ') { $exec = $this->getPhpExecCommand() . ' ' . substr($exec, 5); } if (0 !== ($exitCode = $this->process->execute($exec))) { $this->io->writeError(sprintf('Script %s handling the %s event returned with error code '.$exitCode.'', $callable, $event->getName()), true, IOInterface::QUIET); throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode); } } if ($event->isPropagationStopped()) { break; } } $this->popEvent(); return $return; } protected function getPhpExecCommand() { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(); if (!$phpPath) { throw new \RuntimeException('Failed to locate PHP binary to execute '.$scriptName); } $allowUrlFOpenFlag = ' -d allow_url_fopen=' . ProcessExecutor::escape(ini_get('allow_url_fopen')); $disableFunctionsFlag = ' -d disable_functions=' . ProcessExecutor::escape(ini_get('disable_functions')); $memoryLimitFlag = ' -d memory_limit=' . ProcessExecutor::escape(ini_get('memory_limit')); return ProcessExecutor::escape($phpPath) . $allowUrlFOpenFlag . $disableFunctionsFlag . $memoryLimitFlag; } /** * @param string $className * @param string $methodName * @param Event $event Event invoking the PHP callable */ protected function executeEventPhpScript($className, $methodName, Event $event) { $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event); if ($this->io->isVerbose()) { $this->io->writeError(sprintf('> %s: %s::%s', $event->getName(), $className, $methodName)); } else { $this->io->writeError(sprintf('> %s::%s', $className, $methodName)); } return $className::$methodName($event); } /** * @param mixed $target * @param Event $event * @return Event */ protected function checkListenerExpectedEvent($target, Event $event) { if (in_array($event->getName(), array( 'init', 'command', 'pre-file-download', ), true)) { return $event; } try { $reflected = new \ReflectionParameter($target, 0); } catch (\Exception $e) { return $event; } $typehint = $reflected->getClass(); if (!$typehint instanceof \ReflectionClass) { return $event; } $expected = $typehint->getName(); // BC support if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') { trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED); $event = new \Composer\Script\CommandEvent( $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments() ); } if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') { trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED); $event = new \Composer\Script\PackageEvent( $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(), $event->getOperations(), $event->getOperation() ); } if (!$event instanceof $expected && $expected === 'Composer\Script\Event') { trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED); $event = new \Composer\Script\Event( $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments(), $event->getFlags() ); } return $event; } private function serializeCallback($cb) { if (is_array($cb) && count($cb) === 2) { if (is_object($cb[0])) { $cb[0] = get_class($cb[0]); } if (is_string($cb[0]) && is_string($cb[1])) { $cb = implode('::', $cb); } } if (is_string($cb)) { return $cb; } return var_export($cb, true); } /** * Add a listener for a particular event * * @param string $eventName The event name - typically a constant * @param callable $listener A callable expecting an event argument * @param int $priority A higher value represents a higher priority */ public function addListener($eventName, $listener, $priority = 0) { $this->listeners[$eventName][$priority][] = $listener; } /** * Adds object methods as listeners for the events in getSubscribedEvents * * @see EventSubscriberInterface * * @param EventSubscriberInterface $subscriber */ public function addSubscriber(EventSubscriberInterface $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->addListener($eventName, array($subscriber, $params)); } elseif (is_string($params[0])) { $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0); } else { foreach ($params as $listener) { $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0); } } } } /** * Retrieves all listeners for a given event * * @param Event $event * @return array All listeners: callables and scripts */ protected function getListeners(Event $event) { $scriptListeners = $this->getScriptListeners($event); if (!isset($this->listeners[$event->getName()][0])) { $this->listeners[$event->getName()][0] = array(); } krsort($this->listeners[$event->getName()]); $listeners = $this->listeners; $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners); return call_user_func_array('array_merge', $listeners[$event->getName()]); } /** * Checks if an event has listeners registered * * @param Event $event * @return bool */ public function hasEventListeners(Event $event) { $listeners = $this->getListeners($event); return count($listeners) > 0; } /** * Finds all listeners defined as scripts in the package * * @param Event $event Event object * @return array Listeners */ protected function getScriptListeners(Event $event) { $package = $this->composer->getPackage(); $scripts = $package->getScripts(); if (empty($scripts[$event->getName()])) { return array(); } if ($this->loader) { $this->loader->unregister(); } $generator = $this->composer->getAutoloadGenerator(); if ($event instanceof ScriptEvent) { $generator->setDevMode($event->isDevMode()); } $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages(); $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages); $map = $generator->parseAutoloads($packageMap, $package); $this->loader = $generator->createLoader($map); $this->loader->register(); return $scripts[$event->getName()]; } /** * Checks if string given references a class path and method * * @param string $callable * @return bool */ protected function isPhpScript($callable) { return false === strpos($callable, ' ') && false !== strpos($callable, '::'); } /** * Checks if string given references a composer run-script * * @param string $callable * @return bool */ protected function isComposerScript($callable) { return '@' === substr($callable, 0, 1) && '@php ' !== substr($callable, 0, 5); } /** * Push an event to the stack of active event * * @param Event $event * @throws \RuntimeException * @return number */ protected function pushEvent(Event $event) { $eventName = $event->getName(); if (in_array($eventName, $this->eventStack)) { throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName)); } return array_push($this->eventStack, $eventName); } /** * Pops the active event from the stack * * @return mixed */ protected function popEvent() { return array_pop($this->eventStack); } } composer-1.6.3/src/Composer/EventDispatcher/EventSubscriberInterface.php000066400000000000000000000030211323436022200264460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\EventDispatcher; /** * An EventSubscriber knows which events it is interested in. * * If an EventSubscriber is added to an EventDispatcher, the manager invokes * {@link getSubscribedEvents} and registers the subscriber as a listener for all * returned events. * * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel * @author Bernhard Schussek */ interface EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to */ public static function getSubscribedEvents(); } composer-1.6.3/src/Composer/EventDispatcher/ScriptExecutionException.php000066400000000000000000000006461323436022200265410ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\EventDispatcher; /** * @author Jordi Boggiano */ class ScriptExecutionException extends \RuntimeException { } composer-1.6.3/src/Composer/Exception/000077500000000000000000000000001323436022200176615ustar00rootroot00000000000000composer-1.6.3/src/Composer/Exception/NoSslException.php000066400000000000000000000006261323436022200233130ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Exception; /** * @author Jordi Boggiano */ class NoSslException extends \RuntimeException { } composer-1.6.3/src/Composer/Factory.php000066400000000000000000000575461323436022200200640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Config\JsonConfigSource; use Composer\Json\JsonFile; use Composer\IO\IOInterface; use Composer\Package\Archiver; use Composer\Package\Version\VersionGuesser; use Composer\Repository\RepositoryManager; use Composer\Repository\RepositoryFactory; use Composer\Repository\WritableRepositoryInterface; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\Util\Silencer; use Composer\Plugin\PluginEvents; use Composer\EventDispatcher\Event; use Seld\JsonLint\DuplicateKeyException; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Output\ConsoleOutput; use Composer\EventDispatcher\EventDispatcher; use Composer\Autoload\AutoloadGenerator; use Composer\Package\Version\VersionParser; use Composer\Downloader\TransportException; use Seld\JsonLint\JsonParser; /** * Creates a configured instance of composer. * * @author Ryan Weaver * @author Jordi Boggiano * @author Igor Wiedler * @author Nils Adermann */ class Factory { /** * @throws \RuntimeException * @return string */ protected static function getHomeDir() { $home = getenv('COMPOSER_HOME'); if ($home) { return $home; } if (Platform::isWindows()) { if (!getenv('APPDATA')) { throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly'); } return rtrim(strtr(getenv('APPDATA'), '\\', '/'), '/') . '/Composer'; } $userDir = self::getUserDir(); if (is_dir($userDir . '/.composer')) { return $userDir . '/.composer'; } if (self::useXdg()) { // XDG Base Directory Specifications $xdgConfig = getenv('XDG_CONFIG_HOME') ?: $userDir . '/.config'; return $xdgConfig . '/composer'; } return $userDir . '/.composer'; } /** * @param string $home * @return string */ protected static function getCacheDir($home) { $cacheDir = getenv('COMPOSER_CACHE_DIR'); if ($cacheDir) { return $cacheDir; } $homeEnv = getenv('COMPOSER_HOME'); if ($homeEnv) { return $homeEnv . '/cache'; } if (Platform::isWindows()) { if ($cacheDir = getenv('LOCALAPPDATA')) { $cacheDir .= '/Composer'; } else { $cacheDir = $home . '/cache'; } return rtrim(strtr($cacheDir, '\\', '/'), '/'); } $userDir = self::getUserDir(); if ($home === $userDir . '/.composer' && is_dir($home . '/cache')) { return $home . '/cache'; } if (self::useXdg()) { $xdgCache = getenv('XDG_CACHE_HOME') ?: $userDir . '/.cache'; return $xdgCache . '/composer'; } return $home . '/cache'; } /** * @param string $home * @return string */ protected static function getDataDir($home) { $homeEnv = getenv('COMPOSER_HOME'); if ($homeEnv) { return $homeEnv; } if (Platform::isWindows()) { return strtr($home, '\\', '/'); } $userDir = self::getUserDir(); if ($home !== $userDir . '/.composer' && self::useXdg()) { $xdgData = getenv('XDG_DATA_HOME') ?: $userDir . '/.local/share'; return $xdgData . '/composer'; } return $home; } /** * @param IOInterface|null $io * @return Config */ public static function createConfig(IOInterface $io = null, $cwd = null) { $cwd = $cwd ?: getcwd(); $config = new Config(true, $cwd); // determine and add main dirs to the config $home = self::getHomeDir(); $config->merge(array('config' => array( 'home' => $home, 'cache-dir' => self::getCacheDir($home), 'data-dir' => self::getDataDir($home), ))); $htaccessProtect = (bool) $config->get('htaccess-protect'); if ($htaccessProtect) { // Protect directory against web access. Since HOME could be // the www-data's user home and be web-accessible it is a // potential security risk $dirs = array($config->get('home'), $config->get('cache-dir'), $config->get('data-dir')); foreach ($dirs as $dir) { if (!file_exists($dir . '/.htaccess')) { if (!is_dir($dir)) { Silencer::call('mkdir', $dir, 0777, true); } Silencer::call('file_put_contents', $dir . '/.htaccess', 'Deny from all'); } } } // load global config $file = new JsonFile($config->get('home').'/config.json'); if ($file->exists()) { if ($io && $io->isDebug()) { $io->writeError('Loading config file ' . $file->getPath()); } $config->merge($file->read()); } $config->setConfigSource(new JsonConfigSource($file)); // load global auth file $file = new JsonFile($config->get('home').'/auth.json'); if ($file->exists()) { if ($io && $io->isDebug()) { $io->writeError('Loading config file ' . $file->getPath()); } $config->merge(array('config' => $file->read())); } $config->setAuthConfigSource(new JsonConfigSource($file, true)); // load COMPOSER_AUTH environment variable if set if ($composerAuthEnv = getenv('COMPOSER_AUTH')) { $authData = json_decode($composerAuthEnv, true); if (null === $authData) { throw new \UnexpectedValueException('COMPOSER_AUTH environment variable is malformed, should be a valid JSON object'); } if ($io && $io->isDebug()) { $io->writeError('Loading auth config from COMPOSER_AUTH'); } $config->merge(array('config' => $authData)); } return $config; } public static function getComposerFile() { return trim(getenv('COMPOSER')) ?: './composer.json'; } public static function createAdditionalStyles() { return array( 'highlight' => new OutputFormatterStyle('red'), 'warning' => new OutputFormatterStyle('black', 'yellow'), ); } /** * Creates a ConsoleOutput instance * * @return ConsoleOutput */ public static function createOutput() { $styles = self::createAdditionalStyles(); $formatter = new OutputFormatter(false, $styles); return new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, null, $formatter); } /** * @deprecated Use Composer\Repository\RepositoryFactory::defaultRepos instead */ public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null) { return RepositoryFactory::defaultRepos($io, $config, $rm); } /** * Creates a Composer instance * * @param IOInterface $io IO instance * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will * read from the default filename * @param bool $disablePlugins Whether plugins should not be loaded * @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer) * @throws \InvalidArgumentException * @throws \UnexpectedValueException * @return Composer */ public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true) { $cwd = $cwd ?: getcwd(); // load Composer configuration if (null === $localConfig) { $localConfig = static::getComposerFile(); } if (is_string($localConfig)) { $composerFile = $localConfig; $file = new JsonFile($localConfig, null, $io); if (!$file->exists()) { if ($localConfig === './composer.json' || $localConfig === 'composer.json') { $message = 'Composer could not find a composer.json file in '.$cwd; } else { $message = 'Composer could not find the config file: '.$localConfig; } $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section'; throw new \InvalidArgumentException($message.PHP_EOL.$instructions); } $file->validateSchema(JsonFile::LAX_SCHEMA); $jsonParser = new JsonParser; try { $jsonParser->parse(file_get_contents($localConfig), JsonParser::DETECT_KEY_CONFLICTS); } catch (DuplicateKeyException $e) { $details = $e->getDetails(); $io->writeError('Key '.$details['key'].' is a duplicate in '.$localConfig.' at line '.$details['line'].''); } $localConfig = $file->read(); } // Load config and override with local config/auth config $config = static::createConfig($io, $cwd); $config->merge($localConfig); if (isset($composerFile)) { $io->writeError('Loading config file ' . $composerFile, true, IOInterface::DEBUG); $config->setConfigSource(new JsonConfigSource(new JsonFile(realpath($composerFile), null, $io))); $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json', null, $io); if ($localAuthFile->exists()) { $io->writeError('Loading config file ' . $localAuthFile->getPath(), true, IOInterface::DEBUG); $config->merge(array('config' => $localAuthFile->read())); $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true)); } } $vendorDir = $config->get('vendor-dir'); // initialize composer $composer = new Composer(); $composer->setConfig($config); if ($fullLoad) { // load auth configs into the IO instance $io->loadConfiguration($config); } $rfs = self::createRemoteFilesystem($io, $config); // initialize event dispatcher $dispatcher = new EventDispatcher($composer, $io); $composer->setEventDispatcher($dispatcher); // initialize repository manager $rm = RepositoryFactory::manager($io, $config, $dispatcher, $rfs); $composer->setRepositoryManager($rm); // load local repository $this->addLocalRepository($io, $rm, $vendorDir); // force-set the version of the global package if not defined as // guessing it adds no value and only takes time if (!$fullLoad && !isset($localConfig['version'])) { $localConfig['version'] = '1.0.0'; } // load package $parser = new VersionParser; $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser); $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser); $package = $loader->load($localConfig, 'Composer\Package\RootPackage', $cwd); $composer->setPackage($package); // initialize installation manager $im = $this->createInstallationManager(); $composer->setInstallationManager($im); if ($fullLoad) { // initialize download manager $dm = $this->createDownloadManager($io, $config, $dispatcher, $rfs); $composer->setDownloadManager($dm); // initialize autoload generator $generator = new AutoloadGenerator($dispatcher, $io); $composer->setAutoloadGenerator($generator); // initialize archive manager $am = $this->createArchiveManager($config, $dm); $composer->setArchiveManager($am); } // add installers to the manager (must happen after download manager is created since they read it out of $composer) $this->createDefaultInstallers($im, $composer, $io); if ($fullLoad) { $globalComposer = null; if (realpath($config->get('home')) !== $cwd) { $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins); } $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins); $composer->setPluginManager($pm); $pm->loadInstalledPlugins(); } // init locker if possible if ($fullLoad && isset($composerFile)) { $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION) ? substr($composerFile, 0, -4).'lock' : $composerFile . '.lock'; $locker = new Package\Locker($io, new JsonFile($lockFile, null, $io), $rm, $im, file_get_contents($composerFile)); $composer->setLocker($locker); } if ($fullLoad) { $initEvent = new Event(PluginEvents::INIT); $composer->getEventDispatcher()->dispatch($initEvent->getName(), $initEvent); // once everything is initialized we can // purge packages from local repos if they have been deleted on the filesystem if ($rm->getLocalRepository()) { $this->purgePackages($rm->getLocalRepository(), $im); } } return $composer; } /** * @param IOInterface $io IO instance * @param bool $disablePlugins Whether plugins should not be loaded * @return Composer */ public static function createGlobal(IOInterface $io, $disablePlugins = false) { $factory = new static(); return $factory->createGlobalComposer($io, static::createConfig($io), $disablePlugins, true); } /** * @param Repository\RepositoryManager $rm * @param string $vendorDir */ protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, $vendorDir) { $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json', null, $io))); } /** * @param Config $config * @return Composer|null */ protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins, $fullLoad = false) { $composer = null; try { $composer = $this->createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), $fullLoad); } catch (\Exception $e) { $io->writeError('Failed to initialize global composer: '.$e->getMessage(), true, IOInterface::DEBUG); } return $composer; } /** * @param IO\IOInterface $io * @param Config $config * @param EventDispatcher $eventDispatcher * @return Downloader\DownloadManager */ public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, RemoteFilesystem $rfs = null) { $cache = null; if ($config->get('cache-files-ttl') > 0) { $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./'); } $dm = new Downloader\DownloadManager($io); switch ($preferred = $config->get('preferred-install')) { case 'dist': $dm->setPreferDist(true); break; case 'source': $dm->setPreferSource(true); break; case 'auto': default: // noop break; } if (is_array($preferred)) { $dm->setPreferences($preferred); } $executor = new ProcessExecutor($io); $fs = new Filesystem($executor); $dm->setDownloader('git', new Downloader\GitDownloader($io, $config, $executor, $fs)); $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config, $executor, $fs)); $dm->setDownloader('fossil', new Downloader\FossilDownloader($io, $config, $executor, $fs)); $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config, $executor, $fs)); $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config)); $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache, $executor, $rfs)); $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache, $executor, $rfs)); $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache, $rfs)); $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache, $executor, $rfs)); $dm->setDownloader('xz', new Downloader\XzDownloader($io, $config, $eventDispatcher, $cache, $executor, $rfs)); $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache, $rfs)); $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache, $rfs)); $dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $eventDispatcher, $cache, $rfs)); return $dm; } /** * @param Config $config The configuration * @param Downloader\DownloadManager $dm Manager use to download sources * @return Archiver\ArchiveManager */ public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null) { if (null === $dm) { $io = new IO\NullIO(); $io->loadConfiguration($config); $dm = $this->createDownloadManager($io, $config); } $am = new Archiver\ArchiveManager($dm); $am->addArchiver(new Archiver\ZipArchiver); $am->addArchiver(new Archiver\PharArchiver); return $am; } /** * @param IOInterface $io * @param Composer $composer * @param Composer $globalComposer * @param bool $disablePlugins * @return Plugin\PluginManager */ protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false) { return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins); } /** * @return Installer\InstallationManager */ protected function createInstallationManager() { return new Installer\InstallationManager(); } /** * @param Installer\InstallationManager $im * @param Composer $composer * @param IO\IOInterface $io */ protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io) { $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null)); $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library')); $im->addInstaller(new Installer\PluginInstaller($io, $composer)); $im->addInstaller(new Installer\MetapackageInstaller($io)); } /** * @param WritableRepositoryInterface $repo repository to purge packages from * @param Installer\InstallationManager $im manager to check whether packages are still installed */ protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im) { foreach ($repo->getPackages() as $package) { if (!$im->isPackageInstalled($repo, $package)) { $repo->removePackage($package); } } } /** * @param IOInterface $io IO instance * @param mixed $config either a configuration array or a filename to read from, if null it will read from * the default filename * @param bool $disablePlugins Whether plugins should not be loaded * @return Composer */ public static function create(IOInterface $io, $config = null, $disablePlugins = false) { $factory = new static(); return $factory->createComposer($io, $config, $disablePlugins); } /** * @param IOInterface $io IO instance * @param Config $config Config instance * @param array $options Array of options passed directly to RemoteFilesystem constructor * @return RemoteFilesystem */ public static function createRemoteFilesystem(IOInterface $io, Config $config = null, $options = array()) { static $warned = false; $disableTls = false; if ($config && $config->get('disable-tls') === true) { if (!$warned) { $io->write('You are running Composer with SSL/TLS protection disabled.'); } $warned = true; $disableTls = true; } elseif (!extension_loaded('openssl')) { throw new Exception\NoSslException('The openssl extension is required for SSL/TLS protection but is not available. ' . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.'); } $remoteFilesystemOptions = array(); if ($disableTls === false) { if ($config && $config->get('cafile')) { $remoteFilesystemOptions['ssl']['cafile'] = $config->get('cafile'); } if ($config && $config->get('capath')) { $remoteFilesystemOptions['ssl']['capath'] = $config->get('capath'); } $remoteFilesystemOptions = array_replace_recursive($remoteFilesystemOptions, $options); } try { $remoteFilesystem = new RemoteFilesystem($io, $config, $remoteFilesystemOptions, $disableTls); } catch (TransportException $e) { if (false !== strpos($e->getMessage(), 'cafile')) { $io->write('Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.'); $io->write('A valid CA certificate file is required for SSL/TLS protection.'); if (PHP_VERSION_ID < 50600) { $io->write('It is recommended you upgrade to PHP 5.6+ which can detect your system CA file automatically.'); } $io->write('You can disable this error, at your own risk, by setting the \'disable-tls\' option to true.'); } throw $e; } return $remoteFilesystem; } /** * @return bool */ private static function useXdg() { foreach (array_keys($_SERVER) as $key) { if (substr($key, 0, 4) === 'XDG_') { return true; } } return false; } /** * @throws \RuntimeException * @return string */ private static function getUserDir() { $home = getenv('HOME'); if (!$home) { throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly'); } return rtrim(strtr($home, '\\', '/'), '/'); } } composer-1.6.3/src/Composer/IO/000077500000000000000000000000001323436022200162325ustar00rootroot00000000000000composer-1.6.3/src/Composer/IO/BaseIO.php000066400000000000000000000166231323436022200200550ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\IO; use Composer\Config; use Composer\Util\ProcessExecutor; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; abstract class BaseIO implements IOInterface, LoggerInterface { protected $authentications = array(); /** * {@inheritDoc} */ public function getAuthentications() { return $this->authentications; } /** * {@inheritDoc} */ public function hasAuthentication($repositoryName) { return isset($this->authentications[$repositoryName]); } /** * {@inheritDoc} */ public function getAuthentication($repositoryName) { if (isset($this->authentications[$repositoryName])) { return $this->authentications[$repositoryName]; } return array('username' => null, 'password' => null); } /** * {@inheritDoc} */ public function setAuthentication($repositoryName, $username, $password = null) { $this->authentications[$repositoryName] = array('username' => $username, 'password' => $password); } /** * Check for overwrite and set the authentication information for the repository. * * @param string $repositoryName The unique name of repository * @param string $username The username * @param string $password The password */ protected function checkAndSetAuthentication($repositoryName, $username, $password = null) { if ($this->hasAuthentication($repositoryName)) { $auth = $this->getAuthentication($repositoryName); if ($auth['username'] === $username && $auth['password'] === $password) { return; } $this->writeError( sprintf( "Warning: You should avoid overwriting already defined auth settings for %s.", $repositoryName ) ); } $this->setAuthentication($repositoryName, $username, $password); } /** * {@inheritDoc} */ public function loadConfiguration(Config $config) { $bitbucketOauth = $config->get('bitbucket-oauth') ?: array(); $githubOauth = $config->get('github-oauth') ?: array(); $gitlabOauth = $config->get('gitlab-oauth') ?: array(); $gitlabToken = $config->get('gitlab-token') ?: array(); $httpBasic = $config->get('http-basic') ?: array(); // reload oauth tokens from config if available foreach ($bitbucketOauth as $domain => $cred) { $this->checkAndSetAuthentication($domain, $cred['consumer-key'], $cred['consumer-secret']); } foreach ($githubOauth as $domain => $token) { if (!preg_match('{^[.a-z0-9]+$}', $token)) { throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"'); } $this->checkAndSetAuthentication($domain, $token, 'x-oauth-basic'); } foreach ($gitlabOauth as $domain => $token) { $this->checkAndSetAuthentication($domain, $token, 'oauth2'); } foreach ($gitlabToken as $domain => $token) { $this->checkAndSetAuthentication($domain, $token, 'private-token'); } // reload http basic credentials from config if available foreach ($httpBasic as $domain => $cred) { $this->checkAndSetAuthentication($domain, $cred['username'], $cred['password']); } // setup process timeout ProcessExecutor::setTimeout((int) $config->get('process-timeout')); } /** * System is unusable. * * @param string $message * @param array $context * @return null */ public function emergency($message, array $context = array()) { return $this->log(LogLevel::EMERGENCY, $message, $context); } /** * Action must be taken immediately. * * Example: Entire website down, database unavailable, etc. This should * trigger the SMS alerts and wake you up. * * @param string $message * @param array $context * @return null */ public function alert($message, array $context = array()) { return $this->log(LogLevel::ALERT, $message, $context); } /** * Critical conditions. * * Example: Application component unavailable, unexpected exception. * * @param string $message * @param array $context * @return null */ public function critical($message, array $context = array()) { return $this->log(LogLevel::CRITICAL, $message, $context); } /** * Runtime errors that do not require immediate action but should typically * be logged and monitored. * * @param string $message * @param array $context * @return null */ public function error($message, array $context = array()) { return $this->log(LogLevel::ERROR, $message, $context); } /** * Exceptional occurrences that are not errors. * * Example: Use of deprecated APIs, poor use of an API, undesirable things * that are not necessarily wrong. * * @param string $message * @param array $context * @return null */ public function warning($message, array $context = array()) { return $this->log(LogLevel::WARNING, $message, $context); } /** * Normal but significant events. * * @param string $message * @param array $context * @return null */ public function notice($message, array $context = array()) { return $this->log(LogLevel::NOTICE, $message, $context); } /** * Interesting events. * * Example: User logs in, SQL logs. * * @param string $message * @param array $context * @return null */ public function info($message, array $context = array()) { return $this->log(LogLevel::INFO, $message, $context); } /** * Detailed debug information. * * @param string $message * @param array $context * @return null */ public function debug($message, array $context = array()) { return $this->log(LogLevel::DEBUG, $message, $context); } /** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $context * @return null */ public function log($level, $message, array $context = array()) { if (in_array($level, array(LogLevel::EMERGENCY, LogLevel::ALERT, LogLevel::CRITICAL, LogLevel::ERROR))) { $this->writeError(''.$message.'', true, self::NORMAL); } elseif ($level === LogLevel::WARNING) { $this->writeError(''.$message.'', true, self::NORMAL); } elseif ($level === LogLevel::NOTICE) { $this->writeError(''.$message.'', true, self::VERBOSE); } elseif ($level === LogLevel::INFO) { $this->writeError(''.$message.'', true, self::VERY_VERBOSE); } else { $this->writeError($message, true, self::DEBUG); } } } composer-1.6.3/src/Composer/IO/BufferIO.php000066400000000000000000000034231323436022200204060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\IO; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Formatter\OutputFormatterInterface; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Helper\HelperSet; /** * @author Jordi Boggiano */ class BufferIO extends ConsoleIO { /** * @param string $input * @param int $verbosity * @param OutputFormatterInterface|null $formatter */ public function __construct($input = '', $verbosity = StreamOutput::VERBOSITY_NORMAL, OutputFormatterInterface $formatter = null) { $input = new StringInput($input); $input->setInteractive(false); $output = new StreamOutput(fopen('php://memory', 'rw'), $verbosity, $formatter ? $formatter->isDecorated() : false, $formatter); parent::__construct($input, $output, new HelperSet(array())); } public function getOutput() { fseek($this->output->getStream(), 0); $output = stream_get_contents($this->output->getStream()); $output = preg_replace_callback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches) { $pre = strip_tags($matches[1]); if (strlen($pre) === strlen($matches[2])) { return ''; } // TODO reverse parse the string, skipping span tags and \033\[([0-9;]+)m(.*?)\033\[0m style blobs return rtrim($matches[1])."\n"; }, $output); return $output; } } composer-1.6.3/src/Composer/IO/ConsoleIO.php000066400000000000000000000230271323436022200206010ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\IO; use Composer\Question\StrictConfirmationQuestion; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ChoiceQuestion; use Symfony\Component\Console\Question\Question; /** * The Input/Output helper. * * @author François Pluchino * @author Jordi Boggiano */ class ConsoleIO extends BaseIO { /** @var InputInterface */ protected $input; /** @var OutputInterface */ protected $output; /** @var HelperSet */ protected $helperSet; /** @var string */ protected $lastMessage; /** @var string */ protected $lastMessageErr; /** @var float */ private $startTime; /** @var array */ private $verbosityMap; /** * Constructor. * * @param InputInterface $input The input instance * @param OutputInterface $output The output instance * @param HelperSet $helperSet The helperSet instance */ public function __construct(InputInterface $input, OutputInterface $output, HelperSet $helperSet) { $this->input = $input; $this->output = $output; $this->helperSet = $helperSet; $this->verbosityMap = array( self::QUIET => OutputInterface::VERBOSITY_QUIET, self::NORMAL => OutputInterface::VERBOSITY_NORMAL, self::VERBOSE => OutputInterface::VERBOSITY_VERBOSE, self::VERY_VERBOSE => OutputInterface::VERBOSITY_VERY_VERBOSE, self::DEBUG => OutputInterface::VERBOSITY_DEBUG, ); } /** * @param float $startTime */ public function enableDebugging($startTime) { $this->startTime = $startTime; } /** * {@inheritDoc} */ public function isInteractive() { return $this->input->isInteractive(); } /** * {@inheritDoc} */ public function isDecorated() { return $this->output->isDecorated(); } /** * {@inheritDoc} */ public function isVerbose() { return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE; } /** * {@inheritDoc} */ public function isVeryVerbose() { return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE; } /** * {@inheritDoc} */ public function isDebug() { return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG; } /** * {@inheritDoc} */ public function write($messages, $newline = true, $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, false, $verbosity); } /** * {@inheritDoc} */ public function writeError($messages, $newline = true, $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, true, $verbosity); } /** * @param array|string $messages * @param bool $newline * @param bool $stderr * @param int $verbosity */ private function doWrite($messages, $newline, $stderr, $verbosity) { $sfVerbosity = $this->verbosityMap[$verbosity]; if ($sfVerbosity > $this->output->getVerbosity()) { return; } // hack to keep our usage BC with symfony<2.8 versions // this removes the quiet output but there is no way around it // see https://github.com/composer/composer/pull/4913 if (OutputInterface::VERBOSITY_QUIET === 0) { $sfVerbosity = OutputInterface::OUTPUT_NORMAL; } if (null !== $this->startTime) { $memoryUsage = memory_get_usage() / 1024 / 1024; $timeSpent = microtime(true) - $this->startTime; $messages = array_map(function ($message) use ($memoryUsage, $timeSpent) { return sprintf('[%.1fMB/%.2fs] %s', $memoryUsage, $timeSpent, $message); }, (array) $messages); } if (true === $stderr && $this->output instanceof ConsoleOutputInterface) { $this->output->getErrorOutput()->write($messages, $newline, $sfVerbosity); $this->lastMessageErr = implode($newline ? "\n" : '', (array) $messages); return; } $this->output->write($messages, $newline, $sfVerbosity); $this->lastMessage = implode($newline ? "\n" : '', (array) $messages); } /** * {@inheritDoc} */ public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL) { $this->doOverwrite($messages, $newline, $size, false, $verbosity); } /** * {@inheritDoc} */ public function overwriteError($messages, $newline = true, $size = null, $verbosity = self::NORMAL) { $this->doOverwrite($messages, $newline, $size, true, $verbosity); } /** * @param array|string $messages * @param bool $newline * @param int|null $size * @param bool $stderr * @param int $verbosity */ private function doOverwrite($messages, $newline, $size, $stderr, $verbosity) { // messages can be an array, let's convert it to string anyway $messages = implode($newline ? "\n" : '', (array) $messages); // since overwrite is supposed to overwrite last message... if (!isset($size)) { // removing possible formatting of lastMessage with strip_tags $size = strlen(strip_tags($stderr ? $this->lastMessageErr : $this->lastMessage)); } // ...let's fill its length with backspaces $this->doWrite(str_repeat("\x08", $size), false, $stderr, $verbosity); // write the new message $this->doWrite($messages, false, $stderr, $verbosity); // In cmd.exe on Win8.1 (possibly 10?), the line can not be cleared, so we need to // track the length of previous output and fill it with spaces to make sure the line is cleared. // See https://github.com/composer/composer/pull/5836 for more details $fill = $size - strlen(strip_tags($messages)); if ($fill > 0) { // whitespace whatever has left $this->doWrite(str_repeat(' ', $fill), false, $stderr, $verbosity); // move the cursor back $this->doWrite(str_repeat("\x08", $fill), false, $stderr, $verbosity); } if ($newline) { $this->doWrite('', true, $stderr, $verbosity); } if ($stderr) { $this->lastMessageErr = $messages; } else { $this->lastMessage = $messages; } } /** * {@inheritDoc} */ public function ask($question, $default = null) { /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */ $helper = $this->helperSet->get('question'); $question = new Question($question, $default); return $helper->ask($this->input, $this->getErrorOutput(), $question); } /** * {@inheritDoc} */ public function askConfirmation($question, $default = true) { /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */ $helper = $this->helperSet->get('question'); $question = new StrictConfirmationQuestion($question, $default); return $helper->ask($this->input, $this->getErrorOutput(), $question); } /** * {@inheritDoc} */ public function askAndValidate($question, $validator, $attempts = null, $default = null) { /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */ $helper = $this->helperSet->get('question'); $question = new Question($question, $default); $question->setValidator($validator); $question->setMaxAttempts($attempts); return $helper->ask($this->input, $this->getErrorOutput(), $question); } /** * {@inheritDoc} */ public function askAndHideAnswer($question) { $this->writeError($question, false); return \Seld\CliPrompt\CliPrompt::hiddenPrompt(true); } /** * {@inheritDoc} */ public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false) { /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */ $helper = $this->helperSet->get('question'); $question = new ChoiceQuestion($question, $choices, $default); $question->setMaxAttempts($attempts ?: null); // IOInterface requires false, and Question requires null or int $question->setErrorMessage($errorMessage); $question->setMultiselect($multiselect); $result = $helper->ask($this->input, $this->getErrorOutput(), $question); $results = array(); foreach ($choices as $index => $choice) { if (in_array($choice, $result, true)) { $results[] = (string) $index; } } return $results; } /** * @return OutputInterface */ private function getErrorOutput() { if ($this->output instanceof ConsoleOutputInterface) { return $this->output->getErrorOutput(); } return $this->output; } } composer-1.6.3/src/Composer/IO/IOInterface.php000066400000000000000000000151421323436022200210760ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\IO; use Composer\Config; /** * The Input/Output helper interface. * * @author François Pluchino */ interface IOInterface { const QUIET = 1; const NORMAL = 2; const VERBOSE = 4; const VERY_VERBOSE = 8; const DEBUG = 16; /** * Is this input means interactive? * * @return bool */ public function isInteractive(); /** * Is this output verbose? * * @return bool */ public function isVerbose(); /** * Is the output very verbose? * * @return bool */ public function isVeryVerbose(); /** * Is the output in debug verbosity? * * @return bool */ public function isDebug(); /** * Is this output decorated? * * @return bool */ public function isDecorated(); /** * Writes a message to the output. * * @param string|array $messages The message as an array of lines or a single string * @param bool $newline Whether to add a newline or not * @param int $verbosity Verbosity level from the VERBOSITY_* constants */ public function write($messages, $newline = true, $verbosity = self::NORMAL); /** * Writes a message to the error output. * * @param string|array $messages The message as an array of lines or a single string * @param bool $newline Whether to add a newline or not * @param int $verbosity Verbosity level from the VERBOSITY_* constants */ public function writeError($messages, $newline = true, $verbosity = self::NORMAL); /** * Overwrites a previous message to the output. * * @param string|array $messages The message as an array of lines or a single string * @param bool $newline Whether to add a newline or not * @param int $size The size of line * @param int $verbosity Verbosity level from the VERBOSITY_* constants */ public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL); /** * Overwrites a previous message to the error output. * * @param string|array $messages The message as an array of lines or a single string * @param bool $newline Whether to add a newline or not * @param int $size The size of line * @param int $verbosity Verbosity level from the VERBOSITY_* constants */ public function overwriteError($messages, $newline = true, $size = null, $verbosity = self::NORMAL); /** * Asks a question to the user. * * @param string|array $question The question to ask * @param string $default The default answer if none is given by the user * * @throws \RuntimeException If there is no data to read in the input stream * @return string The user answer */ public function ask($question, $default = null); /** * Asks a confirmation to the user. * * The question will be asked until the user answers by nothing, yes, or no. * * @param string|array $question The question to ask * @param bool $default The default answer if the user enters nothing * * @return bool true if the user has confirmed, false otherwise */ public function askConfirmation($question, $default = true); /** * Asks for a value and validates the response. * * The validator receives the data to validate. It must return the * validated data when the data is valid and throw an exception * otherwise. * * @param string|array $question The question to ask * @param callable $validator A PHP callback * @param null|int $attempts Max number of times to ask before giving up (default of null means infinite) * @param mixed $default The default answer if none is given by the user * * @throws \Exception When any of the validators return an error * @return mixed */ public function askAndValidate($question, $validator, $attempts = null, $default = null); /** * Asks a question to the user and hide the answer. * * @param string $question The question to ask * * @return string The answer */ public function askAndHideAnswer($question); /** * Asks the user to select a value. * * @param string|array $question The question to ask * @param array $choices List of choices to pick from * @param bool|string $default The default answer if the user enters nothing * @param bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite) * @param string $errorMessage Message which will be shown if invalid value from choice list would be picked * @param bool $multiselect Select more than one value separated by comma * * @throws \InvalidArgumentException * @return int|string|array The selected value or values (the key of the choices array) */ public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false); /** * Get all authentication information entered. * * @return array The map of authentication data */ public function getAuthentications(); /** * Verify if the repository has a authentication information. * * @param string $repositoryName The unique name of repository * * @return bool */ public function hasAuthentication($repositoryName); /** * Get the username and password of repository. * * @param string $repositoryName The unique name of repository * * @return array The 'username' and 'password' */ public function getAuthentication($repositoryName); /** * Set the authentication information for the repository. * * @param string $repositoryName The unique name of repository * @param string $username The username * @param string $password The password */ public function setAuthentication($repositoryName, $username, $password = null); /** * Loads authentications from a config instance * * @param Config $config */ public function loadConfiguration(Config $config); } composer-1.6.3/src/Composer/IO/NullIO.php000066400000000000000000000044071323436022200201120ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\IO; /** * IOInterface that is not interactive and never writes the output * * @author Christophe Coevoet */ class NullIO extends BaseIO { /** * {@inheritDoc} */ public function isInteractive() { return false; } /** * {@inheritDoc} */ public function isVerbose() { return false; } /** * {@inheritDoc} */ public function isVeryVerbose() { return false; } /** * {@inheritDoc} */ public function isDebug() { return false; } /** * {@inheritDoc} */ public function isDecorated() { return false; } /** * {@inheritDoc} */ public function write($messages, $newline = true, $verbosity = self::NORMAL) { } /** * {@inheritDoc} */ public function writeError($messages, $newline = true, $verbosity = self::NORMAL) { } /** * {@inheritDoc} */ public function overwrite($messages, $newline = true, $size = 80, $verbosity = self::NORMAL) { } /** * {@inheritDoc} */ public function overwriteError($messages, $newline = true, $size = 80, $verbosity = self::NORMAL) { } /** * {@inheritDoc} */ public function ask($question, $default = null) { return $default; } /** * {@inheritDoc} */ public function askConfirmation($question, $default = true) { return $default; } /** * {@inheritDoc} */ public function askAndValidate($question, $validator, $attempts = false, $default = null) { return $default; } /** * {@inheritDoc} */ public function askAndHideAnswer($question) { return null; } /** * {@inheritDoc} */ public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false) { return $default; } } composer-1.6.3/src/Composer/Installer.php000066400000000000000000002071261323436022200204010ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Autoload\AutoloadGenerator; use Composer\DependencyResolver\DefaultPolicy; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\DependencyResolver\PolicyInterface; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Request; use Composer\DependencyResolver\Rule; use Composer\DependencyResolver\Solver; use Composer\DependencyResolver\SolverProblemsException; use Composer\Downloader\DownloadManager; use Composer\EventDispatcher\EventDispatcher; use Composer\Installer\InstallationManager; use Composer\Installer\InstallerEvents; use Composer\Installer\NoopInstaller; use Composer\Installer\SuggestedPackagesReporter; use Composer\IO\IOInterface; use Composer\Package\AliasPackage; use Composer\Package\CompletePackage; use Composer\Package\Link; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Dumper\ArrayDumper; use Composer\Semver\Constraint\Constraint; use Composer\Package\Locker; use Composer\Package\PackageInterface; use Composer\Package\RootPackageInterface; use Composer\Repository\CompositeRepository; use Composer\Repository\InstalledArrayRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryInterface; use Composer\Repository\RepositoryManager; use Composer\Repository\WritableRepositoryInterface; use Composer\Script\ScriptEvents; /** * @author Jordi Boggiano * @author Beau Simensen * @author Konstantin Kudryashov * @author Nils Adermann */ class Installer { /** * @var IOInterface */ protected $io; /** * @var Config */ protected $config; /** * @var RootPackageInterface */ protected $package; /** * @var DownloadManager */ protected $downloadManager; /** * @var RepositoryManager */ protected $repositoryManager; /** * @var Locker */ protected $locker; /** * @var InstallationManager */ protected $installationManager; /** * @var EventDispatcher */ protected $eventDispatcher; /** * @var AutoloadGenerator */ protected $autoloadGenerator; protected $preferSource = false; protected $preferDist = false; protected $optimizeAutoloader = false; protected $classMapAuthoritative = false; protected $apcuAutoloader = false; protected $devMode = false; protected $dryRun = false; protected $verbose = false; protected $update = false; protected $dumpAutoloader = true; protected $runScripts = true; protected $ignorePlatformReqs = false; protected $preferStable = false; protected $preferLowest = false; protected $skipSuggest = false; protected $writeLock = true; protected $executeOperations = true; /** * Array of package names/globs flagged for update * * @var array|null */ protected $updateWhitelist = null; protected $whitelistDependencies = false; // TODO 2.0 rename to whitelistTransitiveDependencies protected $whitelistAllDependencies = false; /** * @var SuggestedPackagesReporter */ protected $suggestedPackagesReporter; /** * @var RepositoryInterface */ protected $additionalInstalledRepository; /** * Constructor * * @param IOInterface $io * @param Config $config * @param RootPackageInterface $package * @param DownloadManager $downloadManager * @param RepositoryManager $repositoryManager * @param Locker $locker * @param InstallationManager $installationManager * @param EventDispatcher $eventDispatcher * @param AutoloadGenerator $autoloadGenerator */ public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator) { $this->io = $io; $this->config = $config; $this->package = $package; $this->downloadManager = $downloadManager; $this->repositoryManager = $repositoryManager; $this->locker = $locker; $this->installationManager = $installationManager; $this->eventDispatcher = $eventDispatcher; $this->autoloadGenerator = $autoloadGenerator; } /** * Run installation (or update) * * @throws \Exception * @return int 0 on success or a positive error code on failure */ public function run() { // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands // of PHP objects, the GC can spend quite some time walking the tree of references looking // for stuff to collect while there is nothing to collect. This slows things down dramatically // and turning it off results in much better performance. Do not try this at home however. gc_collect_cycles(); gc_disable(); // Force update if there is no lock file present if (!$this->update && !$this->locker->isLocked()) { $this->update = true; } if ($this->dryRun) { $this->verbose = true; $this->runScripts = false; $this->executeOperations = false; $this->writeLock = false; $this->dumpAutoloader = false; $this->installationManager->addInstaller(new NoopInstaller); $this->mockLocalRepositories($this->repositoryManager); } if ($this->runScripts) { $devMode = (int) $this->devMode; putenv("COMPOSER_DEV_MODE=$devMode"); // dispatch pre event $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD; $this->eventDispatcher->dispatchScript($eventName, $this->devMode); } $this->downloadManager->setPreferSource($this->preferSource); $this->downloadManager->setPreferDist($this->preferDist); // create installed repo, this contains all local packages + platform packages (php & extensions) $localRepo = $this->repositoryManager->getLocalRepository(); if ($this->update) { $platformOverrides = $this->config->get('platform') ?: array(); } else { $platformOverrides = $this->locker->getPlatformOverrides(); } $platformRepo = new PlatformRepository(array(), $platformOverrides); $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo); $aliases = $this->getRootAliases(); $this->aliasPlatformPackages($platformRepo, $aliases); if (!$this->suggestedPackagesReporter) { $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io); } try { list($res, $devPackages) = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases); if ($res !== 0) { return $res; } } catch (\Exception $e) { if ($this->executeOperations) { $this->installationManager->notifyInstalls($this->io); } throw $e; } if ($this->executeOperations) { $this->installationManager->notifyInstalls($this->io); } // output suggestions if we're in dev mode if ($this->devMode && !$this->skipSuggest) { $this->suggestedPackagesReporter->output($installedRepo); } # Find abandoned packages and warn user foreach ($localRepo->getPackages() as $package) { if (!$package instanceof CompletePackage || !$package->isAbandoned()) { continue; } $replacement = (is_string($package->getReplacementPackage())) ? 'Use ' . $package->getReplacementPackage() . ' instead' : 'No replacement was suggested'; $this->io->writeError( sprintf( "Package %s is abandoned, you should avoid using it. %s.", $package->getPrettyName(), $replacement ) ); } // write lock if ($this->update && $this->writeLock) { $localRepo->reload(); $platformReqs = $this->extractPlatformRequirements($this->package->getRequires()); $platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires()); $updatedLock = $this->locker->setLockData( array_diff($localRepo->getCanonicalPackages(), $devPackages), $devPackages, $platformReqs, $platformDevReqs, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags(), $this->preferStable || $this->package->getPreferStable(), $this->preferLowest, $this->config->get('platform') ?: array() ); if ($updatedLock) { $this->io->writeError('Writing lock file'); } } if ($this->dumpAutoloader) { // write autoloader if ($this->optimizeAutoloader) { $this->io->writeError('Generating optimized autoload files'); } else { $this->io->writeError('Generating autoload files'); } $this->autoloadGenerator->setDevMode($this->devMode); $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative); $this->autoloadGenerator->setApcu($this->apcuAutoloader); $this->autoloadGenerator->setRunScripts($this->runScripts); $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader); } if ($this->executeOperations) { // force binaries re-generation in case they are missing foreach ($localRepo->getPackages() as $package) { $this->installationManager->ensureBinariesPresence($package); } $vendorDir = $this->config->get('vendor-dir'); if (is_dir($vendorDir)) { // suppress errors as this fails sometimes on OSX for no apparent reason // see https://github.com/composer/composer/issues/4070#issuecomment-129792748 @touch($vendorDir); } } if ($this->runScripts) { // dispatch post event $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD; $this->eventDispatcher->dispatchScript($eventName, $this->devMode); } // re-enable GC except on HHVM which triggers a warning here if (!defined('HHVM_VERSION')) { gc_enable(); } return 0; } /** * @param RepositoryInterface $localRepo * @param RepositoryInterface $installedRepo * @param PlatformRepository $platformRepo * @param array $aliases * @return array [int, PackageInterfaces[]|null] with the exit code and an array of dev packages on update, or null on install */ protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases) { // init vars $lockedRepository = null; $repositories = null; // initialize locked repo if we are installing from lock or in a partial update // and a lock file is present as we need to force install non-whitelisted lock file // packages in that case if (!$this->update || (!empty($this->updateWhitelist) && $this->locker->isLocked())) { try { $lockedRepository = $this->locker->getLockedRepository($this->devMode); } catch (\RuntimeException $e) { // if there are dev requires, then we really can not install if ($this->package->getDevRequires()) { throw $e; } // no require-dev in composer.json and the lock file was created with no dev info, so skip them $lockedRepository = $this->locker->getLockedRepository(); } } $this->whitelistUpdateDependencies( $lockedRepository ?: $localRepo, $this->package->getRequires(), $this->package->getDevRequires() ); $this->io->writeError('Loading composer repositories with package information'); // creating repository pool $policy = $this->createPolicy(); $pool = $this->createPool($this->update ? null : $lockedRepository); $pool->addRepository($installedRepo, $aliases); if ($this->update) { $repositories = $this->repositoryManager->getRepositories(); foreach ($repositories as $repository) { $pool->addRepository($repository, $aliases); } } // Add the locked repository after the others in case we are doing a // partial update so missing packages can be found there still. // For installs from lock it's the only one added so it is first if ($lockedRepository) { $pool->addRepository($lockedRepository, $aliases); } // creating requirements request $request = $this->createRequest($this->package, $platformRepo); if ($this->update) { // remove unstable packages from the localRepo if they don't match the current stability settings $removedUnstablePackages = array(); foreach ($localRepo->getPackages() as $package) { if ( !$pool->isPackageAcceptable($package->getNames(), $package->getStability()) && $this->installationManager->isPackageInstalled($localRepo, $package) ) { $removedUnstablePackages[$package->getName()] = true; $request->remove($package->getName(), new Constraint('=', $package->getVersion())); } } $this->io->writeError('Updating dependencies'.($this->devMode ? ' (including require-dev)' : '').''); $request->updateAll(); $links = array_merge($this->package->getRequires(), $this->package->getDevRequires()); foreach ($links as $link) { $request->install($link->getTarget(), $link->getConstraint()); } // if the updateWhitelist is enabled, packages not in it are also fixed // to the version specified in the lock, or their currently installed version if ($this->updateWhitelist) { $currentPackages = $this->getCurrentPackages($installedRepo); // collect packages to fixate from root requirements as well as installed packages $candidates = array(); foreach ($links as $link) { $candidates[$link->getTarget()] = true; $rootRequires[$link->getTarget()] = $link; } foreach ($currentPackages as $package) { $candidates[$package->getName()] = true; } // fix them to the version in lock (or currently installed) if they are not updateable foreach ($candidates as $candidate => $dummy) { foreach ($currentPackages as $curPackage) { if ($curPackage->getName() === $candidate) { if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) { $constraint = new Constraint('=', $curPackage->getVersion()); $description = $this->locker->isLocked() ? '(locked at' : '(installed at'; $requiredAt = isset($rootRequires[$candidate]) ? ', required as ' . $rootRequires[$candidate]->getPrettyConstraint() : ''; $constraint->setPrettyString($description . ' ' . $curPackage->getPrettyVersion() . $requiredAt . ')'); $request->install($curPackage->getName(), $constraint); } break; } } } } } else { $this->io->writeError('Installing dependencies'.($this->devMode ? ' (including require-dev)' : '').' from lock file'); if (!$this->locker->isFresh()) { $this->io->writeError('Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.', true, IOInterface::QUIET); } foreach ($lockedRepository->getPackages() as $package) { $version = $package->getVersion(); if (isset($aliases[$package->getName()][$version])) { $version = $aliases[$package->getName()][$version]['alias_normalized']; } $constraint = new Constraint('=', $version); $constraint->setPrettyString($package->getPrettyVersion()); $request->install($package->getName(), $constraint); } foreach ($this->locker->getPlatformRequirements($this->devMode) as $link) { $request->install($link->getTarget(), $link->getConstraint()); } } // force dev packages to have the latest links if we update or install from a (potentially new) lock $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-links'); // solve dependencies $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request); $solver = new Solver($policy, $pool, $installedRepo, $this->io); try { $operations = $solver->solve($request, $this->ignorePlatformReqs); } catch (SolverProblemsException $e) { $this->io->writeError('Your requirements could not be resolved to an installable set of packages.', true, IOInterface::QUIET); $this->io->writeError($e->getMessage()); if ($this->update && !$this->devMode) { $this->io->writeError('Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.', true, IOInterface::QUIET); } return array(max(1, $e->getCode()), array()); } // force dev packages to be updated if we update or install from a (potentially new) lock $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-updates', $operations); $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request, $operations); $this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE); $this->io->writeError("Analyzed ".$solver->getRuleSetSize()." rules to resolve dependencies", true, IOInterface::VERBOSE); // execute operations if (!$operations) { $this->io->writeError('Nothing to install or update'); } $operations = $this->movePluginsToFront($operations); $operations = $this->moveUninstallsToFront($operations); // extract dev packages and mark them to be skipped if it's a --no-dev install or update // we also force them to be uninstalled if they are present in the local repo if ($this->update) { $devPackages = $this->extractDevPackages($operations, $localRepo, $platformRepo, $aliases); if (!$this->devMode) { $operations = $this->filterDevPackageOperations($devPackages, $operations, $localRepo); } } else { $devPackages = null; } if ($operations) { $installs = $updates = $uninstalls = array(); foreach ($operations as $operation) { if ($operation instanceof InstallOperation) { $installs[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion(); } elseif ($operation instanceof UpdateOperation) { $updates[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion(); } elseif ($operation instanceof UninstallOperation) { $uninstalls[] = $operation->getPackage()->getPrettyName(); } } $this->io->writeError( sprintf("Package operations: %d install%s, %d update%s, %d removal%s", count($installs), 1 === count($installs) ? '' : 's', count($updates), 1 === count($updates) ? '' : 's', count($uninstalls), 1 === count($uninstalls) ? '' : 's') ); if ($installs) { $this->io->writeError("Installs: ".implode(', ', $installs), true, IOInterface::VERBOSE); } if ($updates) { $this->io->writeError("Updates: ".implode(', ', $updates), true, IOInterface::VERBOSE); } if ($uninstalls) { $this->io->writeError("Removals: ".implode(', ', $uninstalls), true, IOInterface::VERBOSE); } } foreach ($operations as $operation) { // collect suggestions if ('install' === $operation->getJobType()) { $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage()); } // updating, force dev packages' references if they're in root package refs if ($this->update) { $package = null; if ('update' === $operation->getJobType()) { $package = $operation->getTargetPackage(); } elseif ('install' === $operation->getJobType()) { $package = $operation->getPackage(); } if ($package && $package->isDev()) { $references = $this->package->getReferences(); if (isset($references[$package->getName()])) { $this->updateInstallReferences($package, $references[$package->getName()]); } } if ('update' === $operation->getJobType() && $operation->getTargetPackage()->isDev() && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion() && (!$operation->getTargetPackage()->getSourceReference() || $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference()) && (!$operation->getTargetPackage()->getDistReference() || $operation->getTargetPackage()->getDistReference() === $operation->getInitialPackage()->getDistReference()) ) { $this->io->writeError(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version', true, IOInterface::DEBUG); $this->io->writeError('', true, IOInterface::DEBUG); continue; } } $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType()); if (defined($event) && $this->runScripts) { $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation); } // output non-alias ops when not executing operations (i.e. dry run), output alias ops in debug verbosity if (!$this->executeOperations && false === strpos($operation->getJobType(), 'Alias')) { $this->io->writeError(' - ' . $operation); } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) { $this->io->writeError(' - ' . $operation); } $this->installationManager->execute($localRepo, $operation); // output reasons why the operation was ran, only for install/update operations if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) { $reason = $operation->getReason(); if ($reason instanceof Rule) { switch ($reason->getReason()) { case Rule::RULE_JOB_INSTALL: $this->io->writeError(' REASON: Required by the root package: '.$reason->getPrettyString($pool)); $this->io->writeError(''); break; case Rule::RULE_PACKAGE_REQUIRES: $this->io->writeError(' REASON: '.$reason->getPrettyString($pool)); $this->io->writeError(''); break; } } } $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($operation->getJobType()); if (defined($event) && $this->runScripts) { $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation); } if ($this->executeOperations || $this->writeLock) { $localRepo->write(); } } if ($this->executeOperations) { // force source/dist urls to be updated for all packages $this->processPackageUrls($pool, $policy, $localRepo, $repositories); $localRepo->write(); } return array(0, $devPackages); } /** * Extracts the dev packages out of the localRepo * * This works by faking the operations so we can see what the dev packages * would be at the end of the operation execution. This lets us then remove * the dev packages from the list of operations accordingly if we are in a * --no-dev install or update. * * @return array */ private function extractDevPackages(array $operations, RepositoryInterface $localRepo, PlatformRepository $platformRepo, array $aliases) { if (!$this->package->getDevRequires()) { return array(); } // fake-apply all operations to this clone of the local repo so we see the complete set of package we would end up with $tempLocalRepo = clone $localRepo; foreach ($operations as $operation) { switch ($operation->getJobType()) { case 'install': case 'markAliasInstalled': if (!$tempLocalRepo->hasPackage($operation->getPackage())) { $tempLocalRepo->addPackage(clone $operation->getPackage()); } break; case 'uninstall': case 'markAliasUninstalled': $tempLocalRepo->removePackage($operation->getPackage()); break; case 'update': $tempLocalRepo->removePackage($operation->getInitialPackage()); if (!$tempLocalRepo->hasPackage($operation->getTargetPackage())) { $tempLocalRepo->addPackage(clone $operation->getTargetPackage()); } break; default: throw new \LogicException('Unknown type: '.$operation->getJobType()); } } // we have to reload the local repo to handle aliases properly // but as it is not persisted on disk we use a loader/dumper // to reload it in memory $localRepo = new InstalledArrayRepository(array()); $loader = new ArrayLoader(null, true); $dumper = new ArrayDumper(); foreach ($tempLocalRepo->getCanonicalPackages() as $pkg) { $localRepo->addPackage($loader->load($dumper->dump($pkg))); } unset($tempLocalRepo, $loader, $dumper); $policy = $this->createPolicy(); $pool = $this->createPool(); $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo); $pool->addRepository($installedRepo, $aliases); // creating requirements request without dev requirements $request = $this->createRequest($this->package, $platformRepo); $request->updateAll(); foreach ($this->package->getRequires() as $link) { $request->install($link->getTarget(), $link->getConstraint()); } // solve deps to see which get removed $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request); $solver = new Solver($policy, $pool, $installedRepo, $this->io); $ops = $solver->solve($request, $this->ignorePlatformReqs); $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops); $devPackages = array(); foreach ($ops as $op) { if ($op->getJobType() === 'uninstall') { $devPackages[] = $op->getPackage(); } } return $devPackages; } /** * @return OperationInterface[] filtered operations, dev packages are uninstalled and all operations on them ignored */ private function filterDevPackageOperations(array $devPackages, array $operations, RepositoryInterface $localRepo) { $finalOps = array(); $packagesToSkip = array(); foreach ($devPackages as $pkg) { $packagesToSkip[$pkg->getName()] = true; if ($installedDevPkg = $localRepo->findPackage($pkg->getName(), '*')) { $finalOps[] = new UninstallOperation($installedDevPkg, 'non-dev install removing it'); } } // skip operations applied on dev packages foreach ($operations as $op) { $package = $op->getJobType() === 'update' ? $op->getTargetPackage() : $op->getPackage(); if (isset($packagesToSkip[$package->getName()])) { continue; } $finalOps[] = $op; } return $finalOps; } /** * Workaround: if your packages depend on plugins, we must be sure * that those are installed / updated first; else it would lead to packages * being installed multiple times in different folders, when running Composer * twice. * * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147, * it at least fixes the symptoms and makes usage of composer possible (again) * in such scenarios. * * @param OperationInterface[] $operations * @return OperationInterface[] reordered operation list */ private function movePluginsToFront(array $operations) { $pluginsNoDeps = array(); $pluginsWithDeps = array(); $pluginRequires = array(); foreach (array_reverse($operations, true) as $idx => $op) { if ($op instanceof InstallOperation) { $package = $op->getPackage(); } elseif ($op instanceof UpdateOperation) { $package = $op->getTargetPackage(); } else { continue; } // is this package a plugin? $isPlugin = $package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer'; // is this a plugin or a dependency of a plugin? if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) { // get the package's requires, but filter out any platform requirements or 'composer-plugin-api' $requires = array_filter(array_keys($package->getRequires()), function ($req) { return $req !== 'composer-plugin-api' && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req); }); // is this a plugin with no meaningful dependencies? if ($isPlugin && !count($requires)) { // plugins with no dependencies go to the very front array_unshift($pluginsNoDeps, $op); } else { // capture the requirements for this package so those packages will be moved up as well $pluginRequires = array_merge($pluginRequires, $requires); // move the operation to the front array_unshift($pluginsWithDeps, $op); } unset($operations[$idx]); } } return array_merge($pluginsNoDeps, $pluginsWithDeps, $operations); } /** * Removals of packages should be executed before installations in * case two packages resolve to the same path (due to custom installers) * * @param OperationInterface[] $operations * @return OperationInterface[] reordered operation list */ private function moveUninstallsToFront(array $operations) { $uninstOps = array(); foreach ($operations as $idx => $op) { if ($op instanceof UninstallOperation) { $uninstOps[] = $op; unset($operations[$idx]); } } return array_merge($uninstOps, $operations); } /** * @return RepositoryInterface */ private function createInstalledRepo(RepositoryInterface $localRepo, PlatformRepository $platformRepo) { // clone root package to have one in the installed repo that does not require anything // we don't want it to be uninstallable, but its requirements should not conflict // with the lock file for example $installedRootPackage = clone $this->package; $installedRootPackage->setRequires(array()); $installedRootPackage->setDevRequires(array()); $repos = array( $localRepo, new InstalledArrayRepository(array($installedRootPackage)), $platformRepo, ); $installedRepo = new CompositeRepository($repos); if ($this->additionalInstalledRepository) { $installedRepo->addRepository($this->additionalInstalledRepository); } return $installedRepo; } /** * @param RepositoryInterface|null $lockedRepository * @return Pool */ private function createPool(RepositoryInterface $lockedRepository = null) { if ($this->update) { $minimumStability = $this->package->getMinimumStability(); $stabilityFlags = $this->package->getStabilityFlags(); $requires = array_merge($this->package->getRequires(), $this->package->getDevRequires()); } else { $minimumStability = $this->locker->getMinimumStability(); $stabilityFlags = $this->locker->getStabilityFlags(); $requires = array(); foreach ($lockedRepository->getPackages() as $package) { $constraint = new Constraint('=', $package->getVersion()); $constraint->setPrettyString($package->getPrettyVersion()); $requires[$package->getName()] = $constraint; } } $rootConstraints = array(); foreach ($requires as $req => $constraint) { // skip platform requirements from the root package to avoid filtering out existing platform packages if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) { continue; } if ($constraint instanceof Link) { $rootConstraints[$req] = $constraint->getConstraint(); } else { $rootConstraints[$req] = $constraint; } } return new Pool($minimumStability, $stabilityFlags, $rootConstraints); } /** * @return DefaultPolicy */ private function createPolicy() { $preferStable = null; $preferLowest = null; if (!$this->update) { $preferStable = $this->locker->getPreferStable(); $preferLowest = $this->locker->getPreferLowest(); } // old lock file without prefer stable/lowest will return null // so in this case we use the composer.json info if (null === $preferStable) { $preferStable = $this->preferStable || $this->package->getPreferStable(); } if (null === $preferLowest) { $preferLowest = $this->preferLowest; } return new DefaultPolicy($preferStable, $preferLowest); } /** * @param RootPackageInterface $rootPackage * @param PlatformRepository $platformRepo * @return Request */ private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo) { $request = new Request(); $constraint = new Constraint('=', $rootPackage->getVersion()); $constraint->setPrettyString($rootPackage->getPrettyVersion()); $request->install($rootPackage->getName(), $constraint); $fixedPackages = $platformRepo->getPackages(); if ($this->additionalInstalledRepository) { $additionalFixedPackages = $this->additionalInstalledRepository->getPackages(); $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages); } // fix the version of all platform packages + additionally installed packages // to prevent the solver trying to remove or update those $provided = $rootPackage->getProvides(); foreach ($fixedPackages as $package) { $constraint = new Constraint('=', $package->getVersion()); $constraint->setPrettyString($package->getPrettyVersion()); // skip platform packages that are provided by the root package if ($package->getRepository() !== $platformRepo || !isset($provided[$package->getName()]) || !$provided[$package->getName()]->getConstraint()->matches($constraint) ) { $request->fix($package->getName(), $constraint); } } return $request; } /** * @param WritableRepositoryInterface $localRepo * @param Pool $pool * @param PolicyInterface $policy * @param array $repositories * @param RepositoryInterface $installedRepo * @param RepositoryInterface $lockedRepository * @param string $task * @param array|null $operations * @return array */ private function processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $task, array $operations = null) { if ($task === 'force-updates' && null === $operations) { throw new \InvalidArgumentException('Missing operations argument'); } if ($task === 'force-links') { $operations = array(); } if ($this->update && $this->updateWhitelist) { $currentPackages = $this->getCurrentPackages($installedRepo); } foreach ($localRepo->getCanonicalPackages() as $package) { // skip non-dev packages if (!$package->isDev()) { continue; } // skip packages that will be updated/uninstalled foreach ($operations as $operation) { if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package)) || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package)) ) { continue 2; } } if ($this->update) { // skip package if the whitelist is enabled and it is not in it if ($this->updateWhitelist && !$this->isUpdateable($package)) { // check if non-updateable packages are out of date compared to the lock file to ensure we don't corrupt it foreach ($currentPackages as $curPackage) { if ($curPackage->isDev() && $curPackage->getName() === $package->getName() && $curPackage->getVersion() === $package->getVersion()) { if ($task === 'force-links') { $package->setRequires($curPackage->getRequires()); $package->setConflicts($curPackage->getConflicts()); $package->setProvides($curPackage->getProvides()); $package->setReplaces($curPackage->getReplaces()); } elseif ($task === 'force-updates') { if (($curPackage->getSourceReference() && $curPackage->getSourceReference() !== $package->getSourceReference()) || ($curPackage->getDistReference() && $curPackage->getDistReference() !== $package->getDistReference()) ) { $operations[] = new UpdateOperation($package, $curPackage); } } break; } } continue; } // find similar packages (name/version) in all repositories $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion())); foreach ($matches as $index => $match) { // skip local packages if (!in_array($match->getRepository(), $repositories, true)) { unset($matches[$index]); continue; } // skip providers/replacers if ($match->getName() !== $package->getName()) { unset($matches[$index]); continue; } $matches[$index] = $match->getId(); } // select preferred package according to policy rules if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) { $newPackage = $pool->literalToPackage($matches[0]); if ($task === 'force-links' && $newPackage) { $package->setRequires($newPackage->getRequires()); $package->setConflicts($newPackage->getConflicts()); $package->setProvides($newPackage->getProvides()); $package->setReplaces($newPackage->getReplaces()); } if ($task === 'force-updates' && $newPackage && ( (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference()) || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference()) ) )) { $operations[] = new UpdateOperation($package, $newPackage); continue; } } if ($task === 'force-updates') { // force installed package to update to referenced version in root package if it does not match the installed version $references = $this->package->getReferences(); if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) { // changing the source ref to update to will be handled in the operations loop $operations[] = new UpdateOperation($package, clone $package); } } } else { // force update to locked version if it does not match the installed version foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) { if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) { if ($task === 'force-links') { $package->setRequires($lockedPackage->getRequires()); $package->setConflicts($lockedPackage->getConflicts()); $package->setProvides($lockedPackage->getProvides()); $package->setReplaces($lockedPackage->getReplaces()); } elseif ($task === 'force-updates') { if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference()) || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference()) ) { $operations[] = new UpdateOperation($package, $lockedPackage); } } break; } } } } return $operations; } /** * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback * @param RepositoryInterface $installedRepo * @return array */ private function getCurrentPackages($installedRepo) { if ($this->locker->isLocked()) { try { return $this->locker->getLockedRepository(true)->getPackages(); } catch (\RuntimeException $e) { // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file return $this->locker->getLockedRepository()->getPackages(); } } return $installedRepo->getPackages(); } /** * @return array */ private function getRootAliases() { if ($this->update) { $aliases = $this->package->getAliases(); } else { $aliases = $this->locker->getAliases(); } $normalizedAliases = array(); foreach ($aliases as $alias) { $normalizedAliases[$alias['package']][$alias['version']] = array( 'alias' => $alias['alias'], 'alias_normalized' => $alias['alias_normalized'], ); } return $normalizedAliases; } /** * @param Pool $pool * @param PolicyInterface $policy * @param WritableRepositoryInterface $localRepo * @param array $repositories */ private function processPackageUrls($pool, $policy, $localRepo, $repositories) { if (!$this->update) { return; } $rootRefs = $this->package->getReferences(); foreach ($localRepo->getCanonicalPackages() as $package) { // find similar packages (name/version) in all repositories $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion())); foreach ($matches as $index => $match) { // skip local packages if (!in_array($match->getRepository(), $repositories, true)) { unset($matches[$index]); continue; } // skip providers/replacers if ($match->getName() !== $package->getName()) { unset($matches[$index]); continue; } $matches[$index] = $match->getId(); } // select preferred package according to policy rules if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) { $newPackage = $pool->literalToPackage($matches[0]); // update the dist and source URLs $sourceUrl = $package->getSourceUrl(); $newSourceUrl = $newPackage->getSourceUrl(); $newReference = $newPackage->getSourceReference(); if ($package->isDev() && isset($rootRefs[$package->getName()]) && $package->getSourceReference() === $rootRefs[$package->getName()]) { $newReference = $rootRefs[$package->getName()]; } $this->updatePackageUrl($package, $newSourceUrl, $newPackage->getSourceType(), $newReference, $newPackage->getDistUrl()); if ($package instanceof CompletePackage && $newPackage instanceof CompletePackage) { $package->setAbandoned($newPackage->getReplacementPackage() ?: $newPackage->isAbandoned()); } $package->setDistMirrors($newPackage->getDistMirrors()); $package->setSourceMirrors($newPackage->getSourceMirrors()); } } } private function updatePackageUrl(PackageInterface $package, $sourceUrl, $sourceType, $sourceReference, $distUrl) { $oldSourceRef = $package->getSourceReference(); if ($package->getSourceUrl() !== $sourceUrl) { $package->setSourceType($sourceType); $package->setSourceUrl($sourceUrl); $package->setSourceReference($sourceReference); } // only update dist url for github/bitbucket dists as they use a combination of dist url + dist reference to install // but for other urls this is ambiguous and could result in bad outcomes if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com)/}i', $distUrl)) { $package->setDistUrl($distUrl); $this->updateInstallReferences($package, $sourceReference); } if ($this->updateWhitelist && !$this->isUpdateable($package)) { $this->updateInstallReferences($package, $oldSourceRef); } } private function updateInstallReferences(PackageInterface $package, $reference) { if (!$reference) { return; } $package->setSourceReference($reference); if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com)/}i', $package->getDistUrl())) { $package->setDistReference($reference); $package->setDistUrl(preg_replace('{(?<=/)[a-f0-9]{40}(?=/|$)}i', $reference, $package->getDistUrl())); } elseif ($package->getDistReference()) { // update the dist reference if there was one, but if none was provided ignore it $package->setDistReference($reference); } } /** * @param PlatformRepository $platformRepo * @param array $aliases */ private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases) { foreach ($aliases as $package => $versions) { foreach ($versions as $version => $alias) { $packages = $platformRepo->findPackages($package, $version); foreach ($packages as $package) { $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']); $aliasPackage->setRootPackageAlias(true); $platformRepo->addPackage($aliasPackage); } } } } /** * @param PackageInterface $package * @return bool */ private function isUpdateable(PackageInterface $package) { if (!$this->updateWhitelist) { throw new \LogicException('isUpdateable should only be called when a whitelist is present'); } foreach ($this->updateWhitelist as $whiteListedPattern => $void) { $patternRegexp = $this->packageNameToRegexp($whiteListedPattern); if (preg_match($patternRegexp, $package->getName())) { return true; } } return false; } /** * Build a regexp from a package name, expanding * globs as required * * @param string $whiteListedPattern * @return string */ private function packageNameToRegexp($whiteListedPattern) { $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern)); return "{^" . $cleanedWhiteListedPattern . "$}i"; } /** * @param array $links * @return array */ private function extractPlatformRequirements($links) { $platformReqs = array(); foreach ($links as $link) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) { $platformReqs[$link->getTarget()] = $link->getPrettyConstraint(); } } return $platformReqs; } /** * Adds all dependencies of the update whitelist to the whitelist, too. * * Packages which are listed as requirements in the root package will be * skipped including their dependencies, unless they are listed in the * update whitelist themselves or $whitelistAllDependencies is true. * * @param RepositoryInterface $localOrLockRepo Use the locked repo if available, otherwise installed repo will do * As we want the most accurate package list to work with, and installed * repo might be empty but locked repo will always be current. * @param array $rootRequires An array of links to packages in require of the root package * @param array $rootDevRequires An array of links to packages in require-dev of the root package */ private function whitelistUpdateDependencies($localOrLockRepo, array $rootRequires, array $rootDevRequires) { if (!$this->updateWhitelist) { return; } $rootRequires = array_merge($rootRequires, $rootDevRequires); $requiredPackageNames = array(); foreach ($rootRequires as $require) { $requiredPackageNames[] = $require->getTarget(); } $skipPackages = array(); if (!$this->whitelistAllDependencies) { foreach ($rootRequires as $require) { $skipPackages[$require->getTarget()] = true; } } $pool = new Pool('dev'); $pool->addRepository($localOrLockRepo); $seen = array(); $rootRequiredPackageNames = array_keys($rootRequires); foreach ($this->updateWhitelist as $packageName => $void) { $packageQueue = new \SplQueue; $depPackages = $pool->whatProvides($packageName); $nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true); // check if the name is a glob pattern that did not match directly if (!$nameMatchesRequiredPackage) { $whitelistPatternRegexp = $this->packageNameToRegexp($packageName); foreach ($rootRequiredPackageNames as $rootRequiredPackageName) { if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) { $nameMatchesRequiredPackage = true; break; } } } if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock', 'mirrors'))) { $this->io->writeError('Package "' . $packageName . '" listed for update is not installed. Ignoring.'); } foreach ($depPackages as $depPackage) { $packageQueue->enqueue($depPackage); } while (!$packageQueue->isEmpty()) { $package = $packageQueue->dequeue(); if (isset($seen[$package->getId()])) { continue; } $seen[$package->getId()] = true; $this->updateWhitelist[$package->getName()] = true; if (!$this->whitelistDependencies && !$this->whitelistAllDependencies) { continue; } $requires = $package->getRequires(); foreach ($requires as $require) { $requirePackages = $pool->whatProvides($require->getTarget()); foreach ($requirePackages as $requirePackage) { if (isset($this->updateWhitelist[$requirePackage->getName()])) { continue; } if (isset($skipPackages[$requirePackage->getName()])) { $this->io->writeError('Dependency "' . $requirePackage->getName() . '" is also a root requirement, but is not explicitly whitelisted. Ignoring.'); continue; } $packageQueue->enqueue($requirePackage); } } } } } /** * Replace local repositories with InstalledArrayRepository instances * * This is to prevent any accidental modification of the existing repos on disk * * @param RepositoryManager $rm */ private function mockLocalRepositories(RepositoryManager $rm) { $packages = array(); foreach ($rm->getLocalRepository()->getPackages() as $package) { $packages[(string) $package] = clone $package; } foreach ($packages as $key => $package) { if ($package instanceof AliasPackage) { $alias = (string) $package->getAliasOf(); $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion()); } } $rm->setLocalRepository( new InstalledArrayRepository($packages) ); } /** * Create Installer * * @param IOInterface $io * @param Composer $composer * @return Installer */ public static function create(IOInterface $io, Composer $composer) { return new static( $io, $composer->getConfig(), $composer->getPackage(), $composer->getDownloadManager(), $composer->getRepositoryManager(), $composer->getLocker(), $composer->getInstallationManager(), $composer->getEventDispatcher(), $composer->getAutoloadGenerator() ); } /** * @param RepositoryInterface $additionalInstalledRepository * @return $this */ public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository) { $this->additionalInstalledRepository = $additionalInstalledRepository; return $this; } /** * Whether to run in drymode or not * * @param bool $dryRun * @return Installer */ public function setDryRun($dryRun = true) { $this->dryRun = (bool) $dryRun; return $this; } /** * Checks, if this is a dry run (simulation mode). * * @return bool */ public function isDryRun() { return $this->dryRun; } /** * prefer source installation * * @param bool $preferSource * @return Installer */ public function setPreferSource($preferSource = true) { $this->preferSource = (bool) $preferSource; return $this; } /** * prefer dist installation * * @param bool $preferDist * @return Installer */ public function setPreferDist($preferDist = true) { $this->preferDist = (bool) $preferDist; return $this; } /** * Whether or not generated autoloader are optimized * * @param bool $optimizeAutoloader * @return Installer */ public function setOptimizeAutoloader($optimizeAutoloader = false) { $this->optimizeAutoloader = (bool) $optimizeAutoloader; if (!$this->optimizeAutoloader) { // Force classMapAuthoritative off when not optimizing the // autoloader $this->setClassMapAuthoritative(false); } return $this; } /** * Whether or not generated autoloader considers the class map * authoritative. * * @param bool $classMapAuthoritative * @return Installer */ public function setClassMapAuthoritative($classMapAuthoritative = false) { $this->classMapAuthoritative = (bool) $classMapAuthoritative; if ($this->classMapAuthoritative) { // Force optimizeAutoloader when classmap is authoritative $this->setOptimizeAutoloader(true); } return $this; } /** * Whether or not generated autoloader considers APCu caching. * * @param bool $apcuAutoloader * @return Installer */ public function setApcuAutoloader($apcuAutoloader = false) { $this->apcuAutoloader = (bool) $apcuAutoloader; return $this; } /** * update packages * * @param bool $update * @return Installer */ public function setUpdate($update = true) { $this->update = (bool) $update; return $this; } /** * enables dev packages * * @param bool $devMode * @return Installer */ public function setDevMode($devMode = true) { $this->devMode = (bool) $devMode; return $this; } /** * set whether to run autoloader or not * * This is disabled implicitly when enabling dryRun * * @param bool $dumpAutoloader * @return Installer */ public function setDumpAutoloader($dumpAutoloader = true) { $this->dumpAutoloader = (bool) $dumpAutoloader; return $this; } /** * set whether to run scripts or not * * This is disabled implicitly when enabling dryRun * * @param bool $runScripts * @return Installer */ public function setRunScripts($runScripts = true) { $this->runScripts = (bool) $runScripts; return $this; } /** * set the config instance * * @param Config $config * @return Installer */ public function setConfig(Config $config) { $this->config = $config; return $this; } /** * run in verbose mode * * @param bool $verbose * @return Installer */ public function setVerbose($verbose = true) { $this->verbose = (bool) $verbose; return $this; } /** * Checks, if running in verbose mode. * * @return bool */ public function isVerbose() { return $this->verbose; } /** * set ignore Platform Package requirements * * @param bool $ignorePlatformReqs * @return Installer */ public function setIgnorePlatformRequirements($ignorePlatformReqs = false) { $this->ignorePlatformReqs = (bool) $ignorePlatformReqs; return $this; } /** * restrict the update operation to a few packages, all other packages * that are already installed will be kept at their current version * * @param array $packages * @return Installer */ public function setUpdateWhitelist(array $packages) { $this->updateWhitelist = array_flip(array_map('strtolower', $packages)); return $this; } /** * @deprecated use setWhitelistTransitiveDependencies instead */ public function setWhitelistDependencies($updateDependencies = true) { return $this->setWhitelistTransitiveDependencies($updateDependencies); } /** * Should dependencies of whitelisted packages (but not direct dependencies) be updated? * * This will NOT whitelist any dependencies that are also directly defined * in the root package. * * @param bool $updateTransitiveDependencies * @return Installer */ public function setWhitelistTransitiveDependencies($updateTransitiveDependencies = true) { $this->whitelistDependencies = (bool) $updateTransitiveDependencies; return $this; } /** * Should all dependencies of whitelisted packages be updated recursively? * * This will whitelist any dependencies of the whitelisted packages, including * those defined in the root package. * * @param bool $updateAllDependencies * @return Installer */ public function setWhitelistAllDependencies($updateAllDependencies = true) { $this->whitelistAllDependencies = (bool) $updateAllDependencies; return $this; } /** * Should packages be preferred in a stable version when updating? * * @param bool $preferStable * @return Installer */ public function setPreferStable($preferStable = true) { $this->preferStable = (bool) $preferStable; return $this; } /** * Should packages be preferred in a lowest version when updating? * * @param bool $preferLowest * @return Installer */ public function setPreferLowest($preferLowest = true) { $this->preferLowest = (bool) $preferLowest; return $this; } /** * Should the lock file be updated when updating? * * This is disabled implicitly when enabling dryRun * * @param bool $writeLock * @return Installer */ public function setWriteLock($writeLock = true) { $this->writeLock = (bool) $writeLock; return $this; } /** * Should the operations (packge install, update and removal) be executed on disk? * * This is disabled implicitly when enabling dryRun * * @param bool $executeOperations * @return Installer */ public function setExecuteOperations($executeOperations = true) { $this->executeOperations = (bool) $executeOperations; return $this; } /** * Should suggestions be skipped? * * @param bool $skipSuggest * @return Installer */ public function setSkipSuggest($skipSuggest = true) { $this->skipSuggest = (bool) $skipSuggest; return $this; } /** * Disables plugins. * * Call this if you want to ensure that third-party code never gets * executed. The default is to automatically install, and execute * custom third-party installers. * * @return Installer */ public function disablePlugins() { $this->installationManager->disablePlugins(); return $this; } /** * @param SuggestedPackagesReporter $suggestedPackagesReporter * @return Installer */ public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter) { $this->suggestedPackagesReporter = $suggestedPackagesReporter; return $this; } } composer-1.6.3/src/Composer/Installer/000077500000000000000000000000001323436022200176605ustar00rootroot00000000000000composer-1.6.3/src/Composer/Installer/BinaryInstaller.php000066400000000000000000000154671323436022200235100ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Util\Silencer; /** * Utility to handle installation of package "bin"/binaries * * @author Jordi Boggiano * @author Konstantin Kudryashov * @author Helmut Hummel */ class BinaryInstaller { protected $binDir; protected $binCompat; protected $io; protected $filesystem; /** * @param IOInterface $io * @param string $binDir * @param string $binCompat * @param Filesystem $filesystem */ public function __construct(IOInterface $io, $binDir, $binCompat, Filesystem $filesystem = null) { $this->binDir = $binDir; $this->binCompat = $binCompat; $this->io = $io; $this->filesystem = $filesystem ?: new Filesystem(); } public function installBinaries(PackageInterface $package, $installPath, $warnOnOverwrite = true) { $binaries = $this->getBinaries($package); if (!$binaries) { return; } foreach ($binaries as $bin) { $binPath = $installPath.'/'.$bin; if (!file_exists($binPath)) { $this->io->writeError(' Skipped installation of bin '.$bin.' for package '.$package->getName().': file not found in package'); continue; } // in case a custom installer returned a relative path for the // $package, we can now safely turn it into a absolute path (as we // already checked the binary's existence). The following helpers // will require absolute paths to work properly. $binPath = realpath($binPath); $this->initializeBinDir(); $link = $this->binDir.'/'.basename($bin); if (file_exists($link)) { if (is_link($link)) { // likely leftover from a previous install, make sure // that the target is still executable in case this // is a fresh install of the vendor. Silencer::call('chmod', $link, 0777 & ~umask()); } if ($warnOnOverwrite) { $this->io->writeError(' Skipped installation of bin '.$bin.' for package '.$package->getName().': name conflicts with an existing file'); } continue; } if ($this->binCompat === "auto") { if (Platform::isWindows()) { $this->installFullBinaries($binPath, $link, $bin, $package); } else { $this->installSymlinkBinaries($binPath, $link); } } elseif ($this->binCompat === "full") { $this->installFullBinaries($binPath, $link, $bin, $package); } Silencer::call('chmod', $link, 0777 & ~umask()); } } public function removeBinaries(PackageInterface $package) { $this->initializeBinDir(); $binaries = $this->getBinaries($package); if (!$binaries) { return; } foreach ($binaries as $bin) { $link = $this->binDir.'/'.basename($bin); if (is_link($link) || file_exists($link)) { $this->filesystem->unlink($link); } if (file_exists($link.'.bat')) { $this->filesystem->unlink($link.'.bat'); } } // attempt removing the bin dir in case it is left empty if ((is_dir($this->binDir)) && ($this->filesystem->isDirEmpty($this->binDir))) { Silencer::call('rmdir', $this->binDir); } } public static function determineBinaryCaller($bin) { if ('.bat' === substr($bin, -4) || '.exe' === substr($bin, -4)) { return 'call'; } $handle = fopen($bin, 'r'); $line = fgets($handle); fclose($handle); if (preg_match('{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m', $line, $match)) { return trim($match[1]); } return 'php'; } protected function getBinaries(PackageInterface $package) { return $package->getBinaries(); } protected function installFullBinaries($binPath, $link, $bin, PackageInterface $package) { // add unixy support for cygwin and similar environments if ('.bat' !== substr($binPath, -4)) { $this->installUnixyProxyBinaries($binPath, $link); @chmod($link, 0777 & ~umask()); $link .= '.bat'; if (file_exists($link)) { $this->io->writeError(' Skipped installation of bin '.$bin.'.bat proxy for package '.$package->getName().': a .bat proxy was already installed'); } } if (!file_exists($link)) { file_put_contents($link, $this->generateWindowsProxyCode($binPath, $link)); } } protected function installSymlinkBinaries($binPath, $link) { if (!$this->filesystem->relativeSymlink($binPath, $link)) { $this->installUnixyProxyBinaries($binPath, $link); } } protected function installUnixyProxyBinaries($binPath, $link) { file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link)); } protected function initializeBinDir() { $this->filesystem->ensureDirectoryExists($this->binDir); $this->binDir = realpath($this->binDir); } protected function generateWindowsProxyCode($bin, $link) { $binPath = $this->filesystem->findShortestPath($link, $bin); $caller = self::determineBinaryCaller($bin); return "@ECHO OFF\r\n". "setlocal DISABLEDELAYEDEXPANSION\r\n". "SET BIN_TARGET=%~dp0/".trim(ProcessExecutor::escape($binPath), '"\'')."\r\n". "{$caller} \"%BIN_TARGET%\" %*\r\n"; } protected function generateUnixyProxyCode($bin, $link) { $binPath = $this->filesystem->findShortestPath($link, $bin); $binDir = ProcessExecutor::escape(dirname($binPath)); $binFile = basename($binPath); $proxyCode = << /dev/null; cd $binDir && pwd) if [ -d /proc/cygdrive ] && [[ \$(which php) == \$(readlink -n /proc/cygdrive)/* ]]; then # We are in Cgywin using Windows php, so the path must be translated dir=\$(cygpath -m "\$dir"); fi "\${dir}/$binFile" "\$@" PROXY; return $proxyCode; } } composer-1.6.3/src/Composer/Installer/BinaryPresenceInterface.php000066400000000000000000000013331323436022200251230ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Package\PackageInterface; /** * Interface for the package installation manager that handle binary installation. * * @author Jordi Boggiano */ interface BinaryPresenceInterface { /** * Make sure binaries are installed for a given package. * * @param PackageInterface $package package instance */ public function ensureBinariesPresence(PackageInterface $package); } composer-1.6.3/src/Composer/Installer/InstallationManager.php000066400000000000000000000250171323436022200243320ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Repository\RepositoryInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation; use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation; use Composer\Util\StreamContextFactory; /** * Package operation manager. * * @author Konstantin Kudryashov * @author Jordi Boggiano * @author Nils Adermann */ class InstallationManager { private $installers = array(); private $cache = array(); private $notifiablePackages = array(); public function reset() { $this->notifiablePackages = array(); } /** * Adds installer * * @param InstallerInterface $installer installer instance */ public function addInstaller(InstallerInterface $installer) { array_unshift($this->installers, $installer); $this->cache = array(); } /** * Removes installer * * @param InstallerInterface $installer installer instance */ public function removeInstaller(InstallerInterface $installer) { if (false !== ($key = array_search($installer, $this->installers, true))) { array_splice($this->installers, $key, 1); $this->cache = array(); } } /** * Disables plugins. * * We prevent any plugins from being instantiated by simply * deactivating the installer for them. This ensure that no third-party * code is ever executed. */ public function disablePlugins() { foreach ($this->installers as $i => $installer) { if (!$installer instanceof PluginInstaller) { continue; } unset($this->installers[$i]); } } /** * Returns installer for a specific package type. * * @param string $type package type * * @throws \InvalidArgumentException if installer for provided type is not registered * @return InstallerInterface */ public function getInstaller($type) { $type = strtolower($type); if (isset($this->cache[$type])) { return $this->cache[$type]; } foreach ($this->installers as $installer) { if ($installer->supports($type)) { return $this->cache[$type] = $installer; } } throw new \InvalidArgumentException('Unknown installer type: '.$type); } /** * Checks whether provided package is installed in one of the registered installers. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance * * @return bool */ public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { if ($package instanceof AliasPackage) { return $repo->hasPackage($package) && $this->isPackageInstalled($repo, $package->getAliasOf()); } return $this->getInstaller($package->getType())->isInstalled($repo, $package); } /** * Install binary for the given package. * If the installer associated to this package doesn't handle that function, it'll do nothing. * * @param PackageInterface $package Package instance */ public function ensureBinariesPresence(PackageInterface $package) { try { $installer = $this->getInstaller($package->getType()); } catch (\InvalidArgumentException $e) { // no installer found for the current package type (@see `getInstaller()`) return; } // if the given installer support installing binaries if ($installer instanceof BinaryPresenceInterface) { $installer->ensureBinariesPresence($package); } } /** * Executes solver operation. * * @param RepositoryInterface $repo repository in which to check * @param OperationInterface $operation operation instance */ public function execute(RepositoryInterface $repo, OperationInterface $operation) { $method = $operation->getJobType(); $this->$method($repo, $operation); } /** * Executes install operation. * * @param RepositoryInterface $repo repository in which to check * @param InstallOperation $operation operation instance */ public function install(RepositoryInterface $repo, InstallOperation $operation) { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); $installer->install($repo, $package); $this->markForNotification($package); } /** * Executes update operation. * * @param RepositoryInterface $repo repository in which to check * @param UpdateOperation $operation operation instance */ public function update(RepositoryInterface $repo, UpdateOperation $operation) { $initial = $operation->getInitialPackage(); $target = $operation->getTargetPackage(); $initialType = $initial->getType(); $targetType = $target->getType(); if ($initialType === $targetType) { $installer = $this->getInstaller($initialType); $installer->update($repo, $initial, $target); $this->markForNotification($target); } else { $this->getInstaller($initialType)->uninstall($repo, $initial); $this->getInstaller($targetType)->install($repo, $target); } } /** * Uninstalls package. * * @param RepositoryInterface $repo repository in which to check * @param UninstallOperation $operation operation instance */ public function uninstall(RepositoryInterface $repo, UninstallOperation $operation) { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); $installer->uninstall($repo, $package); } /** * Executes markAliasInstalled operation. * * @param RepositoryInterface $repo repository in which to check * @param MarkAliasInstalledOperation $operation operation instance */ public function markAliasInstalled(RepositoryInterface $repo, MarkAliasInstalledOperation $operation) { $package = $operation->getPackage(); if (!$repo->hasPackage($package)) { $repo->addPackage(clone $package); } } /** * Executes markAlias operation. * * @param RepositoryInterface $repo repository in which to check * @param MarkAliasUninstalledOperation $operation operation instance */ public function markAliasUninstalled(RepositoryInterface $repo, MarkAliasUninstalledOperation $operation) { $package = $operation->getPackage(); $repo->removePackage($package); } /** * Returns the installation path of a package * * @param PackageInterface $package * @return string path */ public function getInstallPath(PackageInterface $package) { $installer = $this->getInstaller($package->getType()); return $installer->getInstallPath($package); } public function notifyInstalls(IOInterface $io) { foreach ($this->notifiablePackages as $repoUrl => $packages) { $repositoryName = parse_url($repoUrl, PHP_URL_HOST); if ($io->hasAuthentication($repositoryName)) { $auth = $io->getAuthentication($repositoryName); $authStr = base64_encode($auth['username'] . ':' . $auth['password']); $authHeader = 'Authorization: Basic '.$authStr; } // non-batch API, deprecated if (strpos($repoUrl, '%package%')) { foreach ($packages as $package) { $url = str_replace('%package%', $package->getPrettyName(), $repoUrl); $params = array( 'version' => $package->getPrettyVersion(), 'version_normalized' => $package->getVersion(), ); $opts = array('http' => array( 'method' => 'POST', 'header' => array('Content-type: application/x-www-form-urlencoded'), 'content' => http_build_query($params, '', '&'), 'timeout' => 3, ), ); if (isset($authHeader)) { $opts['http']['header'][] = $authHeader; } $context = StreamContextFactory::getContext($url, $opts); @file_get_contents($url, false, $context); } continue; } $postData = array('downloads' => array()); foreach ($packages as $package) { $postData['downloads'][] = array( 'name' => $package->getPrettyName(), 'version' => $package->getVersion(), ); } $opts = array('http' => array( 'method' => 'POST', 'header' => array('Content-Type: application/json'), 'content' => json_encode($postData), 'timeout' => 6, ), ); if (isset($authHeader)) { $opts['http']['header'][] = $authHeader; } $context = StreamContextFactory::getContext($repoUrl, $opts); @file_get_contents($repoUrl, false, $context); } $this->reset(); } private function markForNotification(PackageInterface $package) { if ($package->getNotificationUrl()) { $this->notifiablePackages[$package->getNotificationUrl()][$package->getName()] = $package; } } } composer-1.6.3/src/Composer/Installer/InstallerEvent.php000066400000000000000000000062241323436022200233340ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Composer; use Composer\DependencyResolver\PolicyInterface; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Request; use Composer\EventDispatcher\Event; use Composer\IO\IOInterface; use Composer\Repository\CompositeRepository; /** * An event for all installer. * * @author François Pluchino */ class InstallerEvent extends Event { /** * @var Composer */ private $composer; /** * @var IOInterface */ private $io; /** * @var bool */ private $devMode; /** * @var PolicyInterface */ private $policy; /** * @var Pool */ private $pool; /** * @var CompositeRepository */ private $installedRepo; /** * @var Request */ private $request; /** * @var OperationInterface[] */ private $operations; /** * Constructor. * * @param string $eventName * @param Composer $composer * @param IOInterface $io * @param bool $devMode * @param PolicyInterface $policy * @param Pool $pool * @param CompositeRepository $installedRepo * @param Request $request * @param OperationInterface[] $operations */ public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array()) { parent::__construct($eventName); $this->composer = $composer; $this->io = $io; $this->devMode = $devMode; $this->policy = $policy; $this->pool = $pool; $this->installedRepo = $installedRepo; $this->request = $request; $this->operations = $operations; } /** * @return Composer */ public function getComposer() { return $this->composer; } /** * @return IOInterface */ public function getIO() { return $this->io; } /** * @return bool */ public function isDevMode() { return $this->devMode; } /** * @return PolicyInterface */ public function getPolicy() { return $this->policy; } /** * @return Pool */ public function getPool() { return $this->pool; } /** * @return CompositeRepository */ public function getInstalledRepo() { return $this->installedRepo; } /** * @return Request */ public function getRequest() { return $this->request; } /** * @return OperationInterface[] */ public function getOperations() { return $this->operations; } } composer-1.6.3/src/Composer/Installer/InstallerEvents.php000066400000000000000000000020171323436022200235130ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; /** * The Installer Events. * * @author François Pluchino */ class InstallerEvents { /** * The PRE_DEPENDENCIES_SOLVING event occurs as a installer begins * resolve operations. * * The event listener method receives a * Composer\Installer\InstallerEvent instance. * * @var string */ const PRE_DEPENDENCIES_SOLVING = 'pre-dependencies-solving'; /** * The POST_DEPENDENCIES_SOLVING event occurs as a installer after * resolve operations. * * The event listener method receives a * Composer\Installer\InstallerEvent instance. * * @var string */ const POST_DEPENDENCIES_SOLVING = 'post-dependencies-solving'; } composer-1.6.3/src/Composer/Installer/InstallerInterface.php000066400000000000000000000046311323436022200241530ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepositoryInterface; use InvalidArgumentException; /** * Interface for the package installation manager. * * @author Konstantin Kudryashov * @author Jordi Boggiano */ interface InstallerInterface { /** * Decides if the installer supports the given type * * @param string $packageType * @return bool */ public function supports($packageType); /** * Checks that provided package is installed. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance * * @return bool */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package); /** * Installs specific package. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package); /** * Updates specific package. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $initial already installed package version * @param PackageInterface $target updated version * * @throws InvalidArgumentException if $initial package is not installed */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target); /** * Uninstalls specific package. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package); /** * Returns the installation path of a package * * @param PackageInterface $package * @return string path */ public function getInstallPath(PackageInterface $package); } composer-1.6.3/src/Composer/Installer/LibraryInstaller.php000066400000000000000000000162371323436022200236640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; use Composer\Util\Filesystem; use Composer\Util\Silencer; /** * Package installation manager. * * @author Jordi Boggiano * @author Konstantin Kudryashov */ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface { protected $composer; protected $vendorDir; protected $binDir; protected $downloadManager; protected $io; protected $type; protected $filesystem; protected $binCompat; protected $binaryInstaller; /** * Initializes library installer. * * @param IOInterface $io * @param Composer $composer * @param string $type * @param Filesystem $filesystem * @param BinaryInstaller $binaryInstaller */ public function __construct(IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null) { $this->composer = $composer; $this->downloadManager = $composer->getDownloadManager(); $this->io = $io; $this->type = $type; $this->filesystem = $filesystem ?: new Filesystem(); $this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/'); $this->binaryInstaller = $binaryInstaller ?: new BinaryInstaller($this->io, rtrim($composer->getConfig()->get('bin-dir'), '/'), $composer->getConfig()->get('bin-compat'), $this->filesystem); } /** * {@inheritDoc} */ public function supports($packageType) { return $packageType === $this->type || null === $this->type; } /** * {@inheritDoc} */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { return $repo->hasPackage($package) && is_readable($this->getInstallPath($package)); } /** * {@inheritDoc} */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $this->initializeVendorDir(); $downloadPath = $this->getInstallPath($package); // remove the binaries if it appears the package files are missing if (!is_readable($downloadPath) && $repo->hasPackage($package)) { $this->binaryInstaller->removeBinaries($package); } $this->installCode($package); $this->binaryInstaller->installBinaries($package, $this->getInstallPath($package)); if (!$repo->hasPackage($package)) { $repo->addPackage(clone $package); } } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { if (!$repo->hasPackage($initial)) { throw new \InvalidArgumentException('Package is not installed: '.$initial); } $this->initializeVendorDir(); $this->binaryInstaller->removeBinaries($initial); $this->updateCode($initial, $target); $this->binaryInstaller->installBinaries($target, $this->getInstallPath($target)); $repo->removePackage($initial); if (!$repo->hasPackage($target)) { $repo->addPackage(clone $target); } } /** * {@inheritDoc} */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { if (!$repo->hasPackage($package)) { throw new \InvalidArgumentException('Package is not installed: '.$package); } $this->removeCode($package); $this->binaryInstaller->removeBinaries($package); $repo->removePackage($package); $downloadPath = $this->getPackageBasePath($package); if (strpos($package->getName(), '/')) { $packageVendorDir = dirname($downloadPath); if (is_dir($packageVendorDir) && $this->filesystem->isDirEmpty($packageVendorDir)) { Silencer::call('rmdir', $packageVendorDir); } } } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { $this->initializeVendorDir(); $basePath = ($this->vendorDir ? $this->vendorDir.'/' : '') . $package->getPrettyName(); $targetDir = $package->getTargetDir(); return $basePath . ($targetDir ? '/'.$targetDir : ''); } /** * Make sure binaries are installed for a given package. * * @param PackageInterface $package Package instance */ public function ensureBinariesPresence(PackageInterface $package) { $this->binaryInstaller->installBinaries($package, $this->getInstallPath($package), false); } /** * Returns the base path of the package without target-dir path * * It is used for BC as getInstallPath tends to be overridden by * installer plugins but not getPackageBasePath * * @param PackageInterface $package * @return string */ protected function getPackageBasePath(PackageInterface $package) { $installPath = $this->getInstallPath($package); $targetDir = $package->getTargetDir(); if ($targetDir) { return preg_replace('{/*'.str_replace('/', '/+', preg_quote($targetDir)).'/?$}', '', $installPath); } return $installPath; } protected function installCode(PackageInterface $package) { $downloadPath = $this->getInstallPath($package); $this->downloadManager->download($package, $downloadPath); } protected function updateCode(PackageInterface $initial, PackageInterface $target) { $initialDownloadPath = $this->getInstallPath($initial); $targetDownloadPath = $this->getInstallPath($target); if ($targetDownloadPath !== $initialDownloadPath) { // if the target and initial dirs intersect, we force a remove + install // to avoid the rename wiping the target dir as part of the initial dir cleanup if (substr($initialDownloadPath, 0, strlen($targetDownloadPath)) === $targetDownloadPath || substr($targetDownloadPath, 0, strlen($initialDownloadPath)) === $initialDownloadPath ) { $this->removeCode($initial); $this->installCode($target); return; } $this->filesystem->rename($initialDownloadPath, $targetDownloadPath); } $this->downloadManager->update($initial, $target, $targetDownloadPath); } protected function removeCode(PackageInterface $package) { $downloadPath = $this->getPackageBasePath($package); $this->downloadManager->remove($package, $downloadPath); } protected function initializeVendorDir() { $this->filesystem->ensureDirectoryExists($this->vendorDir); $this->vendorDir = realpath($this->vendorDir); } } composer-1.6.3/src/Composer/Installer/MetapackageInstaller.php000066400000000000000000000035711323436022200244570ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; /** * Metapackage installation manager. * * @author Martin Hasoň */ class MetapackageInstaller implements InstallerInterface { /** * {@inheritDoc} */ public function supports($packageType) { return $packageType === 'metapackage'; } /** * {@inheritDoc} */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { return $repo->hasPackage($package); } /** * {@inheritDoc} */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $repo->addPackage(clone $package); } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { if (!$repo->hasPackage($initial)) { throw new \InvalidArgumentException('Package is not installed: '.$initial); } $repo->removePackage($initial); $repo->addPackage(clone $target); } /** * {@inheritDoc} */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { if (!$repo->hasPackage($package)) { throw new \InvalidArgumentException('Package is not installed: '.$package); } $repo->removePackage($package); } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { return ''; } } composer-1.6.3/src/Composer/Installer/NoopInstaller.php000066400000000000000000000041561323436022200231700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; /** * Does not install anything but marks packages installed in the repo * * Useful for dry runs * * @author Jordi Boggiano */ class NoopInstaller implements InstallerInterface { /** * {@inheritDoc} */ public function supports($packageType) { return true; } /** * {@inheritDoc} */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { return $repo->hasPackage($package); } /** * {@inheritDoc} */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { if (!$repo->hasPackage($package)) { $repo->addPackage(clone $package); } } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { if (!$repo->hasPackage($initial)) { throw new \InvalidArgumentException('Package is not installed: '.$initial); } $repo->removePackage($initial); if (!$repo->hasPackage($target)) { $repo->addPackage(clone $target); } } /** * {@inheritDoc} */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { if (!$repo->hasPackage($package)) { throw new \InvalidArgumentException('Package is not installed: '.$package); } $repo->removePackage($package); } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { $targetDir = $package->getTargetDir(); return $package->getPrettyName() . ($targetDir ? '/'.$targetDir : ''); } } composer-1.6.3/src/Composer/Installer/PackageEvent.php000066400000000000000000000035241323436022200227320ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Composer; use Composer\IO\IOInterface; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\DependencyResolver\PolicyInterface; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Request; use Composer\Repository\CompositeRepository; /** * The Package Event. * * @author Jordi Boggiano */ class PackageEvent extends InstallerEvent { /** * @var OperationInterface The package instance */ private $operation; /** * Constructor. * * @param string $eventName * @param Composer $composer * @param IOInterface $io * @param bool $devMode * @param PolicyInterface $policy * @param Pool $pool * @param CompositeRepository $installedRepo * @param Request $request * @param OperationInterface[] $operations * @param OperationInterface $operation */ public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation) { parent::__construct($eventName, $composer, $io, $devMode, $policy, $pool, $installedRepo, $request, $operations); $this->operation = $operation; } /** * Returns the package instance. * * @return OperationInterface */ public function getOperation() { return $this->operation; } } composer-1.6.3/src/Composer/Installer/PackageEvents.php000066400000000000000000000037441323436022200231210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; /** * Package Events. * * @author Jordi Boggiano */ class PackageEvents { /** * The PRE_PACKAGE_INSTALL event occurs before a package is installed. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const PRE_PACKAGE_INSTALL = 'pre-package-install'; /** * The POST_PACKAGE_INSTALL event occurs after a package is installed. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const POST_PACKAGE_INSTALL = 'post-package-install'; /** * The PRE_PACKAGE_UPDATE event occurs before a package is updated. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const PRE_PACKAGE_UPDATE = 'pre-package-update'; /** * The POST_PACKAGE_UPDATE event occurs after a package is updated. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const POST_PACKAGE_UPDATE = 'post-package-update'; /** * The PRE_PACKAGE_UNINSTALL event occurs before a package has been uninstalled. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const PRE_PACKAGE_UNINSTALL = 'pre-package-uninstall'; /** * The POST_PACKAGE_UNINSTALL event occurs after a package has been uninstalled. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @var string */ const POST_PACKAGE_UNINSTALL = 'post-package-uninstall'; } composer-1.6.3/src/Composer/Installer/PearBinaryInstaller.php000066400000000000000000000114761323436022200243140ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Util\Filesystem; use Composer\Util\ProcessExecutor; /** * Utility to handle installation of package "bin"/binaries for PEAR packages * * @author Jordi Boggiano */ class PearBinaryInstaller extends BinaryInstaller { private $installer; private $vendorDir; /** * @param IOInterface $io * @param string $binDir * @param string $vendorDir * @param string $binCompat * @param Filesystem $filesystem * @param PearInstaller $installer */ public function __construct(IOInterface $io, $binDir, $vendorDir, $binCompat, Filesystem $filesystem, PearInstaller $installer) { parent::__construct($io, $binDir, $binCompat, $filesystem); $this->installer = $installer; $this->vendorDir = $vendorDir; } protected function getBinaries(PackageInterface $package) { $binariesPath = $this->installer->getInstallPath($package) . '/bin/'; $binaries = array(); if (file_exists($binariesPath)) { foreach (new \FilesystemIterator($binariesPath, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO) as $fileName => $value) { if (!$value->isDir()) { $binaries[] = 'bin/'.$fileName; } } } return $binaries; } protected function initializeBinDir() { parent::initializeBinDir(); file_put_contents($this->binDir.'/composer-php', $this->generateUnixyPhpProxyCode()); @chmod($this->binDir.'/composer-php', 0777); file_put_contents($this->binDir.'/composer-php.bat', $this->generateWindowsPhpProxyCode()); @chmod($this->binDir.'/composer-php.bat', 0777); } protected function generateWindowsProxyCode($bin, $link) { $binPath = $this->filesystem->findShortestPath($link, $bin); if ('.bat' === substr($bin, -4)) { $caller = 'call'; } else { $handle = fopen($bin, 'r'); $line = fgets($handle); fclose($handle); if (preg_match('{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m', $line, $match)) { $caller = trim($match[1]); } else { $caller = 'php'; } if ($caller === 'php') { return "@echo off\r\n". "pushd .\r\n". "cd %~dp0\r\n". "set PHP_PROXY=%CD%\\composer-php.bat\r\n". "cd ".ProcessExecutor::escape(dirname($binPath))."\r\n". "set BIN_TARGET=%CD%\\".basename($binPath)."\r\n". "popd\r\n". "%PHP_PROXY% \"%BIN_TARGET%\" %*\r\n"; } } return "@echo off\r\n". "pushd .\r\n". "cd %~dp0\r\n". "cd ".ProcessExecutor::escape(dirname($binPath))."\r\n". "set BIN_TARGET=%CD%\\".basename($binPath)."\r\n". "popd\r\n". $caller." \"%BIN_TARGET%\" %*\r\n"; } private function generateWindowsPhpProxyCode() { $binToVendor = $this->filesystem->findShortestPath($this->binDir, $this->vendorDir, true); return "@echo off\r\n" . "setlocal enabledelayedexpansion\r\n" . "set BIN_DIR=%~dp0\r\n" . "set VENDOR_DIR=%BIN_DIR%\\".$binToVendor."\r\n" . "set DIRS=.\r\n" . "FOR /D %%V IN (%VENDOR_DIR%\\*) DO (\r\n" . " FOR /D %%P IN (%%V\\*) DO (\r\n" . " set DIRS=!DIRS!;%%~fP\r\n" . " )\r\n" . ")\r\n" . "php.exe -d include_path=!DIRS! %*\r\n"; } private function generateUnixyPhpProxyCode() { $binToVendor = $this->filesystem->findShortestPath($this->binDir, $this->vendorDir, true); return "#!/usr/bin/env sh\n". "SRC_DIR=`pwd`\n". "BIN_DIR=`dirname $0`\n". "VENDOR_DIR=\$BIN_DIR/".escapeshellarg($binToVendor)."\n". "DIRS=\"\"\n". "for vendor in \$VENDOR_DIR/*; do\n". " if [ -d \"\$vendor\" ]; then\n". " for package in \$vendor/*; do\n". " if [ -d \"\$package\" ]; then\n". " DIRS=\"\${DIRS}:\${package}\"\n". " fi\n". " done\n". " fi\n". "done\n". "php -d include_path=\".\$DIRS\" $@\n"; } } composer-1.6.3/src/Composer/Installer/PearInstaller.php000066400000000000000000000054661323436022200231510ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\IO\IOInterface; use Composer\Composer; use Composer\Downloader\PearPackageExtractor; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; use Composer\Util\Platform; use Composer\Util\Filesystem; /** * Package installation manager. * * @author Jordi Boggiano * @author Konstantin Kudryashov */ class PearInstaller extends LibraryInstaller { /** * Initializes library installer. * * @param IOInterface $io io instance * @param Composer $composer * @param string $type package type that this installer handles */ public function __construct(IOInterface $io, Composer $composer, $type = 'pear-library') { $filesystem = new Filesystem(); $binaryInstaller = new PearBinaryInstaller($io, rtrim($composer->getConfig()->get('bin-dir'), '/'), rtrim($composer->getConfig()->get('vendor-dir'), '/'), $composer->getConfig()->get('bin-compat'), $filesystem, $this); parent::__construct($io, $composer, $type, $filesystem, $binaryInstaller); } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { $this->uninstall($repo, $initial); $this->install($repo, $target); } protected function installCode(PackageInterface $package) { parent::installCode($package); $isWindows = Platform::isWindows(); $php_bin = $this->binDir . ($isWindows ? '/composer-php.bat' : '/composer-php'); if (!$isWindows) { $php_bin = '/usr/bin/env ' . $php_bin; } $installPath = $this->getInstallPath($package); $vars = array( 'os' => $isWindows ? 'windows' : 'linux', 'php_bin' => $php_bin, 'pear_php' => $installPath, 'php_dir' => $installPath, 'bin_dir' => $installPath . '/bin', 'data_dir' => $installPath . '/data', 'version' => $package->getPrettyVersion(), ); $packageArchive = $this->getInstallPath($package).'/'.pathinfo($package->getDistUrl(), PATHINFO_BASENAME); $pearExtractor = new PearPackageExtractor($packageArchive); $pearExtractor->extractTo($this->getInstallPath($package), array('php' => '/', 'script' => '/bin', 'data' => '/data'), $vars); $this->io->writeError(' Cleaning up', true, IOInterface::VERBOSE); $this->filesystem->unlink($packageArchive); } } composer-1.6.3/src/Composer/Installer/PluginInstaller.php000066400000000000000000000050641323436022200235120ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; /** * Installer for plugin packages * * @author Jordi Boggiano * @author Nils Adermann */ class PluginInstaller extends LibraryInstaller { private $installationManager; /** * Initializes Plugin installer. * * @param IOInterface $io * @param Composer $composer * @param string $type */ public function __construct(IOInterface $io, Composer $composer, $type = 'library') { parent::__construct($io, $composer, 'composer-plugin'); $this->installationManager = $composer->getInstallationManager(); } /** * {@inheritDoc} */ public function supports($packageType) { return $packageType === 'composer-plugin' || $packageType === 'composer-installer'; } /** * {@inheritDoc} */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $extra = $package->getExtra(); if (empty($extra['class'])) { throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.'); } parent::install($repo, $package); try { $this->composer->getPluginManager()->registerPackage($package, true); } catch (\Exception $e) { // Rollback installation $this->io->writeError('Plugin installation failed, rolling back'); parent::uninstall($repo, $package); throw $e; } } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { $extra = $target->getExtra(); if (empty($extra['class'])) { throw new \UnexpectedValueException('Error while installing '.$target->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.'); } parent::update($repo, $initial, $target); $this->composer->getPluginManager()->registerPackage($target, true); } } composer-1.6.3/src/Composer/Installer/ProjectInstaller.php000066400000000000000000000050571323436022200236640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\Package\PackageInterface; use Composer\Downloader\DownloadManager; use Composer\Repository\InstalledRepositoryInterface; use Composer\Util\Filesystem; /** * Project Installer is used to install a single package into a directory as * root project. * * @author Benjamin Eberlei */ class ProjectInstaller implements InstallerInterface { private $installPath; private $downloadManager; private $filesystem; public function __construct($installPath, DownloadManager $dm) { $this->installPath = rtrim(strtr($installPath, '\\', '/'), '/').'/'; $this->downloadManager = $dm; $this->filesystem = new Filesystem; } /** * Decides if the installer supports the given type * * @param string $packageType * @return bool */ public function supports($packageType) { return true; } /** * {@inheritDoc} */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { return false; } /** * {@inheritDoc} */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $installPath = $this->installPath; if (file_exists($installPath) && !$this->filesystem->isDirEmpty($installPath)) { throw new \InvalidArgumentException("Project directory $installPath is not empty."); } if (!is_dir($installPath)) { mkdir($installPath, 0777, true); } $this->downloadManager->download($package, $installPath); } /** * {@inheritDoc} */ public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { throw new \InvalidArgumentException("not supported"); } /** * {@inheritDoc} */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { throw new \InvalidArgumentException("not supported"); } /** * Returns the installation path of a package * * @param PackageInterface $package * @return string path */ public function getInstallPath(PackageInterface $package) { return $this->installPath; } } composer-1.6.3/src/Composer/Installer/SuggestedPackagesReporter.php000066400000000000000000000076251323436022200255170ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Installer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Repository\RepositoryInterface; use Symfony\Component\Console\Formatter\OutputFormatter; /** * Add suggested packages from different places to output them in the end. * * @author Haralan Dobrev */ class SuggestedPackagesReporter { /** * @var array */ protected $suggestedPackages = array(); /** * @var IOInterface */ private $io; public function __construct(IOInterface $io) { $this->io = $io; } /** * @return array Suggested packages with source, target and reason keys. */ public function getPackages() { return $this->suggestedPackages; } /** * Add suggested packages to be listed after install * * Could be used to add suggested packages both from the installer * or from CreateProjectCommand. * * @param string $source Source package which made the suggestion * @param string $target Target package to be suggested * @param string $reason Reason the target package to be suggested * @return SuggestedPackagesReporter */ public function addPackage($source, $target, $reason) { $this->suggestedPackages[] = array( 'source' => $source, 'target' => $target, 'reason' => $reason, ); return $this; } /** * Add all suggestions from a package. * * @param PackageInterface $package * @return SuggestedPackagesReporter */ public function addSuggestionsFromPackage(PackageInterface $package) { $source = $package->getPrettyName(); foreach ($package->getSuggests() as $target => $reason) { $this->addPackage( $source, $target, $reason ); } return $this; } /** * Output suggested packages. * Do not list the ones already installed if installed repository provided. * * @param RepositoryInterface $installedRepo Installed packages * @return SuggestedPackagesReporter */ public function output(RepositoryInterface $installedRepo = null) { $suggestedPackages = $this->getPackages(); $installedPackages = array(); if (null !== $installedRepo && ! empty($suggestedPackages)) { foreach ($installedRepo->getPackages() as $package) { $installedPackages = array_merge( $installedPackages, $package->getNames() ); } } foreach ($suggestedPackages as $suggestion) { if (in_array($suggestion['target'], $installedPackages)) { continue; } $this->io->writeError(sprintf( '%s suggests installing %s (%s)', $suggestion['source'], $this->escapeOutput($suggestion['target']), $this->escapeOutput($suggestion['reason']) )); } return $this; } /** * @param string $string * @return string */ private function escapeOutput($string) { return OutputFormatter::escape( $this->removeControlCharacters($string) ); } /** * @param string $string * @return string */ private function removeControlCharacters($string) { return preg_replace( '/[[:cntrl:]]/', '', str_replace("\n", ' ', $string) ); } } composer-1.6.3/src/Composer/Json/000077500000000000000000000000001323436022200166345ustar00rootroot00000000000000composer-1.6.3/src/Composer/Json/JsonFile.php000066400000000000000000000224671323436022200210710ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Json; use JsonSchema\Validator; use Seld\JsonLint\JsonParser; use Seld\JsonLint\ParsingException; use Composer\Util\RemoteFilesystem; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; /** * Reads/writes json files. * * @author Konstantin Kudryashiv * @author Jordi Boggiano */ class JsonFile { const LAX_SCHEMA = 1; const STRICT_SCHEMA = 2; const JSON_UNESCAPED_SLASHES = 64; const JSON_PRETTY_PRINT = 128; const JSON_UNESCAPED_UNICODE = 256; private $path; private $rfs; private $io; /** * Initializes json file reader/parser. * * @param string $path path to a lockfile * @param RemoteFilesystem $rfs required for loading http/https json files * @param IOInterface $io * @throws \InvalidArgumentException */ public function __construct($path, RemoteFilesystem $rfs = null, IOInterface $io = null) { $this->path = $path; if (null === $rfs && preg_match('{^https?://}i', $path)) { throw new \InvalidArgumentException('http urls require a RemoteFilesystem instance to be passed'); } $this->rfs = $rfs; $this->io = $io; } /** * @return string */ public function getPath() { return $this->path; } /** * Checks whether json file exists. * * @return bool */ public function exists() { return is_file($this->path); } /** * Reads json file. * * @throws \RuntimeException * @return mixed */ public function read() { try { if ($this->rfs) { $json = $this->rfs->getContents($this->path, $this->path, false); } else { if ($this->io && $this->io->isDebug()) { $this->io->writeError('Reading ' . $this->path); } $json = file_get_contents($this->path); } } catch (TransportException $e) { throw new \RuntimeException($e->getMessage(), 0, $e); } catch (\Exception $e) { throw new \RuntimeException('Could not read '.$this->path."\n\n".$e->getMessage()); } return static::parseJson($json, $this->path); } /** * Writes json file. * * @param array $hash writes hash into json file * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) * @throws \UnexpectedValueException|\Exception */ public function write(array $hash, $options = 448) { $dir = dirname($this->path); if (!is_dir($dir)) { if (file_exists($dir)) { throw new \UnexpectedValueException( $dir.' exists and is not a directory.' ); } if (!@mkdir($dir, 0777, true)) { throw new \UnexpectedValueException( $dir.' does not exist and could not be created.' ); } } $retries = 3; while ($retries--) { try { file_put_contents($this->path, static::encode($hash, $options). ($options & self::JSON_PRETTY_PRINT ? "\n" : '')); break; } catch (\Exception $e) { if ($retries) { usleep(500000); continue; } throw $e; } } } /** * Validates the schema of the current json file according to composer-schema.json rules * * @param int $schema a JsonFile::*_SCHEMA constant * @throws JsonValidationException * @return bool true on success */ public function validateSchema($schema = self::STRICT_SCHEMA) { $content = file_get_contents($this->path); $data = json_decode($content); if (null === $data && 'null' !== $content) { self::validateSyntax($content, $this->path); } $schemaFile = __DIR__ . '/../../../res/composer-schema.json'; // Prepend with file:// only when not using a special schema already (e.g. in the phar) if (false === strpos($schemaFile, '://')) { $schemaFile = 'file://' . $schemaFile; } $schemaData = (object) array('$ref' => $schemaFile); if ($schema === self::LAX_SCHEMA) { $schemaData->additionalProperties = true; $schemaData->required = array(); } $validator = new Validator(); $validator->check($data, $schemaData); // TODO add more validation like check version constraints and such, perhaps build that into the arrayloader? if (!$validator->isValid()) { $errors = array(); foreach ((array) $validator->getErrors() as $error) { $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message']; } throw new JsonValidationException('"'.$this->path.'" does not match the expected JSON schema', $errors); } return true; } /** * Encodes an array into (optionally pretty-printed) JSON * * @param mixed $data Data to encode into a formatted JSON string * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) * @return string Encoded json */ public static function encode($data, $options = 448) { if (PHP_VERSION_ID >= 50400) { $json = json_encode($data, $options); if (false === $json) { self::throwEncodeError(json_last_error()); } // compact brackets to follow recent php versions if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) { $json = preg_replace('/\[\s+\]/', '[]', $json); $json = preg_replace('/\{\s+\}/', '{}', $json); } return $json; } $json = json_encode($data); if (false === $json) { self::throwEncodeError(json_last_error()); } $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT); $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE); $unescapeSlashes = (bool) ($options & self::JSON_UNESCAPED_SLASHES); if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes) { return $json; } return JsonFormatter::format($json, $unescapeUnicode, $unescapeSlashes); } /** * Throws an exception according to a given code with a customized message * * @param int $code return code of json_last_error function * @throws \RuntimeException */ private static function throwEncodeError($code) { switch ($code) { case JSON_ERROR_DEPTH: $msg = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $msg = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $msg = 'Unexpected control character found'; break; case JSON_ERROR_UTF8: $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $msg = 'Unknown error'; } throw new \RuntimeException('JSON encoding failed: '.$msg); } /** * Parses json string and returns hash. * * @param string $json json string * @param string $file the json file * * @return mixed */ public static function parseJson($json, $file = null) { if (null === $json) { return; } $data = json_decode($json, true); if (null === $data && JSON_ERROR_NONE !== json_last_error()) { self::validateSyntax($json, $file); } return $data; } /** * Validates the syntax of a JSON string * * @param string $json * @param string $file * @throws \UnexpectedValueException * @throws JsonValidationException * @throws ParsingException * @return bool true on success */ protected static function validateSyntax($json, $file = null) { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { throw new \UnexpectedValueException('"'.$file.'" is not UTF-8, could not parse as JSON'); } return true; } throw new ParsingException('"'.$file.'" does not contain valid JSON'."\n".$result->getMessage(), $result->getDetails()); } } composer-1.6.3/src/Composer/Json/JsonFormatter.php000066400000000000000000000100241323436022200221370ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Json; /** * Formats json strings used for php < 5.4 because the json_encode doesn't * supports the flags JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE * in these versions * * @author Konstantin Kudryashiv * @author Jordi Boggiano */ class JsonFormatter { /** * This code is based on the function found at: * http://recursive-design.com/blog/2008/03/11/format-json-with-php/ * * Originally licensed under MIT by Dave Perrett * * * @param string $json * @param bool $unescapeUnicode Un escape unicode * @param bool $unescapeSlashes Un escape slashes * @return string */ public static function format($json, $unescapeUnicode, $unescapeSlashes) { $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $outOfQuotes = true; $buffer = ''; $noescape = true; for ($i = 0; $i < $strLen; $i++) { // Grab the next character in the string $char = substr($json, $i, 1); // Are we inside a quoted string? if ('"' === $char && $noescape) { $outOfQuotes = !$outOfQuotes; } if (!$outOfQuotes) { $buffer .= $char; $noescape = '\\' === $char ? !$noescape : true; continue; } elseif ('' !== $buffer) { if ($unescapeSlashes) { $buffer = str_replace('\\/', '/', $buffer); } if ($unescapeUnicode && function_exists('mb_convert_encoding')) { // https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha $buffer = preg_replace_callback('/(\\\\+)u([0-9a-f]{4})/i', function ($match) { $l = strlen($match[1]); if ($l % 2) { return str_repeat('\\', $l - 1) . mb_convert_encoding( pack('H*', $match[2]), 'UTF-8', 'UCS-2BE' ); } return $match[0]; }, $buffer); } $result .= $buffer.$char; $buffer = ''; continue; } if (':' === $char) { // Add a space after the : character $char .= ' '; } elseif (('}' === $char || ']' === $char)) { $pos--; $prevChar = substr($json, $i - 1, 1); if ('{' !== $prevChar && '[' !== $prevChar) { // If this character is the end of an element, // output a new line and indent the next line $result .= $newLine; for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } else { // Collapse empty {} and [] $result = rtrim($result); } } $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line if (',' === $char || '{' === $char || '[' === $char) { $result .= $newLine; if ('{' === $char || '[' === $char) { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } } return $result; } } composer-1.6.3/src/Composer/Json/JsonManipulator.php000066400000000000000000000452601323436022200225010ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Json; use Composer\Repository\PlatformRepository; /** * @author Jordi Boggiano */ class JsonManipulator { private static $DEFINES = '(?(DEFINE) (? -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? ) (? true | false | null ) (? " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " ) (? \[ (?: (?&json) \s* (?: , (?&json) \s* )* )? \s* \] ) (? \s* (?&string) \s* : (?&json) \s* ) (? \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} ) (? \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) ) )'; private $contents; private $newline; private $indent; public function __construct($contents) { $contents = trim($contents); if ($contents === '') { $contents = '{}'; } if (!$this->pregMatch('#^\{(.*)\}$#s', $contents)) { throw new \InvalidArgumentException('The json file must be an object ({})'); } $this->newline = false !== strpos($contents, "\r\n") ? "\r\n" : "\n"; $this->contents = $contents === '{}' ? '{' . $this->newline . '}' : $contents; $this->detectIndenting(); } public function getContents() { return $this->contents . $this->newline; } public function addLink($type, $package, $constraint, $sortPackages = false) { $decoded = JsonFile::parseJson($this->contents); // no link of that type yet if (!isset($decoded[$type])) { return $this->addMainKey($type, array($package => $constraint)); } $regex = '{'.self::$DEFINES.'^(?P\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?)'. '(?P'.preg_quote(JsonFile::encode($type)).'\s*:\s*)(?P(?&json))(?P.*)}sx'; if (!$this->pregMatch($regex, $this->contents, $matches)) { return false; } $links = $matches['value']; // try to find existing link $packageRegex = str_replace('/', '\\\\?/', preg_quote($package)); $regex = '{'.self::$DEFINES.'"(?P'.$packageRegex.')"(\s*:\s*)(?&string)}ix'; if ($this->pregMatch($regex, $links, $packageMatches)) { // update existing link $existingPackage = $packageMatches['package']; $packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage)); $links = preg_replace_callback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint) { return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"'; }, $links); } else { if ($this->pregMatch('#^\s*\{\s*\S+.*?(\s*\}\s*)$#s', $links, $match)) { // link missing but non empty links $links = preg_replace( '{'.preg_quote($match[1]).'$}', // addcslashes is used to double up backslashes/$ since preg_replace resolves them as back references otherwise, see #1588 addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1], '\\$'), $links ); } else { // links empty $links = '{' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $this->newline . $this->indent . '}'; } } if (true === $sortPackages) { $requirements = json_decode($links, true); $this->sortPackages($requirements); $links = $this->format($requirements); } $this->contents = $matches['start'] . $matches['property'] . $links . $matches['end']; return true; } /** * Sorts packages by importance (platform packages first, then PHP dependencies) and alphabetically. * * @link https://getcomposer.org/doc/02-libraries.md#platform-packages * * @param array $packages */ private function sortPackages(array &$packages = array()) { $prefix = function ($requirement) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $requirement)) { return preg_replace( array( '/^php/', '/^hhvm/', '/^ext/', '/^lib/', '/^\D/', ), array( '0-$0', '1-$0', '2-$0', '3-$0', '4-$0', ), $requirement ); } return '5-'.$requirement; }; uksort($packages, function ($a, $b) use ($prefix) { return strnatcmp($prefix($a), $prefix($b)); }); } public function addRepository($name, $config) { return $this->addSubNode('repositories', $name, $config); } public function removeRepository($name) { return $this->removeSubNode('repositories', $name); } public function addConfigSetting($name, $value) { return $this->addSubNode('config', $name, $value); } public function removeConfigSetting($name) { return $this->removeSubNode('config', $name); } public function addProperty($name, $value) { if (substr($name, 0, 6) === 'extra.') { return $this->addSubNode('extra', substr($name, 6), $value); } return $this->addMainKey($name, $value); } public function removeProperty($name) { if (substr($name, 0, 6) === 'extra.') { return $this->removeSubNode('extra', substr($name, 6)); } return $this->removeMainKey($name); } public function addSubNode($mainNode, $name, $value) { $decoded = JsonFile::parseJson($this->contents); $subName = null; if (in_array($mainNode, array('config', 'extra')) && false !== strpos($name, '.')) { list($name, $subName) = explode('.', $name, 2); } // no main node yet if (!isset($decoded[$mainNode])) { if ($subName !== null) { $this->addMainKey($mainNode, array($name => array($subName => $value))); } else { $this->addMainKey($mainNode, array($name => $value)); } return true; } // main node content not match-able $nodeRegex = '{'.self::$DEFINES.'^(?P \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P(?&object))(?P.*)}sx'; try { if (!$this->pregMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } $children = $match['content']; // invalid match due to un-regexable content, abort if (!@json_decode($children)) { return false; } $that = $this; // child exists $childRegex = '{'.self::$DEFINES.'(?P"'.preg_quote($name).'"\s*:\s*)(?P(?&json))(?P,?)}x'; if ($this->pregMatch($childRegex, $children, $matches)) { $children = preg_replace_callback($childRegex, function ($matches) use ($name, $subName, $value, $that) { if ($subName !== null) { $curVal = json_decode($matches['content'], true); if (!is_array($curVal)) { $curVal = array(); } $curVal[$subName] = $value; $value = $curVal; } return $matches['start'] . $that->format($value, 1) . $matches['end']; }, $children); } else { $this->pregMatch('#^{ \s*? (?P\S+.*?)? (?P\s*) }$#sx', $children, $match); $whitespace = ''; if (!empty($match['trailingspace'])) { $whitespace = $match['trailingspace']; } if (!empty($match['content'])) { if ($subName !== null) { $value = array($subName => $value); } // child missing but non empty children $children = preg_replace( '#'.$whitespace.'}$#', addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $whitespace . '}', '\\$'), $children ); } else { if ($subName !== null) { $value = array($subName => $value); } // children present but empty $children = '{' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $whitespace . '}'; } } $this->contents = preg_replace_callback($nodeRegex, function ($m) use ($children) { return $m['start'] . $children . $m['end']; }, $this->contents); return true; } public function removeSubNode($mainNode, $name) { $decoded = JsonFile::parseJson($this->contents); // no node or empty node if (empty($decoded[$mainNode])) { return true; } // no node content match-able $nodeRegex = '{'.self::$DEFINES.'^(?P \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P(?&object))(?P.*)}sx'; try { if (!$this->pregMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } $children = $match['content']; // invalid match due to un-regexable content, abort if (!@json_decode($children, true)) { return false; } $subName = null; if (in_array($mainNode, array('config', 'extra')) && false !== strpos($name, '.')) { list($name, $subName) = explode('.', $name, 2); } // no node to remove if (!isset($decoded[$mainNode][$name]) || ($subName && !isset($decoded[$mainNode][$name][$subName]))) { return true; } // try and find a match for the subkey if ($this->pregMatch('{"'.preg_quote($name).'"\s*:}i', $children)) { // find best match for the value of "name" if (preg_match_all('{'.self::$DEFINES.'"'.preg_quote($name).'"\s*:\s*(?:(?&json))}x', $children, $matches)) { $bestMatch = ''; foreach ($matches[0] as $match) { if (strlen($bestMatch) < strlen($match)) { $bestMatch = $match; } } $childrenClean = preg_replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count); if (1 !== $count) { $childrenClean = preg_replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $childrenClean, -1, $count); if (1 !== $count) { return false; } } } } else { $childrenClean = $children; } // no child data left, $name was the only key in $this->pregMatch('#^{ \s*? (?P\S+.*?)? (?P\s*) }$#sx', $childrenClean, $match); if (empty($match['content'])) { $newline = $this->newline; $indent = $this->indent; $this->contents = preg_replace_callback($nodeRegex, function ($matches) use ($indent, $newline) { return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end']; }, $this->contents); // we have a subname, so we restore the rest of $name if ($subName !== null) { $curVal = json_decode($children, true); unset($curVal[$name][$subName]); $this->addSubNode($mainNode, $name, $curVal[$name]); } return true; } $that = $this; $this->contents = preg_replace_callback($nodeRegex, function ($matches) use ($that, $name, $subName, $childrenClean) { if ($subName !== null) { $curVal = json_decode($matches['content'], true); unset($curVal[$name][$subName]); $childrenClean = $that->format($curVal, 0); } return $matches['start'] . $childrenClean . $matches['end']; }, $this->contents); return true; } public function addMainKey($key, $content) { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); // key exists already $regex = '{'.self::$DEFINES.'^(?P\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?)'. '(?P'.preg_quote(JsonFile::encode($key)).'\s*:\s*(?&json))(?P.*)}sx'; if (isset($decoded[$key]) && $this->pregMatch($regex, $this->contents, $matches)) { // invalid match due to un-regexable content, abort if (!@json_decode('{'.$matches['key'].'}')) { return false; } $this->contents = $matches['start'] . JsonFile::encode($key).': '.$content . $matches['end']; return true; } // append at the end of the file and keep whitespace if ($this->pregMatch('#[^{\s](\s*)\}$#', $this->contents, $match)) { $this->contents = preg_replace( '#'.$match[1].'\}$#', addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key). ': '. $content . $this->newline . '}', '\\$'), $this->contents ); return true; } // append at the end of the file $this->contents = preg_replace( '#\}$#', addcslashes($this->indent . JsonFile::encode($key). ': '.$content . $this->newline . '}', '\\$'), $this->contents ); return true; } public function removeMainKey($key) { $decoded = JsonFile::parseJson($this->contents); if (!array_key_exists($key, $decoded)) { return true; } // key exists already $regex = '{'.self::$DEFINES.'^(?P\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?)'. '(?P'.preg_quote(JsonFile::encode($key)).'\s*:\s*(?&json))\s*,?\s*(?P.*)}sx'; if ($this->pregMatch($regex, $this->contents, $matches)) { // invalid match due to un-regexable content, abort if (!@json_decode('{'.$matches['removal'].'}')) { return false; } // check that we are not leaving a dangling comma on the previous line if the last line was removed if (preg_match('#,\s*$#', $matches['start']) && preg_match('#^\}$#', $matches['end'])) { $matches['start'] = rtrim(preg_replace('#,(\s*)$#', '$1', $matches['start']), $this->indent); } $this->contents = $matches['start'] . $matches['end']; if (preg_match('#^\{\s*\}\s*$#', $this->contents)) { $this->contents = "{\n}"; } return true; } return false; } public function format($data, $depth = 0) { if (is_array($data)) { reset($data); if (is_numeric(key($data))) { foreach ($data as $key => $val) { $data[$key] = $this->format($val, $depth + 1); } return '['.implode(', ', $data).']'; } $out = '{' . $this->newline; $elems = array(); foreach ($data as $key => $val) { $elems[] = str_repeat($this->indent, $depth + 2) . JsonFile::encode($key). ': '.$this->format($val, $depth + 1); } return $out . implode(','.$this->newline, $elems) . $this->newline . str_repeat($this->indent, $depth + 1) . '}'; } return JsonFile::encode($data); } protected function detectIndenting() { if ($this->pregMatch('{^([ \t]+)"}m', $this->contents, $match)) { $this->indent = $match[1]; } else { $this->indent = ' '; } } protected function pregMatch($re, $str, &$matches = array()) { $count = preg_match($re, $str, $matches); if ($count === false) { switch (preg_last_error()) { case PREG_NO_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_NO_ERROR', PREG_NO_ERROR); case PREG_INTERNAL_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_INTERNAL_ERROR', PREG_INTERNAL_ERROR); case PREG_BACKTRACK_LIMIT_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_BACKTRACK_LIMIT_ERROR', PREG_BACKTRACK_LIMIT_ERROR); case PREG_RECURSION_LIMIT_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_RECURSION_LIMIT_ERROR', PREG_RECURSION_LIMIT_ERROR); case PREG_BAD_UTF8_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_BAD_UTF8_ERROR', PREG_BAD_UTF8_ERROR); case PREG_BAD_UTF8_OFFSET_ERROR: throw new \RuntimeException('Failed to execute regex: PREG_BAD_UTF8_OFFSET_ERROR', PREG_BAD_UTF8_OFFSET_ERROR); case 6: // PREG_JIT_STACKLIMIT_ERROR if (PHP_VERSION_ID > 70000) { throw new \RuntimeException('Failed to execute regex: PREG_JIT_STACKLIMIT_ERROR', 6); } // fallthrough default: throw new \RuntimeException('Failed to execute regex: Unknown error'); } } return $count; } } composer-1.6.3/src/Composer/Json/JsonValidationException.php000066400000000000000000000013001323436022200241420ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Json; use Exception; /** * @author Jordi Boggiano */ class JsonValidationException extends Exception { protected $errors; public function __construct($message, $errors = array(), Exception $previous = null) { $this->errors = $errors; parent::__construct($message, 0, $previous); } public function getErrors() { return $this->errors; } } composer-1.6.3/src/Composer/Package/000077500000000000000000000000001323436022200172565ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/AliasPackage.php000066400000000000000000000216071323436022200223020ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Semver\Constraint\Constraint; use Composer\Package\Version\VersionParser; /** * @author Jordi Boggiano */ class AliasPackage extends BasePackage implements CompletePackageInterface { protected $version; protected $prettyVersion; protected $dev; protected $rootPackageAlias = false; protected $stability; /** @var PackageInterface */ protected $aliasOf; /** @var Link[] */ protected $requires; /** @var Link[] */ protected $devRequires; /** @var Link[] */ protected $conflicts; /** @var Link[] */ protected $provides; /** @var Link[] */ protected $replaces; /** * All descendants' constructors should call this parent constructor * * @param PackageInterface $aliasOf The package this package is an alias of * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ public function __construct(PackageInterface $aliasOf, $version, $prettyVersion) { parent::__construct($aliasOf->getName()); $this->version = $version; $this->prettyVersion = $prettyVersion; $this->aliasOf = $aliasOf; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; foreach (array('requires', 'devRequires', 'conflicts', 'provides', 'replaces') as $type) { $links = $aliasOf->{'get' . ucfirst($type)}(); $this->$type = $this->replaceSelfVersionDependencies($links, $type); } } /** * @return PackageInterface */ public function getAliasOf() { return $this->aliasOf; } /** * {@inheritDoc} */ public function getVersion() { return $this->version; } /** * {@inheritDoc} */ public function getStability() { return $this->stability; } /** * {@inheritDoc} */ public function getPrettyVersion() { return $this->prettyVersion; } /** * {@inheritDoc} */ public function isDev() { return $this->dev; } /** * {@inheritDoc} */ public function getRequires() { return $this->requires; } /** * {@inheritDoc} */ public function getConflicts() { return $this->conflicts; } /** * {@inheritDoc} */ public function getProvides() { return $this->provides; } /** * {@inheritDoc} */ public function getReplaces() { return $this->replaces; } /** * {@inheritDoc} */ public function getDevRequires() { return $this->devRequires; } /** * Stores whether this is an alias created by an aliasing in the requirements of the root package or not * * Use by the policy for sorting manually aliased packages first, see #576 * * @param bool $value * * @return mixed */ public function setRootPackageAlias($value) { return $this->rootPackageAlias = $value; } /** * @see setRootPackageAlias * @return bool */ public function isRootPackageAlias() { return $this->rootPackageAlias; } /** * @param Link[] $links * @param string $linkType * * @return Link[] */ protected function replaceSelfVersionDependencies(array $links, $linkType) { if (in_array($linkType, array('conflicts', 'provides', 'replaces'), true)) { $newLinks = array(); foreach ($links as $link) { // link is self.version, but must be replacing also the replaced version if ('self.version' === $link->getPrettyConstraint()) { $newLinks[] = new Link($link->getSource(), $link->getTarget(), new Constraint('=', $this->version), $linkType, $this->prettyVersion); } } $links = array_merge($links, $newLinks); } else { foreach ($links as $index => $link) { if ('self.version' === $link->getPrettyConstraint()) { $links[$index] = new Link($link->getSource(), $link->getTarget(), new Constraint('=', $this->version), $linkType, $this->prettyVersion); } } } return $links; } /*************************************** * Wrappers around the aliased package * ***************************************/ public function getType() { return $this->aliasOf->getType(); } public function getTargetDir() { return $this->aliasOf->getTargetDir(); } public function getExtra() { return $this->aliasOf->getExtra(); } public function setInstallationSource($type) { $this->aliasOf->setInstallationSource($type); } public function getInstallationSource() { return $this->aliasOf->getInstallationSource(); } public function getSourceType() { return $this->aliasOf->getSourceType(); } public function getSourceUrl() { return $this->aliasOf->getSourceUrl(); } public function getSourceUrls() { return $this->aliasOf->getSourceUrls(); } public function getSourceReference() { return $this->aliasOf->getSourceReference(); } public function setSourceReference($reference) { return $this->aliasOf->setSourceReference($reference); } public function setSourceMirrors($mirrors) { return $this->aliasOf->setSourceMirrors($mirrors); } public function getSourceMirrors() { return $this->aliasOf->getSourceMirrors(); } public function getDistType() { return $this->aliasOf->getDistType(); } public function getDistUrl() { return $this->aliasOf->getDistUrl(); } public function getDistUrls() { return $this->aliasOf->getDistUrls(); } public function getDistReference() { return $this->aliasOf->getDistReference(); } public function setDistReference($reference) { return $this->aliasOf->setDistReference($reference); } public function getDistSha1Checksum() { return $this->aliasOf->getDistSha1Checksum(); } public function setTransportOptions(array $options) { return $this->aliasOf->setTransportOptions($options); } public function getTransportOptions() { return $this->aliasOf->getTransportOptions(); } public function setDistMirrors($mirrors) { return $this->aliasOf->setDistMirrors($mirrors); } public function getDistMirrors() { return $this->aliasOf->getDistMirrors(); } public function getScripts() { return $this->aliasOf->getScripts(); } public function getLicense() { return $this->aliasOf->getLicense(); } public function getAutoload() { return $this->aliasOf->getAutoload(); } public function getDevAutoload() { return $this->aliasOf->getDevAutoload(); } public function getIncludePaths() { return $this->aliasOf->getIncludePaths(); } public function getRepositories() { return $this->aliasOf->getRepositories(); } public function getReleaseDate() { return $this->aliasOf->getReleaseDate(); } public function getBinaries() { return $this->aliasOf->getBinaries(); } public function getKeywords() { return $this->aliasOf->getKeywords(); } public function getDescription() { return $this->aliasOf->getDescription(); } public function getHomepage() { return $this->aliasOf->getHomepage(); } public function getSuggests() { return $this->aliasOf->getSuggests(); } public function getAuthors() { return $this->aliasOf->getAuthors(); } public function getSupport() { return $this->aliasOf->getSupport(); } public function getNotificationUrl() { return $this->aliasOf->getNotificationUrl(); } public function getArchiveExcludes() { return $this->aliasOf->getArchiveExcludes(); } public function isAbandoned() { return $this->aliasOf->isAbandoned(); } public function getReplacementPackage() { return $this->aliasOf->getReplacementPackage(); } public function __toString() { return parent::__toString().' (alias of '.$this->aliasOf->getVersion().')'; } } composer-1.6.3/src/Composer/Package/Archiver/000077500000000000000000000000001323436022200210215ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/Archiver/ArchivableFilesFilter.php000066400000000000000000000017361323436022200257320ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use FilterIterator; use PharData; class ArchivableFilesFilter extends FilterIterator { private $dirs = array(); /** * @return bool true if the current element is acceptable, otherwise false. */ public function accept() { $file = $this->getInnerIterator()->current(); if ($file->isDir()) { $this->dirs[] = (string) $file; return false; } return true; } public function addEmptyDir(PharData $phar, $sources) { foreach ($this->dirs as $filepath) { $localname = str_replace($sources . "/", '', $filepath); $phar->addEmptyDir($localname); } } } composer-1.6.3/src/Composer/Package/Archiver/ArchivableFilesFinder.php000066400000000000000000000055131323436022200257110ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use Composer\Util\Filesystem; use FilesystemIterator; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * A Symfony Finder wrapper which locates files that should go into archives * * Handles .gitignore, .gitattributes and .hgignore files as well as composer's * own exclude rules from composer.json * * @author Nils Adermann */ class ArchivableFilesFinder extends \FilterIterator { /** * @var Finder */ protected $finder; /** * Initializes the internal Symfony Finder with appropriate filters * * @param string $sources Path to source files to be archived * @param array $excludes Composer's own exclude rules from composer.json * @param bool $ignoreFilters Ignore filters when looking for files */ public function __construct($sources, array $excludes, $ignoreFilters = false) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); if ($ignoreFilters) { $filters = array(); } else { $filters = array( new HgExcludeFilter($sources), new GitExcludeFilter($sources), new ComposerExcludeFilter($sources, $excludes), ); } $this->finder = new Finder(); $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs) { if ($file->isLink() && strpos($file->getLinkTarget(), $sources) !== 0) { return false; } $relativePath = preg_replace( '#^'.preg_quote($sources, '#').'#', '', $fs->normalizePath($file->getRealPath()) ); $exclude = false; foreach ($filters as $filter) { $exclude = $filter->filter($relativePath, $exclude); } return !$exclude; }; if (method_exists($filter, 'bindTo')) { $filter = $filter->bindTo(null); } $this->finder ->in($sources) ->filter($filter) ->ignoreVCS(true) ->ignoreDotFiles(false); parent::__construct($this->finder->getIterator()); } public function accept() { /** @var SplFileInfo $current */ $current = $this->getInnerIterator()->current(); if (!$current->isDir()) { return true; } $iterator = new FilesystemIterator($current, FilesystemIterator::SKIP_DOTS); return !$iterator->valid(); } } composer-1.6.3/src/Composer/Package/Archiver/ArchiveManager.php000066400000000000000000000137021323436022200244110ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use Composer\Downloader\DownloadManager; use Composer\Package\PackageInterface; use Composer\Package\RootPackageInterface; use Composer\Util\Filesystem; use Composer\Json\JsonFile; /** * @author Matthieu Moquet * @author Till Klampaeckel */ class ArchiveManager { protected $downloadManager; protected $archivers = array(); /** * @var bool */ protected $overwriteFiles = true; /** * @param DownloadManager $downloadManager A manager used to download package sources */ public function __construct(DownloadManager $downloadManager) { $this->downloadManager = $downloadManager; } /** * @param ArchiverInterface $archiver */ public function addArchiver(ArchiverInterface $archiver) { $this->archivers[] = $archiver; } /** * Set whether existing archives should be overwritten * * @param bool $overwriteFiles New setting * * @return $this */ public function setOverwriteFiles($overwriteFiles) { $this->overwriteFiles = $overwriteFiles; return $this; } /** * Generate a distinct filename for a particular version of a package. * * @param PackageInterface $package The package to get a name for * * @return string A filename without an extension */ public function getPackageFilename(PackageInterface $package) { $nameParts = array(preg_replace('#[^a-z0-9-_]#i', '-', $package->getName())); if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) { $nameParts = array_merge($nameParts, array($package->getDistReference(), $package->getDistType())); } else { $nameParts = array_merge($nameParts, array($package->getPrettyVersion(), $package->getDistReference())); } if ($package->getSourceReference()) { $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6); } $name = implode('-', array_filter($nameParts, function ($p) { return !empty($p); })); return str_replace('/', '-', $name); } /** * Create an archive of the specified package. * * @param PackageInterface $package The package to archive * @param string $format The format of the archive (zip, tar, ...) * @param string $targetDir The directory where to build the archive * @param string|null $fileName The relative file name to use for the archive, or null to generate * the package name. Note that the format will be appended to this name * @param bool $ignoreFilters Ignore filters when looking for files in the package * @throws \InvalidArgumentException * @throws \RuntimeException * @return string The path of the created archive */ public function archive(PackageInterface $package, $format, $targetDir, $fileName = null, $ignoreFilters = false) { if (empty($format)) { throw new \InvalidArgumentException('Format must be specified'); } // Search for the most appropriate archiver $usableArchiver = null; foreach ($this->archivers as $archiver) { if ($archiver->supports($format, $package->getSourceType())) { $usableArchiver = $archiver; break; } } // Checks the format/source type are supported before downloading the package if (null === $usableArchiver) { throw new \RuntimeException(sprintf('No archiver found to support %s format', $format)); } $filesystem = new Filesystem(); if (null === $fileName) { $packageName = $this->getPackageFilename($package); } else { $packageName = $fileName; } // Archive filename $filesystem->ensureDirectoryExists($targetDir); $target = realpath($targetDir).'/'.$packageName.'.'.$format; $filesystem->ensureDirectoryExists(dirname($target)); if (!$this->overwriteFiles && file_exists($target)) { return $target; } if ($package instanceof RootPackageInterface) { $sourcePath = realpath('.'); } else { // Directory used to download the sources $sourcePath = sys_get_temp_dir().'/composer_archive'.uniqid(); $filesystem->ensureDirectoryExists($sourcePath); // Download sources $this->downloadManager->download($package, $sourcePath); // Check exclude from downloaded composer.json if (file_exists($composerJsonPath = $sourcePath.'/composer.json')) { $jsonFile = new JsonFile($composerJsonPath); $jsonData = $jsonFile->read(); if (!empty($jsonData['archive']['exclude'])) { $package->setArchiveExcludes($jsonData['archive']['exclude']); } } } // Create the archive $tempTarget = sys_get_temp_dir().'/composer_archive'.uniqid().'.'.$format; $filesystem->ensureDirectoryExists(dirname($tempTarget)); $archivePath = $usableArchiver->archive($sourcePath, $tempTarget, $format, $package->getArchiveExcludes(), $ignoreFilters); $filesystem->rename($archivePath, $target); // cleanup temporary download if (!$package instanceof RootPackageInterface) { $filesystem->removeDirectory($sourcePath); } $filesystem->remove($tempTarget); return $target; } } composer-1.6.3/src/Composer/Package/Archiver/ArchiverInterface.php000066400000000000000000000023671323436022200251260ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; /** * @author Till Klampaeckel * @author Matthieu Moquet * @author Nils Adermann */ interface ArchiverInterface { /** * Create an archive from the sources. * * @param string $sources The sources directory * @param string $target The target file * @param string $format The format used for archive * @param array $excludes A list of patterns for files to exclude * * @return string The path to the written archive file */ public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false); /** * Format supported by the archiver. * * @param string $format The archive format * @param string $sourceType The source type (git, svn, hg, etc.) * * @return bool true if the format is supported by the archiver */ public function supports($format, $sourceType); } composer-1.6.3/src/Composer/Package/Archiver/BaseExcludeFilter.php000066400000000000000000000076271323436022200251000ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use Symfony\Component\Finder; /** * @author Nils Adermann */ abstract class BaseExcludeFilter { /** * @var string */ protected $sourcePath; /** * @var array */ protected $excludePatterns; /** * @param string $sourcePath Directory containing sources to be filtered */ public function __construct($sourcePath) { $this->sourcePath = $sourcePath; $this->excludePatterns = array(); } /** * Checks the given path against all exclude patterns in this filter * * Negated patterns overwrite exclude decisions of previous filters. * * @param string $relativePath The file's path relative to the sourcePath * @param bool $exclude Whether a previous filter wants to exclude this file * * @return bool Whether the file should be excluded */ public function filter($relativePath, $exclude) { foreach ($this->excludePatterns as $patternData) { list($pattern, $negate, $stripLeadingSlash) = $patternData; if ($stripLeadingSlash) { $path = substr($relativePath, 1); } else { $path = $relativePath; } if (preg_match($pattern, $path)) { $exclude = !$negate; } } return $exclude; } /** * Processes a file containing exclude rules of different formats per line * * @param array $lines A set of lines to be parsed * @param callback $lineParser The parser to be used on each line * * @return array Exclude patterns to be used in filter() */ protected function parseLines(array $lines, $lineParser) { return array_filter( array_map( function ($line) use ($lineParser) { $line = trim($line); if (!$line || 0 === strpos($line, '#')) { return null; } return call_user_func($lineParser, $line); }, $lines ), function ($pattern) { return $pattern !== null; } ); } /** * Generates a set of exclude patterns for filter() from gitignore rules * * @param array $rules A list of exclude rules in gitignore syntax * * @return array Exclude patterns */ protected function generatePatterns($rules) { $patterns = array(); foreach ($rules as $rule) { $patterns[] = $this->generatePattern($rule); } return $patterns; } /** * Generates an exclude pattern for filter() from a gitignore rule * * @param string $rule An exclude rule in gitignore syntax * * @return array An exclude pattern */ protected function generatePattern($rule) { $negate = false; $pattern = '{'; if (strlen($rule) && $rule[0] === '!') { $negate = true; $rule = substr($rule, 1); } if (strlen($rule) && $rule[0] === '/') { $pattern .= '^/'; $rule = substr($rule, 1); } elseif (strlen($rule) - 1 === strpos($rule, '/')) { $pattern .= '/'; $rule = substr($rule, 0, -1); } elseif (false === strpos($rule, '/')) { $pattern .= '/'; } // remove delimiters as well as caret (^) and dollar sign ($) from the regex $pattern .= substr(Finder\Glob::toRegex($rule), 2, -2) . '(?=$|/)'; return array($pattern . '}', $negate, false); } } composer-1.6.3/src/Composer/Package/Archiver/ComposerExcludeFilter.php000066400000000000000000000015321323436022200260020ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; /** * An exclude filter which processes composer's own exclude rules * * @author Nils Adermann */ class ComposerExcludeFilter extends BaseExcludeFilter { /** * @param string $sourcePath Directory containing sources to be filtered * @param array $excludeRules An array of exclude rules from composer.json */ public function __construct($sourcePath, array $excludeRules) { parent::__construct($sourcePath); $this->excludePatterns = $this->generatePatterns($excludeRules); } } composer-1.6.3/src/Composer/Package/Archiver/GitExcludeFilter.php000066400000000000000000000040431323436022200247360ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; /** * An exclude filter that processes gitignore and gitattributes * * It respects export-ignore git attributes * * @author Nils Adermann */ class GitExcludeFilter extends BaseExcludeFilter { /** * Parses .gitignore and .gitattributes files if they exist * * @param string $sourcePath */ public function __construct($sourcePath) { parent::__construct($sourcePath); if (file_exists($sourcePath.'/.gitignore')) { $this->excludePatterns = $this->parseLines( file($sourcePath.'/.gitignore'), array($this, 'parseGitIgnoreLine') ); } if (file_exists($sourcePath.'/.gitattributes')) { $this->excludePatterns = array_merge( $this->excludePatterns, $this->parseLines( file($sourcePath.'/.gitattributes'), array($this, 'parseGitAttributesLine') )); } } /** * Callback line parser which process gitignore lines * * @param string $line A line from .gitignore * * @return array An exclude pattern for filter() */ public function parseGitIgnoreLine($line) { return $this->generatePattern($line); } /** * Callback parser which finds export-ignore rules in git attribute lines * * @param string $line A line from .gitattributes * * @return array An exclude pattern for filter() */ public function parseGitAttributesLine($line) { $parts = preg_split('#\s+#', $line); if (count($parts) == 2 && $parts[1] === 'export-ignore') { return $this->generatePattern($parts[0]); } return null; } } composer-1.6.3/src/Composer/Package/Archiver/HgExcludeFilter.php000066400000000000000000000053551323436022200245600ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use Symfony\Component\Finder; /** * An exclude filter that processes hgignore files * * @author Nils Adermann */ class HgExcludeFilter extends BaseExcludeFilter { const HG_IGNORE_REGEX = 1; const HG_IGNORE_GLOB = 2; /** * Either HG_IGNORE_REGEX or HG_IGNORE_GLOB * @var int */ protected $patternMode; /** * Parses .hgignore file if it exist * * @param string $sourcePath */ public function __construct($sourcePath) { parent::__construct($sourcePath); $this->patternMode = self::HG_IGNORE_REGEX; if (file_exists($sourcePath.'/.hgignore')) { $this->excludePatterns = $this->parseLines( file($sourcePath.'/.hgignore'), array($this, 'parseHgIgnoreLine') ); } } /** * Callback line parser which process hgignore lines * * @param string $line A line from .hgignore * * @return array An exclude pattern for filter() */ public function parseHgIgnoreLine($line) { if (preg_match('#^syntax\s*:\s*(glob|regexp)$#', $line, $matches)) { if ($matches[1] === 'glob') { $this->patternMode = self::HG_IGNORE_GLOB; } else { $this->patternMode = self::HG_IGNORE_REGEX; } return null; } if ($this->patternMode == self::HG_IGNORE_GLOB) { return $this->patternFromGlob($line); } return $this->patternFromRegex($line); } /** * Generates an exclude pattern for filter() from a hg glob expression * * @param string $line A line from .hgignore in glob mode * * @return array An exclude pattern for filter() */ protected function patternFromGlob($line) { $pattern = '#'.substr(Finder\Glob::toRegex($line), 2, -1).'#'; $pattern = str_replace('[^/]*', '.*', $pattern); return array($pattern, false, true); } /** * Generates an exclude pattern for filter() from a hg regexp expression * * @param string $line A line from .hgignore in regexp mode * * @return array An exclude pattern for filter() */ public function patternFromRegex($line) { // WTF need to escape the delimiter safely $pattern = '#'.preg_replace('/((?:\\\\\\\\)*)(\\\\?)#/', '\1\2\2\\#', $line).'#'; return array($pattern, false, true); } } composer-1.6.3/src/Composer/Package/Archiver/PharArchiver.php000066400000000000000000000054651323436022200241220ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; /** * @author Till Klampaeckel * @author Nils Adermann * @author Matthieu Moquet */ class PharArchiver implements ArchiverInterface { protected static $formats = array( 'zip' => \Phar::ZIP, 'tar' => \Phar::TAR, 'tar.gz' => \Phar::TAR, 'tar.bz2' => \Phar::TAR, ); protected static $compressFormats = array( 'tar.gz' => \Phar::GZ, 'tar.bz2' => \Phar::BZ2, ); /** * {@inheritdoc} */ public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false) { $sources = realpath($sources); // Phar would otherwise load the file which we don't want if (file_exists($target)) { unlink($target); } try { $filename = substr($target, 0, strrpos($target, $format) - 1); // Check if compress format if (isset(static::$compressFormats[$format])) { // Current compress format supported base on tar $target = $filename . '.tar'; } $phar = new \PharData($target, null, null, static::$formats[$format]); $files = new ArchivableFilesFinder($sources, $excludes, $ignoreFilters); $filesOnly = new ArchivableFilesFilter($files); $phar->buildFromIterator($filesOnly, $sources); $filesOnly->addEmptyDir($phar, $sources); if (isset(static::$compressFormats[$format])) { // Check can be compressed? if (!$phar->canCompress(static::$compressFormats[$format])) { throw new \RuntimeException(sprintf('Can not compress to %s format', $format)); } // Delete old tar unlink($target); // Compress the new tar $phar->compress(static::$compressFormats[$format]); // Make the correct filename $target = $filename . '.' . $format; } return $target; } catch (\UnexpectedValueException $e) { $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $e->getMessage() ); throw new \RuntimeException($message, $e->getCode(), $e); } } /** * {@inheritdoc} */ public function supports($format, $sourceType) { return isset(static::$formats[$format]); } } composer-1.6.3/src/Composer/Package/Archiver/ZipArchiver.php000066400000000000000000000037141323436022200237650ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; use ZipArchive; use Composer\Util\Filesystem; /** * @author Jan Prieser */ class ZipArchiver implements ArchiverInterface { protected static $formats = array( 'zip' => 1, ); /** * {@inheritdoc} */ public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); $zip = new ZipArchive(); $res = $zip->open($target, ZipArchive::CREATE); if ($res === true) { $files = new ArchivableFilesFinder($sources, $excludes, $ignoreFilters); foreach ($files as $file) { /** @var $file \SplFileInfo */ $filepath = strtr($file->getPath()."/".$file->getFilename(), '\\', '/'); $localname = str_replace($sources.'/', '', $filepath); if ($file->isDir()) { $zip->addEmptyDir($localname); } else { $zip->addFile($filepath, $localname); } } if ($zip->close()) { return $target; } } $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $zip->getStatusString() ); throw new \RuntimeException($message); } /** * {@inheritdoc} */ public function supports($format, $sourceType) { return isset(static::$formats[$format]) && $this->compressionAvailable(); } private function compressionAvailable() { return class_exists('ZipArchive'); } } composer-1.6.3/src/Composer/Package/BasePackage.php000066400000000000000000000130151323436022200221150ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Repository\RepositoryInterface; use Composer\Repository\PlatformRepository; /** * Base class for packages providing name storage and default match implementation * * @author Nils Adermann */ abstract class BasePackage implements PackageInterface { public static $supportedLinkTypes = array( 'require' => array('description' => 'requires', 'method' => 'requires'), 'conflict' => array('description' => 'conflicts', 'method' => 'conflicts'), 'provide' => array('description' => 'provides', 'method' => 'provides'), 'replace' => array('description' => 'replaces', 'method' => 'replaces'), 'require-dev' => array('description' => 'requires (for development)', 'method' => 'devRequires'), ); const STABILITY_STABLE = 0; const STABILITY_RC = 5; const STABILITY_BETA = 10; const STABILITY_ALPHA = 15; const STABILITY_DEV = 20; public static $stabilities = array( 'stable' => self::STABILITY_STABLE, 'RC' => self::STABILITY_RC, 'beta' => self::STABILITY_BETA, 'alpha' => self::STABILITY_ALPHA, 'dev' => self::STABILITY_DEV, ); /** * READ-ONLY: The package id, public for fast access in dependency solver * @var int */ public $id; /** @var string */ protected $name; /** @var string */ protected $prettyName; /** @var RepositoryInterface */ protected $repository; /** @var array */ protected $transportOptions = array(); /** * All descendants' constructors should call this parent constructor * * @param string $name The package's name */ public function __construct($name) { $this->prettyName = $name; $this->name = strtolower($name); $this->id = -1; } /** * {@inheritDoc} */ public function getName() { return $this->name; } /** * {@inheritDoc} */ public function getPrettyName() { return $this->prettyName; } /** * {@inheritDoc} */ public function getNames() { $names = array( $this->getName() => true, ); foreach ($this->getProvides() as $link) { $names[$link->getTarget()] = true; } foreach ($this->getReplaces() as $link) { $names[$link->getTarget()] = true; } return array_keys($names); } /** * {@inheritDoc} */ public function setId($id) { $this->id = $id; } /** * {@inheritDoc} */ public function getId() { return $this->id; } /** * {@inheritDoc} */ public function setRepository(RepositoryInterface $repository) { if ($this->repository && $repository !== $this->repository) { throw new \LogicException('A package can only be added to one repository'); } $this->repository = $repository; } /** * {@inheritDoc} */ public function getRepository() { return $this->repository; } /** * {@inheritDoc} */ public function getTransportOptions() { return $this->transportOptions; } /** * Configures the list of options to download package dist files * * @param array $options */ public function setTransportOptions(array $options) { $this->transportOptions = $options; } /** * checks if this package is a platform package * * @return bool */ public function isPlatform() { return $this->getRepository() instanceof PlatformRepository; } /** * Returns package unique name, constructed from name, version and release type. * * @return string */ public function getUniqueName() { return $this->getName().'-'.$this->getVersion(); } public function equals(PackageInterface $package) { $self = $this; if ($this instanceof AliasPackage) { $self = $this->getAliasOf(); } if ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } return $package === $self; } /** * Converts the package into a readable and unique string * * @return string */ public function __toString() { return $this->getUniqueName(); } public function getPrettyString() { return $this->getPrettyName().' '.$this->getPrettyVersion(); } /** * {@inheritDoc} */ public function getFullPrettyVersion($truncate = true) { if (!$this->isDev() || !in_array($this->getSourceType(), array('hg', 'git'))) { return $this->getPrettyVersion(); } // if source reference is a sha1 hash -- truncate if ($truncate && strlen($this->getSourceReference()) === 40) { return $this->getPrettyVersion() . ' ' . substr($this->getSourceReference(), 0, 7); } return $this->getPrettyVersion() . ' ' . $this->getSourceReference(); } public function getStabilityPriority() { return self::$stabilities[$this->getStability()]; } public function __clone() { $this->repository = null; $this->id = -1; } } composer-1.6.3/src/Composer/Package/CompletePackage.php000066400000000000000000000070721323436022200230210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; /** * Package containing additional metadata that is not used by the solver * * @author Nils Adermann */ class CompletePackage extends Package implements CompletePackageInterface { protected $repositories; protected $license = array(); protected $keywords; protected $authors; protected $description; protected $homepage; protected $scripts = array(); protected $support = array(); protected $abandoned = false; /** * @param array $scripts */ public function setScripts(array $scripts) { $this->scripts = $scripts; } /** * {@inheritDoc} */ public function getScripts() { return $this->scripts; } /** * Set the repositories * * @param array $repositories */ public function setRepositories($repositories) { $this->repositories = $repositories; } /** * {@inheritDoc} */ public function getRepositories() { return $this->repositories; } /** * Set the license * * @param array $license */ public function setLicense(array $license) { $this->license = $license; } /** * {@inheritDoc} */ public function getLicense() { return $this->license; } /** * Set the keywords * * @param array $keywords */ public function setKeywords(array $keywords) { $this->keywords = $keywords; } /** * {@inheritDoc} */ public function getKeywords() { return $this->keywords; } /** * Set the authors * * @param array $authors */ public function setAuthors(array $authors) { $this->authors = $authors; } /** * {@inheritDoc} */ public function getAuthors() { return $this->authors; } /** * Set the description * * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * {@inheritDoc} */ public function getDescription() { return $this->description; } /** * Set the homepage * * @param string $homepage */ public function setHomepage($homepage) { $this->homepage = $homepage; } /** * {@inheritDoc} */ public function getHomepage() { return $this->homepage; } /** * Set the support information * * @param array $support */ public function setSupport(array $support) { $this->support = $support; } /** * {@inheritDoc} */ public function getSupport() { return $this->support; } /** * @return bool */ public function isAbandoned() { return (bool) $this->abandoned; } /** * @param bool|string $abandoned */ public function setAbandoned($abandoned) { $this->abandoned = $abandoned; } /** * If the package is abandoned and has a suggested replacement, this method returns it * * @return string|null */ public function getReplacementPackage() { return is_string($this->abandoned) ? $this->abandoned : null; } } composer-1.6.3/src/Composer/Package/CompletePackageInterface.php000066400000000000000000000037431323436022200246430ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; /** * Defines package metadata that is not necessarily needed for solving and installing packages * * @author Nils Adermann */ interface CompletePackageInterface extends PackageInterface { /** * Returns the scripts of this package * * @return array array('script name' => array('listeners')) */ public function getScripts(); /** * Returns an array of repositories * * {"": {}} * * @return array Repositories */ public function getRepositories(); /** * Returns the package license, e.g. MIT, BSD, GPL * * @return array The package licenses */ public function getLicense(); /** * Returns an array of keywords relating to the package * * @return array */ public function getKeywords(); /** * Returns the package description * * @return string */ public function getDescription(); /** * Returns the package homepage * * @return string */ public function getHomepage(); /** * Returns an array of authors of the package * * Each item can contain name/homepage/email keys * * @return array */ public function getAuthors(); /** * Returns the support information * * @return array */ public function getSupport(); /** * Returns if the package is abandoned or not * * @return bool */ public function isAbandoned(); /** * If the package is abandoned and has a suggested replacement, this method returns it * * @return string */ public function getReplacementPackage(); } composer-1.6.3/src/Composer/Package/Dumper/000077500000000000000000000000001323436022200205125ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/Dumper/ArrayDumper.php000066400000000000000000000106301323436022200234560ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Dumper; use Composer\Package\BasePackage; use Composer\Package\PackageInterface; use Composer\Package\CompletePackageInterface; use Composer\Package\RootPackageInterface; /** * @author Konstantin Kudryashiv * @author Jordi Boggiano */ class ArrayDumper { public function dump(PackageInterface $package) { $keys = array( 'binaries' => 'bin', 'type', 'extra', 'installationSource' => 'installation-source', 'autoload', 'devAutoload' => 'autoload-dev', 'notificationUrl' => 'notification-url', 'includePaths' => 'include-path', ); $data = array(); $data['name'] = $package->getPrettyName(); $data['version'] = $package->getPrettyVersion(); $data['version_normalized'] = $package->getVersion(); if ($package->getTargetDir()) { $data['target-dir'] = $package->getTargetDir(); } if ($package->getSourceType()) { $data['source']['type'] = $package->getSourceType(); $data['source']['url'] = $package->getSourceUrl(); $data['source']['reference'] = $package->getSourceReference(); if ($mirrors = $package->getSourceMirrors()) { $data['source']['mirrors'] = $mirrors; } } if ($package->getDistType()) { $data['dist']['type'] = $package->getDistType(); $data['dist']['url'] = $package->getDistUrl(); $data['dist']['reference'] = $package->getDistReference(); $data['dist']['shasum'] = $package->getDistSha1Checksum(); if ($mirrors = $package->getDistMirrors()) { $data['dist']['mirrors'] = $mirrors; } } if ($package->getArchiveExcludes()) { $data['archive']['exclude'] = $package->getArchiveExcludes(); } foreach (BasePackage::$supportedLinkTypes as $type => $opts) { if ($links = $package->{'get'.ucfirst($opts['method'])}()) { foreach ($links as $link) { $data[$type][$link->getTarget()] = $link->getPrettyConstraint(); } ksort($data[$type]); } } if ($packages = $package->getSuggests()) { ksort($packages); $data['suggest'] = $packages; } if ($package->getReleaseDate()) { $data['time'] = $package->getReleaseDate()->format(DATE_RFC3339); } $data = $this->dumpValues($package, $keys, $data); if ($package instanceof CompletePackageInterface) { $keys = array( 'scripts', 'license', 'authors', 'description', 'homepage', 'keywords', 'repositories', 'support', ); $data = $this->dumpValues($package, $keys, $data); if (isset($data['keywords']) && is_array($data['keywords'])) { sort($data['keywords']); } if ($package->isAbandoned()) { $data['abandoned'] = $package->getReplacementPackage() ?: true; } } if ($package instanceof RootPackageInterface) { $minimumStability = $package->getMinimumStability(); if ($minimumStability) { $data['minimum-stability'] = $minimumStability; } } if (count($package->getTransportOptions()) > 0) { $data['transport-options'] = $package->getTransportOptions(); } return $data; } private function dumpValues(PackageInterface $package, array $keys, array $data) { foreach ($keys as $method => $key) { if (is_numeric($method)) { $method = $key; } $getter = 'get'.ucfirst($method); $value = $package->$getter(); if (null !== $value && !(is_array($value) && 0 === count($value))) { $data[$key] = $value; } } return $data; } } composer-1.6.3/src/Composer/Package/Link.php000066400000000000000000000057051323436022200206730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Semver\Constraint\ConstraintInterface; /** * Represents a link between two packages, represented by their names * * @author Nils Adermann */ class Link { /** * @var string */ protected $source; /** * @var string */ protected $target; /** * @var ConstraintInterface|null */ protected $constraint; /** * @var string */ protected $description; /** * @var string|null */ protected $prettyConstraint; /** * Creates a new package link. * * @param string $source * @param string $target * @param ConstraintInterface|null $constraint Constraint applying to the target of this link * @param string $description Used to create a descriptive string representation * @param string|null $prettyConstraint */ public function __construct($source, $target, ConstraintInterface $constraint = null, $description = 'relates to', $prettyConstraint = null) { $this->source = strtolower($source); $this->target = strtolower($target); $this->constraint = $constraint; $this->description = $description; $this->prettyConstraint = $prettyConstraint; } /** * @return string */ public function getDescription() { return $this->description; } /** * @return string */ public function getSource() { return $this->source; } /** * @return string */ public function getTarget() { return $this->target; } /** * @return ConstraintInterface|null */ public function getConstraint() { return $this->constraint; } /** * @throws \UnexpectedValueException If no pretty constraint was provided * @return string */ public function getPrettyConstraint() { if (null === $this->prettyConstraint) { throw new \UnexpectedValueException(sprintf('Link %s has been misconfigured and had no prettyConstraint given.', $this)); } return $this->prettyConstraint; } /** * @return string */ public function __toString() { return $this->source.' '.$this->description.' '.$this->target.' ('.$this->constraint.')'; } /** * @param PackageInterface $sourcePackage * @return string */ public function getPrettyString(PackageInterface $sourcePackage) { return $sourcePackage->getPrettyString().' '.$this->description.' '.$this->target.' '.$this->constraint->getPrettyString().''; } } composer-1.6.3/src/Composer/Package/LinkConstraint/000077500000000000000000000000001323436022200222205ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/LinkConstraint/EmptyConstraint.php000066400000000000000000000013111323436022200260700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\LinkConstraint; use Composer\Semver\Constraint\EmptyConstraint as SemverEmptyConstraint; trigger_error('The ' . __NAMESPACE__ . '\EmptyConstraint class is deprecated, use Composer\Semver\Constraint\EmptyConstraint instead.', E_USER_DEPRECATED); /** * @deprecated use Composer\Semver\Constraint\EmptyConstraint instead */ class EmptyConstraint extends SemverEmptyConstraint implements LinkConstraintInterface { } composer-1.6.3/src/Composer/Package/LinkConstraint/LinkConstraintInterface.php000066400000000000000000000012571323436022200275210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\LinkConstraint; use Composer\Semver\Constraint\ConstraintInterface; trigger_error('The ' . __NAMESPACE__ . '\LinkConstraintInterface interface is deprecated, use Composer\Semver\Constraint\ConstraintInterface instead.', E_USER_DEPRECATED); /** * @deprecated use Composer\Semver\Constraint\ConstraintInterface instead */ interface LinkConstraintInterface extends ConstraintInterface { } composer-1.6.3/src/Composer/Package/LinkConstraint/MultiConstraint.php000066400000000000000000000013111323436022200260640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\LinkConstraint; use Composer\Semver\Constraint\MultiConstraint as SemverMultiConstraint; trigger_error('The ' . __NAMESPACE__ . '\MultiConstraint class is deprecated, use Composer\Semver\Constraint\MultiConstraint instead.', E_USER_DEPRECATED); /** * @deprecated use Composer\Semver\Constraint\MultiConstraint instead */ class MultiConstraint extends SemverMultiConstraint implements LinkConstraintInterface { } composer-1.6.3/src/Composer/Package/LinkConstraint/SpecificConstraint.php000066400000000000000000000012631323436022200265250ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\LinkConstraint; use Composer\Semver\Constraint\AbstractConstraint; trigger_error('The ' . __NAMESPACE__ . '\SpecificConstraint abstract class is deprecated, there is no replacement for it.', E_USER_DEPRECATED); /** * @deprecated use Composer\Semver\Constraint\AbstractConstraint instead */ abstract class SpecificConstraint extends AbstractConstraint implements LinkConstraintInterface { } composer-1.6.3/src/Composer/Package/LinkConstraint/VersionConstraint.php000066400000000000000000000012321323436022200264210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\LinkConstraint; use Composer\Semver\Constraint\Constraint; trigger_error('The ' . __NAMESPACE__ . '\VersionConstraint class is deprecated, use Composer\Semver\Constraint\Constraint instead.', E_USER_DEPRECATED); /** * @deprecated use Composer\Semver\Constraint\Constraint instead */ class VersionConstraint extends Constraint implements LinkConstraintInterface { } composer-1.6.3/src/Composer/Package/Loader/000077500000000000000000000000001323436022200204645ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/Loader/ArrayLoader.php000066400000000000000000000262071323436022200234110ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; use Composer\Package; use Composer\Package\AliasPackage; use Composer\Package\Link; use Composer\Package\RootAliasPackage; use Composer\Package\RootPackageInterface; use Composer\Package\Version\VersionParser; use Composer\Semver\VersionParser as SemverVersionParser; /** * @author Konstantin Kudryashiv * @author Jordi Boggiano */ class ArrayLoader implements LoaderInterface { protected $versionParser; protected $loadOptions; public function __construct(SemverVersionParser $parser = null, $loadOptions = false) { if (!$parser) { $parser = new VersionParser; } $this->versionParser = $parser; $this->loadOptions = $loadOptions; } public function load(array $config, $class = 'Composer\Package\CompletePackage') { if (!isset($config['name'])) { throw new \UnexpectedValueException('Unknown package has no name defined ('.json_encode($config).').'); } if (!isset($config['version'])) { throw new \UnexpectedValueException('Package '.$config['name'].' has no version defined.'); } // handle already normalized versions if (isset($config['version_normalized'])) { $version = $config['version_normalized']; } else { $version = $this->versionParser->normalize($config['version']); } $package = new $class($config['name'], $version, $config['version']); $package->setType(isset($config['type']) ? strtolower($config['type']) : 'library'); if (isset($config['target-dir'])) { $package->setTargetDir($config['target-dir']); } if (isset($config['extra']) && is_array($config['extra'])) { $package->setExtra($config['extra']); } if (isset($config['bin'])) { foreach ((array) $config['bin'] as $key => $bin) { $config['bin'][$key] = ltrim($bin, '/'); } $package->setBinaries((array) $config['bin']); } if (isset($config['installation-source'])) { $package->setInstallationSource($config['installation-source']); } if (isset($config['source'])) { if (!isset($config['source']['type']) || !isset($config['source']['url']) || !isset($config['source']['reference'])) { throw new \UnexpectedValueException(sprintf( "Package %s's source key should be specified as {\"type\": ..., \"url\": ..., \"reference\": ...},\n%s given.", $config['name'], json_encode($config['source']) )); } $package->setSourceType($config['source']['type']); $package->setSourceUrl($config['source']['url']); $package->setSourceReference($config['source']['reference']); if (isset($config['source']['mirrors'])) { $package->setSourceMirrors($config['source']['mirrors']); } } if (isset($config['dist'])) { if (!isset($config['dist']['type']) || !isset($config['dist']['url'])) { throw new \UnexpectedValueException(sprintf( "Package %s's dist key should be specified as ". "{\"type\": ..., \"url\": ..., \"reference\": ..., \"shasum\": ...},\n%s given.", $config['name'], json_encode($config['dist']) )); } $package->setDistType($config['dist']['type']); $package->setDistUrl($config['dist']['url']); $package->setDistReference(isset($config['dist']['reference']) ? $config['dist']['reference'] : null); $package->setDistSha1Checksum(isset($config['dist']['shasum']) ? $config['dist']['shasum'] : null); if (isset($config['dist']['mirrors'])) { $package->setDistMirrors($config['dist']['mirrors']); } } foreach (Package\BasePackage::$supportedLinkTypes as $type => $opts) { if (isset($config[$type])) { $method = 'set'.ucfirst($opts['method']); $package->{$method}( $this->parseLinks( $package->getName(), $package->getPrettyVersion(), $opts['description'], $config[$type] ) ); } } if (isset($config['suggest']) && is_array($config['suggest'])) { foreach ($config['suggest'] as $target => $reason) { if ('self.version' === trim($reason)) { $config['suggest'][$target] = $package->getPrettyVersion(); } } $package->setSuggests($config['suggest']); } if (isset($config['autoload'])) { $package->setAutoload($config['autoload']); } if (isset($config['autoload-dev'])) { $package->setDevAutoload($config['autoload-dev']); } if (isset($config['include-path'])) { $package->setIncludePaths($config['include-path']); } if (!empty($config['time'])) { $time = preg_match('/^\d++$/D', $config['time']) ? '@'.$config['time'] : $config['time']; try { $date = new \DateTime($time, new \DateTimeZone('UTC')); $package->setReleaseDate($date); } catch (\Exception $e) { } } if (!empty($config['notification-url'])) { $package->setNotificationUrl($config['notification-url']); } if (!empty($config['archive']['exclude'])) { $package->setArchiveExcludes($config['archive']['exclude']); } if ($package instanceof Package\CompletePackageInterface) { if (isset($config['scripts']) && is_array($config['scripts'])) { foreach ($config['scripts'] as $event => $listeners) { $config['scripts'][$event] = (array) $listeners; } if (isset($config['scripts']['composer'])) { trigger_error('The `composer` script name is reserved for internal use, please avoid defining it', E_USER_DEPRECATED); } $package->setScripts($config['scripts']); } if (!empty($config['description']) && is_string($config['description'])) { $package->setDescription($config['description']); } if (!empty($config['homepage']) && is_string($config['homepage'])) { $package->setHomepage($config['homepage']); } if (!empty($config['keywords']) && is_array($config['keywords'])) { $package->setKeywords($config['keywords']); } if (!empty($config['license'])) { $package->setLicense(is_array($config['license']) ? $config['license'] : array($config['license'])); } if (!empty($config['authors']) && is_array($config['authors'])) { $package->setAuthors($config['authors']); } if (isset($config['support'])) { $package->setSupport($config['support']); } if (isset($config['abandoned'])) { $package->setAbandoned($config['abandoned']); } } if ($aliasNormalized = $this->getBranchAlias($config)) { if ($package instanceof RootPackageInterface) { $package = new RootAliasPackage($package, $aliasNormalized, preg_replace('{(\.9{7})+}', '.x', $aliasNormalized)); } else { $package = new AliasPackage($package, $aliasNormalized, preg_replace('{(\.9{7})+}', '.x', $aliasNormalized)); } } if ($this->loadOptions && isset($config['transport-options'])) { $package->setTransportOptions($config['transport-options']); } return $package; } /** * @param string $source source package name * @param string $sourceVersion source package version (pretty version ideally) * @param string $description link description (e.g. requires, replaces, ..) * @param array $links array of package name => constraint mappings * @return Link[] */ public function parseLinks($source, $sourceVersion, $description, $links) { $res = array(); foreach ($links as $target => $constraint) { if (!is_string($constraint)) { throw new \UnexpectedValueException('Link constraint in '.$source.' '.$description.' > '.$target.' should be a string, got '.gettype($constraint) . ' (' . var_export($constraint, true) . ')'); } if ('self.version' === $constraint) { $parsedConstraint = $this->versionParser->parseConstraints($sourceVersion); } else { $parsedConstraint = $this->versionParser->parseConstraints($constraint); } $res[strtolower($target)] = new Link($source, $target, $parsedConstraint, $description, $constraint); } return $res; } /** * Retrieves a branch alias (dev-master => 1.0.x-dev for example) if it exists * * @param array $config the entire package config * @return string|null normalized version of the branch alias or null if there is none */ public function getBranchAlias(array $config) { if (('dev-' !== substr($config['version'], 0, 4) && '-dev' !== substr($config['version'], -4)) || !isset($config['extra']['branch-alias']) || !is_array($config['extra']['branch-alias']) ) { return; } foreach ($config['extra']['branch-alias'] as $sourceBranch => $targetBranch) { // ensure it is an alias to a -dev package if ('-dev' !== substr($targetBranch, -4)) { continue; } // normalize without -dev and ensure it's a numeric branch that is parseable $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4)); if ('-dev' !== substr($validatedTargetBranch, -4)) { continue; } // ensure that it is the current branch aliasing itself if (strtolower($config['version']) !== strtolower($sourceBranch)) { continue; } // If using numeric aliases ensure the alias is a valid subversion if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch)) && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch)) && (stripos($targetPrefix, $sourcePrefix) !== 0) ) { continue; } return $validatedTargetBranch; } } } composer-1.6.3/src/Composer/Package/Loader/InvalidPackageException.php000066400000000000000000000017511323436022200257220ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; /** * @author Jordi Boggiano */ class InvalidPackageException extends \Exception { private $errors; private $warnings; private $data; public function __construct(array $errors, array $warnings, array $data) { $this->errors = $errors; $this->warnings = $warnings; $this->data = $data; parent::__construct("Invalid package information: \n".implode("\n", array_merge($errors, $warnings))); } public function getData() { return $this->data; } public function getErrors() { return $this->errors; } public function getWarnings() { return $this->warnings; } } composer-1.6.3/src/Composer/Package/Loader/JsonLoader.php000066400000000000000000000021341323436022200232350ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; use Composer\Json\JsonFile; /** * @author Konstantin Kudryashiv */ class JsonLoader { private $loader; public function __construct(LoaderInterface $loader) { $this->loader = $loader; } /** * @param string|JsonFile $json A filename, json string or JsonFile instance to load the package from * @return \Composer\Package\PackageInterface */ public function load($json) { if ($json instanceof JsonFile) { $config = $json->read(); } elseif (file_exists($json)) { $config = JsonFile::parseJson(file_get_contents($json), $json); } elseif (is_string($json)) { $config = JsonFile::parseJson($json); } return $this->loader->load($config); } } composer-1.6.3/src/Composer/Package/Loader/LoaderInterface.php000066400000000000000000000015021323436022200242220ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; /** * Defines a loader that takes an array to create package instances * * @author Jordi Boggiano */ interface LoaderInterface { /** * Converts a package from an array to a real instance * * @param array $package Package config * @param string $class Package class to use * @return \Composer\Package\PackageInterface */ public function load(array $package, $class = 'Composer\Package\CompletePackage'); } composer-1.6.3/src/Composer/Package/Loader/RootPackageLoader.php000066400000000000000000000216051323436022200245270ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; use Composer\Package\BasePackage; use Composer\Package\AliasPackage; use Composer\Config; use Composer\Package\RootPackageInterface; use Composer\Repository\RepositoryFactory; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Repository\RepositoryManager; use Composer\Util\ProcessExecutor; /** * ArrayLoader built for the sole purpose of loading the root package * * Sets additional defaults and loads repositories * * @author Jordi Boggiano */ class RootPackageLoader extends ArrayLoader { /** * @var RepositoryManager */ private $manager; /** * @var Config */ private $config; /** * @var VersionGuesser */ private $versionGuesser; public function __construct(RepositoryManager $manager, Config $config, VersionParser $parser = null, VersionGuesser $versionGuesser = null) { parent::__construct($parser); $this->manager = $manager; $this->config = $config; $this->versionGuesser = $versionGuesser ?: new VersionGuesser($config, new ProcessExecutor(), $this->versionParser); } /** * @param array $config package data * @param string $class FQCN to be instantiated * @param string $cwd cwd of the root package to be used to guess the version if it is not provided * @return RootPackageInterface */ public function load(array $config, $class = 'Composer\Package\RootPackage', $cwd = null) { if (!isset($config['name'])) { $config['name'] = '__root__'; } $autoVersioned = false; if (!isset($config['version'])) { $commit = null; // override with env var if available if (getenv('COMPOSER_ROOT_VERSION')) { $config['version'] = getenv('COMPOSER_ROOT_VERSION'); } else { $versionData = $this->versionGuesser->guessVersion($config, $cwd ?: getcwd()); if ($versionData) { $config['version'] = $versionData['pretty_version']; $config['version_normalized'] = $versionData['version']; $commit = $versionData['commit']; } } if (!isset($config['version'])) { $config['version'] = '1.0.0'; $autoVersioned = true; } if ($commit) { $config['source'] = array( 'type' => '', 'url' => '', 'reference' => $commit, ); $config['dist'] = array( 'type' => '', 'url' => '', 'reference' => $commit, ); } } $realPackage = $package = parent::load($config, $class); if ($realPackage instanceof AliasPackage) { $realPackage = $package->getAliasOf(); } if ($autoVersioned) { $realPackage->replaceVersion($realPackage->getVersion(), 'No version set (parsed as 1.0.0)'); } if (isset($config['minimum-stability'])) { $realPackage->setMinimumStability(VersionParser::normalizeStability($config['minimum-stability'])); } $aliases = array(); $stabilityFlags = array(); $references = array(); foreach (array('require', 'require-dev') as $linkType) { if (isset($config[$linkType])) { $linkInfo = BasePackage::$supportedLinkTypes[$linkType]; $method = 'get'.ucfirst($linkInfo['method']); $links = array(); foreach ($realPackage->$method() as $link) { $links[$link->getTarget()] = $link->getConstraint()->getPrettyString(); } $aliases = $this->extractAliases($links, $aliases); $stabilityFlags = $this->extractStabilityFlags($links, $stabilityFlags, $realPackage->getMinimumStability()); $references = $this->extractReferences($links, $references); } } if (isset($links[$config['name']])) { throw new \InvalidArgumentException(sprintf('Root package \'%s\' cannot require itself in its composer.json' . PHP_EOL . 'Did you accidentally name your root package after an external package?', $config['name'])); } $realPackage->setAliases($aliases); $realPackage->setStabilityFlags($stabilityFlags); $realPackage->setReferences($references); if (isset($config['prefer-stable'])) { $realPackage->setPreferStable((bool) $config['prefer-stable']); } if (isset($config['config'])) { $realPackage->setConfig($config['config']); } $repos = RepositoryFactory::defaultRepos(null, $this->config, $this->manager); foreach ($repos as $repo) { $this->manager->addRepository($repo); } $realPackage->setRepositories($this->config->getRepositories()); return $package; } private function extractAliases(array $requires, array $aliases) { foreach ($requires as $reqName => $reqVersion) { if (preg_match('{^([^,\s#]+)(?:#[^ ]+)? +as +([^,\s]+)$}', $reqVersion, $match)) { $aliases[] = array( 'package' => strtolower($reqName), 'version' => $this->versionParser->normalize($match[1], $reqVersion), 'alias' => $match[2], 'alias_normalized' => $this->versionParser->normalize($match[2], $reqVersion), ); } } return $aliases; } private function extractStabilityFlags(array $requires, array $stabilityFlags, $minimumStability) { $stabilities = BasePackage::$stabilities; $minimumStability = $stabilities[$minimumStability]; foreach ($requires as $reqName => $reqVersion) { $constraints = array(); // extract all sub-constraints in case it is an OR/AND multi-constraint $orSplit = preg_split('{\s*\|\|?\s*}', trim($reqVersion)); foreach ($orSplit as $orConstraint) { $andSplit = preg_split('{(?< ,]) *(? $stability) { continue; } $stabilityFlags[$name] = $stability; $match = true; } } if ($match) { continue; } foreach ($constraints as $constraint) { // infer flags for requirements that have an explicit -dev or -beta version specified but only // for those that are more unstable than the minimumStability or existing flags $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $constraint); if (preg_match('{^[^,\s@]+$}', $reqVersion) && 'stable' !== ($stabilityName = VersionParser::parseStability($reqVersion))) { $name = strtolower($reqName); $stability = $stabilities[$stabilityName]; if ((isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) || ($minimumStability > $stability)) { continue; } $stabilityFlags[$name] = $stability; } } } return $stabilityFlags; } private function extractReferences(array $requires, array $references) { foreach ($requires as $reqName => $reqVersion) { $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion); if (preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) && 'dev' === ($stabilityName = VersionParser::parseStability($reqVersion))) { $name = strtolower($reqName); $references[$name] = $match[1]; } } return $references; } } composer-1.6.3/src/Composer/Package/Loader/ValidatingArrayLoader.php000066400000000000000000000523031323436022200254100ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Loader; use Composer\Package; use Composer\Package\BasePackage; use Composer\Semver\Constraint\Constraint; use Composer\Package\Version\VersionParser; use Composer\Repository\PlatformRepository; use Composer\Spdx\SpdxLicenses; /** * @author Jordi Boggiano */ class ValidatingArrayLoader implements LoaderInterface { const CHECK_ALL = 3; const CHECK_UNBOUND_CONSTRAINTS = 1; const CHECK_STRICT_CONSTRAINTS = 2; private $loader; private $versionParser; private $errors; private $warnings; private $config; private $strictName; private $flags; public function __construct(LoaderInterface $loader, $strictName = true, VersionParser $parser = null, $flags = 0) { $this->loader = $loader; $this->versionParser = $parser ?: new VersionParser(); $this->strictName = $strictName; $this->flags = $flags; } public function load(array $config, $class = 'Composer\Package\CompletePackage') { $this->errors = array(); $this->warnings = array(); $this->config = $config; if ($this->strictName) { $this->validateRegex('name', '[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*', true); } else { $this->validateString('name', true); } if (!empty($this->config['version'])) { try { $this->versionParser->normalize($this->config['version']); } catch (\Exception $e) { $this->errors[] = 'version : invalid value ('.$this->config['version'].'): '.$e->getMessage(); unset($this->config['version']); } } if (!empty($this->config['config']['platform'])) { foreach ((array) $this->config['config']['platform'] as $key => $platform) { try { $this->versionParser->normalize($platform); } catch (\Exception $e) { $this->errors[] = 'config.platform.' . $key . ' : invalid value ('.$platform.'): '.$e->getMessage(); } } } $this->validateRegex('type', '[A-Za-z0-9-]+'); $this->validateString('target-dir'); $this->validateArray('extra'); if (isset($this->config['bin'])) { if (is_string($this->config['bin'])) { $this->validateString('bin'); } else { $this->validateFlatArray('bin'); } } $this->validateArray('scripts'); // TODO validate event names & listener syntax $this->validateString('description'); $this->validateUrl('homepage'); $this->validateFlatArray('keywords', '[\p{N}\p{L} ._-]+'); $releaseDate = null; $this->validateString('time'); if (!empty($this->config['time'])) { try { $releaseDate = new \DateTime($this->config['time'], new \DateTimeZone('UTC')); } catch (\Exception $e) { $this->errors[] = 'time : invalid value ('.$this->config['time'].'): '.$e->getMessage(); unset($this->config['time']); } } if (isset($this->config['license'])) { if (is_string($this->config['license'])) { $this->validateRegex('license', '[A-Za-z0-9+. ()-]+'); } else { $this->validateFlatArray('license', '[A-Za-z0-9+. ()-]+'); } if (is_array($this->config['license']) || is_string($this->config['license'])) { $licenses = (array) $this->config['license']; // strip proprietary since it's not a valid SPDX identifier, but is accepted by composer foreach ($licenses as $key => $license) { if ('proprietary' === $license) { unset($licenses[$key]); } } $licenseValidator = new SpdxLicenses(); if (count($licenses) === 1 && !$licenseValidator->validate($licenses) && $licenseValidator->validate(trim($licenses[0]))) { $this->warnings[] = sprintf( 'License %s must not contain extra spaces, make sure to trim it.', json_encode($this->config['license']) ); } elseif (array() !== $licenses && !$licenseValidator->validate($licenses)) { $this->warnings[] = sprintf( 'License %s is not a valid SPDX license identifier, see https://spdx.org/licenses/ if you use an open license.' . PHP_EOL . 'If the software is closed-source, you may use "proprietary" as license.', json_encode($this->config['license']) ); } else if (!$releaseDate || $releaseDate->format('Y-m-d H:i:s') >= '2018-01-20 00:00:00') { // only warn for deprecations for releases/branches that follow the introduction of deprecated licenses foreach ($licenses as $license) { $spdxLicense = $licenseValidator->getLicenseByIdentifier($license); if ($spdxLicense && $spdxLicense[3]) { if (preg_match('{^[AL]?GPL-[123](\.[01])?\+$}i', $license)) { $this->warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, use "'.str_replace('+', '', $license).'-or-later" instead', $license ); } elseif (preg_match('{^[AL]?GPL-[123](\.[01])?$}i', $license)) { $this->warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, use "'.$license.'-only" or "'.$license.'-or-later" instead', $license ); } else { $this->warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, see https://spdx.org/licenses/', $license ); } } } } } } if ($this->validateArray('authors') && !empty($this->config['authors'])) { foreach ($this->config['authors'] as $key => $author) { if (!is_array($author)) { $this->errors[] = 'authors.'.$key.' : should be an array, '.gettype($author).' given'; unset($this->config['authors'][$key]); continue; } foreach (array('homepage', 'email', 'name', 'role') as $authorData) { if (isset($author[$authorData]) && !is_string($author[$authorData])) { $this->errors[] = 'authors.'.$key.'.'.$authorData.' : invalid value, must be a string'; unset($this->config['authors'][$key][$authorData]); } } if (isset($author['homepage']) && !$this->filterUrl($author['homepage'])) { $this->warnings[] = 'authors.'.$key.'.homepage : invalid value ('.$author['homepage'].'), must be an http/https URL'; unset($this->config['authors'][$key]['homepage']); } if (isset($author['email']) && !filter_var($author['email'], FILTER_VALIDATE_EMAIL)) { $this->warnings[] = 'authors.'.$key.'.email : invalid value ('.$author['email'].'), must be a valid email address'; unset($this->config['authors'][$key]['email']); } if (empty($this->config['authors'][$key])) { unset($this->config['authors'][$key]); } } if (empty($this->config['authors'])) { unset($this->config['authors']); } } if ($this->validateArray('support') && !empty($this->config['support'])) { foreach (array('issues', 'forum', 'wiki', 'source', 'email', 'irc', 'docs', 'rss') as $key) { if (isset($this->config['support'][$key]) && !is_string($this->config['support'][$key])) { $this->errors[] = 'support.'.$key.' : invalid value, must be a string'; unset($this->config['support'][$key]); } } if (isset($this->config['support']['email']) && !filter_var($this->config['support']['email'], FILTER_VALIDATE_EMAIL)) { $this->warnings[] = 'support.email : invalid value ('.$this->config['support']['email'].'), must be a valid email address'; unset($this->config['support']['email']); } if (isset($this->config['support']['irc']) && !$this->filterUrl($this->config['support']['irc'], array('irc'))) { $this->warnings[] = 'support.irc : invalid value ('.$this->config['support']['irc'].'), must be a irc:/// URL'; unset($this->config['support']['irc']); } foreach (array('issues', 'forum', 'wiki', 'source', 'docs') as $key) { if (isset($this->config['support'][$key]) && !$this->filterUrl($this->config['support'][$key])) { $this->warnings[] = 'support.'.$key.' : invalid value ('.$this->config['support'][$key].'), must be an http/https URL'; unset($this->config['support'][$key]); } } if (empty($this->config['support'])) { unset($this->config['support']); } } $unboundConstraint = new Constraint('=', $this->versionParser->normalize('dev-master')); $stableConstraint = new Constraint('=', '1.0.0'); foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) { if ($this->validateArray($linkType) && isset($this->config[$linkType])) { foreach ($this->config[$linkType] as $package => $constraint) { if (!preg_match('{^[A-Za-z0-9_./-]+$}', $package)) { $this->warnings[] = $linkType.'.'.$package.' : invalid key, package names must be strings containing only [A-Za-z0-9_./-]'; } if (!is_string($constraint)) { $this->errors[] = $linkType.'.'.$package.' : invalid value, must be a string containing a version constraint'; unset($this->config[$linkType][$package]); } elseif ('self.version' !== $constraint) { try { $linkConstraint = $this->versionParser->parseConstraints($constraint); } catch (\Exception $e) { $this->errors[] = $linkType.'.'.$package.' : invalid version constraint ('.$e->getMessage().')'; unset($this->config[$linkType][$package]); continue; } // check requires for unbound constraints on non-platform packages if ( ($this->flags & self::CHECK_UNBOUND_CONSTRAINTS) && 'require' === $linkType && $linkConstraint->matches($unboundConstraint) && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $package) ) { $this->warnings[] = $linkType.'.'.$package.' : unbound version constraints ('.$constraint.') should be avoided'; } elseif ( // check requires for exact constraints ($this->flags & self::CHECK_STRICT_CONSTRAINTS) && 'require' === $linkType && substr($linkConstraint, 0, 1) === '=' && $stableConstraint->versionCompare($stableConstraint, $linkConstraint, '<=') ) { $this->warnings[] = $linkType.'.'.$package.' : exact version constraints ('.$constraint.') should be avoided if the package follows semantic versioning'; } } } } } if ($this->validateArray('suggest') && !empty($this->config['suggest'])) { foreach ($this->config['suggest'] as $package => $description) { if (!is_string($description)) { $this->errors[] = 'suggest.'.$package.' : invalid value, must be a string describing why the package is suggested'; unset($this->config['suggest'][$package]); } } } if ($this->validateString('minimum-stability') && !empty($this->config['minimum-stability'])) { if (!isset(BasePackage::$stabilities[$this->config['minimum-stability']])) { $this->errors[] = 'minimum-stability : invalid value ('.$this->config['minimum-stability'].'), must be one of '.implode(', ', array_keys(BasePackage::$stabilities)); unset($this->config['minimum-stability']); } } if ($this->validateArray('autoload') && !empty($this->config['autoload'])) { $types = array('psr-0', 'psr-4', 'classmap', 'files', 'exclude-from-classmap'); foreach ($this->config['autoload'] as $type => $typeConfig) { if (!in_array($type, $types)) { $this->errors[] = 'autoload : invalid value ('.$type.'), must be one of '.implode(', ', $types); unset($this->config['autoload'][$type]); } if ($type === 'psr-4') { foreach ($typeConfig as $namespace => $dirs) { if ($namespace !== '' && '\\' !== substr($namespace, -1)) { $this->errors[] = 'autoload.psr-4 : invalid value ('.$namespace.'), namespaces must end with a namespace separator, should be '.$namespace.'\\\\'; } } } } } if (!empty($this->config['autoload']['psr-4']) && !empty($this->config['target-dir'])) { $this->errors[] = 'target-dir : this can not be used together with the autoload.psr-4 setting, remove target-dir to upgrade to psr-4'; // Unset the psr-4 setting, since unsetting target-dir might // interfere with other settings. unset($this->config['autoload']['psr-4']); } // TODO validate dist // TODO validate source // TODO validate repositories // TODO validate package repositories' packages using this recursively $this->validateFlatArray('include-path'); $this->validateArray('transport-options'); // branch alias validation if (isset($this->config['extra']['branch-alias'])) { if (!is_array($this->config['extra']['branch-alias'])) { $this->errors[] = 'extra.branch-alias : must be an array of versions => aliases'; } else { foreach ($this->config['extra']['branch-alias'] as $sourceBranch => $targetBranch) { // ensure it is an alias to a -dev package if ('-dev' !== substr($targetBranch, -4)) { $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must end in -dev'; unset($this->config['extra']['branch-alias'][$sourceBranch]); continue; } // normalize without -dev and ensure it's a numeric branch that is parseable $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4)); if ('-dev' !== substr($validatedTargetBranch, -4)) { $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must be a parseable number like 2.0-dev'; unset($this->config['extra']['branch-alias'][$sourceBranch]); continue; } // If using numeric aliases ensure the alias is a valid subversion if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch)) && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch)) && (stripos($targetPrefix, $sourcePrefix) !== 0) ) { $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') is not a valid numeric alias for this version'; unset($this->config['extra']['branch-alias'][$sourceBranch]); } } } } if ($this->errors) { throw new InvalidPackageException($this->errors, $this->warnings, $config); } $package = $this->loader->load($this->config, $class); $this->config = null; return $package; } public function getWarnings() { return $this->warnings; } public function getErrors() { return $this->errors; } private function validateRegex($property, $regex, $mandatory = false) { if (!$this->validateString($property, $mandatory)) { return false; } if (!preg_match('{^'.$regex.'$}u', $this->config[$property])) { $message = $property.' : invalid value ('.$this->config[$property].'), must match '.$regex; if ($mandatory) { $this->errors[] = $message; } else { $this->warnings[] = $message; } unset($this->config[$property]); return false; } return true; } private function validateString($property, $mandatory = false) { if (isset($this->config[$property]) && !is_string($this->config[$property])) { $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given'; unset($this->config[$property]); return false; } if (!isset($this->config[$property]) || trim($this->config[$property]) === '') { if ($mandatory) { $this->errors[] = $property.' : must be present'; } unset($this->config[$property]); return false; } return true; } private function validateArray($property, $mandatory = false) { if (isset($this->config[$property]) && !is_array($this->config[$property])) { $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given'; unset($this->config[$property]); return false; } if (!isset($this->config[$property]) || !count($this->config[$property])) { if ($mandatory) { $this->errors[] = $property.' : must be present and contain at least one element'; } unset($this->config[$property]); return false; } return true; } private function validateFlatArray($property, $regex = null, $mandatory = false) { if (!$this->validateArray($property, $mandatory)) { return false; } $pass = true; foreach ($this->config[$property] as $key => $value) { if (!is_string($value) && !is_numeric($value)) { $this->errors[] = $property.'.'.$key.' : must be a string or int, '.gettype($value).' given'; unset($this->config[$property][$key]); $pass = false; continue; } if ($regex && !preg_match('{^'.$regex.'$}u', $value)) { $this->warnings[] = $property.'.'.$key.' : invalid value ('.$value.'), must match '.$regex; unset($this->config[$property][$key]); $pass = false; } } return $pass; } private function validateUrl($property, $mandatory = false) { if (!$this->validateString($property, $mandatory)) { return false; } if (!$this->filterUrl($this->config[$property])) { $this->warnings[] = $property.' : invalid value ('.$this->config[$property].'), must be an http/https URL'; unset($this->config[$property]); return false; } return true; } private function filterUrl($value, array $schemes = array('http', 'https')) { if ($value === '') { return true; } $bits = parse_url($value); if (empty($bits['scheme']) || empty($bits['host'])) { return false; } if (!in_array($bits['scheme'], $schemes, true)) { return false; } return true; } } composer-1.6.3/src/Composer/Package/Locker.php000066400000000000000000000345311323436022200212140ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Json\JsonFile; use Composer\Installer\InstallationManager; use Composer\Repository\RepositoryManager; use Composer\Util\ProcessExecutor; use Composer\Repository\ArrayRepository; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\Loader\ArrayLoader; use Composer\Util\Git as GitUtil; use Composer\IO\IOInterface; use Seld\JsonLint\ParsingException; /** * Reads/writes project lockfile (composer.lock). * * @author Konstantin Kudryashiv * @author Jordi Boggiano */ class Locker { private $lockFile; private $repositoryManager; private $installationManager; private $hash; private $contentHash; private $loader; private $dumper; private $process; private $lockDataCache; /** * Initializes packages locker. * * @param IOInterface $io * @param JsonFile $lockFile lockfile loader * @param RepositoryManager $repositoryManager repository manager instance * @param InstallationManager $installationManager installation manager instance * @param string $composerFileContents The contents of the composer file */ public function __construct(IOInterface $io, JsonFile $lockFile, RepositoryManager $repositoryManager, InstallationManager $installationManager, $composerFileContents) { $this->lockFile = $lockFile; $this->repositoryManager = $repositoryManager; $this->installationManager = $installationManager; $this->hash = md5($composerFileContents); $this->contentHash = self::getContentHash($composerFileContents); $this->loader = new ArrayLoader(null, true); $this->dumper = new ArrayDumper(); $this->process = new ProcessExecutor($io); } /** * Returns the md5 hash of the sorted content of the composer file. * * @param string $composerFileContents The contents of the composer file. * * @return string */ public static function getContentHash($composerFileContents) { $content = json_decode($composerFileContents, true); $relevantKeys = array( 'name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra', ); $relevantContent = array(); foreach (array_intersect($relevantKeys, array_keys($content)) as $key) { $relevantContent[$key] = $content[$key]; } if (isset($content['config']['platform'])) { $relevantContent['config']['platform'] = $content['config']['platform']; } ksort($relevantContent); return md5(json_encode($relevantContent)); } /** * Checks whether locker has been locked (lockfile found). * * @return bool */ public function isLocked() { if (!$this->lockFile->exists()) { return false; } $data = $this->getLockData(); return isset($data['packages']); } /** * Checks whether the lock file is still up to date with the current hash * * @return bool */ public function isFresh() { $lock = $this->lockFile->read(); if (!empty($lock['content-hash'])) { // There is a content hash key, use that instead of the file hash return $this->contentHash === $lock['content-hash']; } // BC support for old lock files without content-hash if (!empty($lock['hash'])) { return $this->hash === $lock['hash']; } // should not be reached unless the lock file is corrupted, so assume it's out of date return false; } /** * Searches and returns an array of locked packages, retrieved from registered repositories. * * @param bool $withDevReqs true to retrieve the locked dev packages * @throws \RuntimeException * @return \Composer\Repository\RepositoryInterface */ public function getLockedRepository($withDevReqs = false) { $lockData = $this->getLockData(); $packages = new ArrayRepository(); $lockedPackages = $lockData['packages']; if ($withDevReqs) { if (isset($lockData['packages-dev'])) { $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']); } else { throw new \RuntimeException('The lock file does not contain require-dev information, run install with the --no-dev option or run update to install those packages.'); } } if (empty($lockedPackages)) { return $packages; } if (isset($lockedPackages[0]['name'])) { foreach ($lockedPackages as $info) { $packages->addPackage($this->loader->load($info)); } return $packages; } throw new \RuntimeException('Your composer.lock was created before 2012-09-15, and is not supported anymore. Run "composer update" to generate a new one.'); } /** * Returns the platform requirements stored in the lock file * * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned * @return \Composer\Package\Link[] */ public function getPlatformRequirements($withDevReqs = false) { $lockData = $this->getLockData(); $requirements = array(); if (!empty($lockData['platform'])) { $requirements = $this->loader->parseLinks( '__ROOT__', '1.0.0', 'requires', isset($lockData['platform']) ? $lockData['platform'] : array() ); } if ($withDevReqs && !empty($lockData['platform-dev'])) { $devRequirements = $this->loader->parseLinks( '__ROOT__', '1.0.0', 'requires', isset($lockData['platform-dev']) ? $lockData['platform-dev'] : array() ); $requirements = array_merge($requirements, $devRequirements); } return $requirements; } public function getMinimumStability() { $lockData = $this->getLockData(); return isset($lockData['minimum-stability']) ? $lockData['minimum-stability'] : 'stable'; } public function getStabilityFlags() { $lockData = $this->getLockData(); return isset($lockData['stability-flags']) ? $lockData['stability-flags'] : array(); } public function getPreferStable() { $lockData = $this->getLockData(); // return null if not set to allow caller logic to choose the // right behavior since old lock files have no prefer-stable return isset($lockData['prefer-stable']) ? $lockData['prefer-stable'] : null; } public function getPreferLowest() { $lockData = $this->getLockData(); // return null if not set to allow caller logic to choose the // right behavior since old lock files have no prefer-lowest return isset($lockData['prefer-lowest']) ? $lockData['prefer-lowest'] : null; } public function getPlatformOverrides() { $lockData = $this->getLockData(); return isset($lockData['platform-overrides']) ? $lockData['platform-overrides'] : array(); } public function getAliases() { $lockData = $this->getLockData(); return isset($lockData['aliases']) ? $lockData['aliases'] : array(); } public function getLockData() { if (null !== $this->lockDataCache) { return $this->lockDataCache; } if (!$this->lockFile->exists()) { throw new \LogicException('No lockfile found. Unable to read locked packages'); } return $this->lockDataCache = $this->lockFile->read(); } /** * Locks provided data into lockfile. * * @param array $packages array of packages * @param mixed $devPackages array of dev packages or null if installed without --dev * @param array $platformReqs array of package name => constraint for required platform packages * @param mixed $platformDevReqs array of package name => constraint for dev-required platform packages * @param array $aliases array of aliases * @param string $minimumStability * @param array $stabilityFlags * @param bool $preferStable * @param bool $preferLowest * @param array $platformOverrides * * @return bool */ public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest, array $platformOverrides) { $lock = array( '_readme' => array('This file locks the dependencies of your project to a known state', 'Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file', 'This file is @gener'.'ated automatically', ), 'content-hash' => $this->contentHash, 'packages' => null, 'packages-dev' => null, 'aliases' => array(), 'minimum-stability' => $minimumStability, 'stability-flags' => $stabilityFlags, 'prefer-stable' => $preferStable, 'prefer-lowest' => $preferLowest, ); foreach ($aliases as $package => $versions) { foreach ($versions as $version => $alias) { $lock['aliases'][] = array( 'alias' => $alias['alias'], 'alias_normalized' => $alias['alias_normalized'], 'version' => $version, 'package' => $package, ); } } $lock['packages'] = $this->lockPackages($packages); if (null !== $devPackages) { $lock['packages-dev'] = $this->lockPackages($devPackages); } $lock['platform'] = $platformReqs; $lock['platform-dev'] = $platformDevReqs; if ($platformOverrides) { $lock['platform-overrides'] = $platformOverrides; } if (empty($lock['packages']) && empty($lock['packages-dev']) && empty($lock['platform']) && empty($lock['platform-dev'])) { if ($this->lockFile->exists()) { unlink($this->lockFile->getPath()); } return false; } try { $isLocked = $this->isLocked(); } catch (ParsingException $e) { $isLocked = false; } if (!$isLocked || $lock !== $this->getLockData()) { $this->lockFile->write($lock); $this->lockDataCache = null; return true; } return false; } private function lockPackages(array $packages) { $locked = array(); foreach ($packages as $package) { if ($package instanceof AliasPackage) { continue; } $name = $package->getPrettyName(); $version = $package->getPrettyVersion(); if (!$name || !$version) { throw new \LogicException(sprintf( 'Package "%s" has no version or name and can not be locked', $package )); } $spec = $this->dumper->dump($package); unset($spec['version_normalized']); // always move time to the end of the package definition $time = isset($spec['time']) ? $spec['time'] : null; unset($spec['time']); if ($package->isDev() && $package->getInstallationSource() === 'source') { // use the exact commit time of the current reference if it's a dev package $time = $this->getPackageTime($package) ?: $time; } if (null !== $time) { $spec['time'] = $time; } unset($spec['installation-source']); $locked[] = $spec; } usort($locked, function ($a, $b) { $comparison = strcmp($a['name'], $b['name']); if (0 !== $comparison) { return $comparison; } // If it is the same package, compare the versions to make the order deterministic return strcmp($a['version'], $b['version']); }); return $locked; } /** * Returns the packages's datetime for its source reference. * * @param PackageInterface $package The package to scan. * @return string|null The formatted datetime or null if none was found. */ private function getPackageTime(PackageInterface $package) { if (!function_exists('proc_open')) { return null; } $path = realpath($this->installationManager->getInstallPath($package)); $sourceType = $package->getSourceType(); $datetime = null; if ($path && in_array($sourceType, array('git', 'hg'))) { $sourceRef = $package->getSourceReference() ?: $package->getDistReference(); switch ($sourceType) { case 'git': GitUtil::cleanEnv(); if (0 === $this->process->execute('git log -n1 --pretty=%ct '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*\d+\s*$}', $output)) { $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); } break; case 'hg': if (0 === $this->process->execute('hg log --template "{date|hgdate}" -r '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*(\d+)\s*}', $output, $match)) { $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC')); } break; } } return $datetime ? $datetime->format(DATE_RFC3339) : null; } } composer-1.6.3/src/Composer/Package/Package.php000066400000000000000000000304021323436022200213210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Package\Version\VersionParser; use Composer\Util\ComposerMirror; /** * Core package definitions that are needed to resolve dependencies and install packages * * @author Nils Adermann */ class Package extends BasePackage { protected $type; protected $targetDir; protected $installationSource; protected $sourceType; protected $sourceUrl; protected $sourceReference; protected $sourceMirrors; protected $distType; protected $distUrl; protected $distReference; protected $distSha1Checksum; protected $distMirrors; protected $version; protected $prettyVersion; protected $releaseDate; protected $extra = array(); protected $binaries = array(); protected $dev; protected $stability; protected $notificationUrl; /** @var Link[] */ protected $requires = array(); /** @var Link[] */ protected $conflicts = array(); /** @var Link[] */ protected $provides = array(); /** @var Link[] */ protected $replaces = array(); /** @var Link[] */ protected $devRequires = array(); protected $suggests = array(); protected $autoload = array(); protected $devAutoload = array(); protected $includePaths = array(); protected $archiveExcludes = array(); /** * Creates a new in memory package. * * @param string $name The package's name * @param string $version The package's version * @param string $prettyVersion The package's non-normalized version */ public function __construct($name, $version, $prettyVersion) { parent::__construct($name); $this->version = $version; $this->prettyVersion = $prettyVersion; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; } /** * {@inheritDoc} */ public function isDev() { return $this->dev; } /** * @param string $type */ public function setType($type) { $this->type = $type; } /** * {@inheritDoc} */ public function getType() { return $this->type ?: 'library'; } /** * {@inheritDoc} */ public function getStability() { return $this->stability; } /** * @param string $targetDir */ public function setTargetDir($targetDir) { $this->targetDir = $targetDir; } /** * {@inheritDoc} */ public function getTargetDir() { if (null === $this->targetDir) { return; } return ltrim(preg_replace('{ (?:^|[\\\\/]+) \.\.? (?:[\\\\/]+|$) (?:\.\.? (?:[\\\\/]+|$) )*}x', '/', $this->targetDir), '/'); } /** * @param array $extra */ public function setExtra(array $extra) { $this->extra = $extra; } /** * {@inheritDoc} */ public function getExtra() { return $this->extra; } /** * @param array $binaries */ public function setBinaries(array $binaries) { $this->binaries = $binaries; } /** * {@inheritDoc} */ public function getBinaries() { return $this->binaries; } /** * {@inheritDoc} */ public function setInstallationSource($type) { $this->installationSource = $type; } /** * {@inheritDoc} */ public function getInstallationSource() { return $this->installationSource; } /** * @param string $type */ public function setSourceType($type) { $this->sourceType = $type; } /** * {@inheritDoc} */ public function getSourceType() { return $this->sourceType; } /** * @param string $url */ public function setSourceUrl($url) { $this->sourceUrl = $url; } /** * {@inheritDoc} */ public function getSourceUrl() { return $this->sourceUrl; } /** * @param string $reference */ public function setSourceReference($reference) { $this->sourceReference = $reference; } /** * {@inheritDoc} */ public function getSourceReference() { return $this->sourceReference; } /** * @param array|null $mirrors */ public function setSourceMirrors($mirrors) { $this->sourceMirrors = $mirrors; } /** * {@inheritDoc} */ public function getSourceMirrors() { return $this->sourceMirrors; } /** * {@inheritDoc} */ public function getSourceUrls() { return $this->getUrls($this->sourceUrl, $this->sourceMirrors, $this->sourceReference, $this->sourceType, 'source'); } /** * @param string $type */ public function setDistType($type) { $this->distType = $type; } /** * {@inheritDoc} */ public function getDistType() { return $this->distType; } /** * @param string $url */ public function setDistUrl($url) { $this->distUrl = $url; } /** * {@inheritDoc} */ public function getDistUrl() { return $this->distUrl; } /** * @param string $reference */ public function setDistReference($reference) { $this->distReference = $reference; } /** * {@inheritDoc} */ public function getDistReference() { return $this->distReference; } /** * @param string $sha1checksum */ public function setDistSha1Checksum($sha1checksum) { $this->distSha1Checksum = $sha1checksum; } /** * {@inheritDoc} */ public function getDistSha1Checksum() { return $this->distSha1Checksum; } /** * @param array|null $mirrors */ public function setDistMirrors($mirrors) { $this->distMirrors = $mirrors; } /** * {@inheritDoc} */ public function getDistMirrors() { return $this->distMirrors; } /** * {@inheritDoc} */ public function getDistUrls() { return $this->getUrls($this->distUrl, $this->distMirrors, $this->distReference, $this->distType, 'dist'); } /** * {@inheritDoc} */ public function getVersion() { return $this->version; } /** * {@inheritDoc} */ public function getPrettyVersion() { return $this->prettyVersion; } /** * Set the releaseDate * * @param \DateTime $releaseDate */ public function setReleaseDate(\DateTime $releaseDate) { $this->releaseDate = $releaseDate; } /** * {@inheritDoc} */ public function getReleaseDate() { return $this->releaseDate; } /** * Set the required packages * * @param Link[] $requires A set of package links */ public function setRequires(array $requires) { $this->requires = $requires; } /** * {@inheritDoc} */ public function getRequires() { return $this->requires; } /** * Set the conflicting packages * * @param Link[] $conflicts A set of package links */ public function setConflicts(array $conflicts) { $this->conflicts = $conflicts; } /** * {@inheritDoc} */ public function getConflicts() { return $this->conflicts; } /** * Set the provided virtual packages * * @param Link[] $provides A set of package links */ public function setProvides(array $provides) { $this->provides = $provides; } /** * {@inheritDoc} */ public function getProvides() { return $this->provides; } /** * Set the packages this one replaces * * @param Link[] $replaces A set of package links */ public function setReplaces(array $replaces) { $this->replaces = $replaces; } /** * {@inheritDoc} */ public function getReplaces() { return $this->replaces; } /** * Set the recommended packages * * @param Link[] $devRequires A set of package links */ public function setDevRequires(array $devRequires) { $this->devRequires = $devRequires; } /** * {@inheritDoc} */ public function getDevRequires() { return $this->devRequires; } /** * Set the suggested packages * * @param array $suggests A set of package names/comments */ public function setSuggests(array $suggests) { $this->suggests = $suggests; } /** * {@inheritDoc} */ public function getSuggests() { return $this->suggests; } /** * Set the autoload mapping * * @param array $autoload Mapping of autoloading rules */ public function setAutoload(array $autoload) { $this->autoload = $autoload; } /** * {@inheritDoc} */ public function getAutoload() { return $this->autoload; } /** * Set the dev autoload mapping * * @param array $devAutoload Mapping of dev autoloading rules */ public function setDevAutoload(array $devAutoload) { $this->devAutoload = $devAutoload; } /** * {@inheritDoc} */ public function getDevAutoload() { return $this->devAutoload; } /** * Sets the list of paths added to PHP's include path. * * @param array $includePaths List of directories. */ public function setIncludePaths(array $includePaths) { $this->includePaths = $includePaths; } /** * {@inheritDoc} */ public function getIncludePaths() { return $this->includePaths; } /** * Sets the notification URL * * @param string $notificationUrl */ public function setNotificationUrl($notificationUrl) { $this->notificationUrl = $notificationUrl; } /** * {@inheritDoc} */ public function getNotificationUrl() { return $this->notificationUrl; } /** * Sets a list of patterns to be excluded from archives * * @param array $excludes */ public function setArchiveExcludes(array $excludes) { $this->archiveExcludes = $excludes; } /** * {@inheritDoc} */ public function getArchiveExcludes() { return $this->archiveExcludes; } /** * Replaces current version and pretty version with passed values. * It also sets stability. * * @param string $version The package's normalized version * @param string $prettyVersion The package's non-normalized version */ public function replaceVersion($version, $prettyVersion) { $this->version = $version; $this->prettyVersion = $prettyVersion; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; } protected function getUrls($url, $mirrors, $ref, $type, $urlType) { if (!$url) { return array(); } $urls = array($url); if ($mirrors) { foreach ($mirrors as $mirror) { if ($urlType === 'dist') { $mirrorUrl = ComposerMirror::processUrl($mirror['url'], $this->name, $this->version, $ref, $type); } elseif ($urlType === 'source' && $type === 'git') { $mirrorUrl = ComposerMirror::processGitUrl($mirror['url'], $this->name, $url, $type); } elseif ($urlType === 'source' && $type === 'hg') { $mirrorUrl = ComposerMirror::processHgUrl($mirror['url'], $this->name, $url, $type); } if (!in_array($mirrorUrl, $urls)) { $func = $mirror['preferred'] ? 'array_unshift' : 'array_push'; $func($urls, $mirrorUrl); } } } return $urls; } } composer-1.6.3/src/Composer/Package/PackageInterface.php000066400000000000000000000216231323436022200231470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; use Composer\Repository\RepositoryInterface; /** * Defines the essential information a package has that is used during solving/installation * * @author Jordi Boggiano */ interface PackageInterface { /** * Returns the package's name without version info, thus not a unique identifier * * @return string package name */ public function getName(); /** * Returns the package's pretty (i.e. with proper case) name * * @return string package name */ public function getPrettyName(); /** * Returns a set of names that could refer to this package * * No version or release type information should be included in any of the * names. Provided or replaced package names need to be returned as well. * * @return array An array of strings referring to this package */ public function getNames(); /** * Allows the solver to set an id for this package to refer to it. * * @param int $id */ public function setId($id); /** * Retrieves the package's id set through setId * * @return int The previously set package id */ public function getId(); /** * Returns whether the package is a development virtual package or a concrete one * * @return bool */ public function isDev(); /** * Returns the package type, e.g. library * * @return string The package type */ public function getType(); /** * Returns the package targetDir property * * @return string The package targetDir */ public function getTargetDir(); /** * Returns the package extra data * * @return array The package extra data */ public function getExtra(); /** * Sets source from which this package was installed (source/dist). * * @param string $type source/dist */ public function setInstallationSource($type); /** * Returns source from which this package was installed (source/dist). * * @return string source/dist */ public function getInstallationSource(); /** * Returns the repository type of this package, e.g. git, svn * * @return string The repository type */ public function getSourceType(); /** * Returns the repository url of this package, e.g. git://github.com/naderman/composer.git * * @return string The repository url */ public function getSourceUrl(); /** * Returns the repository urls of this package including mirrors, e.g. git://github.com/naderman/composer.git * * @return array */ public function getSourceUrls(); /** * Returns the repository reference of this package, e.g. master, 1.0.0 or a commit hash for git * * @return string The repository reference */ public function getSourceReference(); /** * Returns the source mirrors of this package * * @return array|null */ public function getSourceMirrors(); /** * Returns the type of the distribution archive of this version, e.g. zip, tarball * * @return string The repository type */ public function getDistType(); /** * Returns the url of the distribution archive of this version * * @return string */ public function getDistUrl(); /** * Returns the urls of the distribution archive of this version, including mirrors * * @return array */ public function getDistUrls(); /** * Returns the reference of the distribution archive of this version, e.g. master, 1.0.0 or a commit hash for git * * @return string */ public function getDistReference(); /** * Returns the sha1 checksum for the distribution archive of this version * * @return string */ public function getDistSha1Checksum(); /** * Returns the dist mirrors of this package * * @return array|null */ public function getDistMirrors(); /** * Returns the version of this package * * @return string version */ public function getVersion(); /** * Returns the pretty (i.e. non-normalized) version string of this package * * @return string version */ public function getPrettyVersion(); /** * Returns the pretty version string plus a git or hg commit hash of this package * * @see getPrettyVersion * * @param bool $truncate If the source reference is a sha1 hash, truncate it * @return string version */ public function getFullPrettyVersion($truncate = true); /** * Returns the release date of the package * * @return \DateTime */ public function getReleaseDate(); /** * Returns the stability of this package: one of (dev, alpha, beta, RC, stable) * * @return string */ public function getStability(); /** * Returns a set of links to packages which need to be installed before * this package can be installed * * @return Link[] An array of package links defining required packages */ public function getRequires(); /** * Returns a set of links to packages which must not be installed at the * same time as this package * * @return Link[] An array of package links defining conflicting packages */ public function getConflicts(); /** * Returns a set of links to virtual packages that are provided through * this package * * @return Link[] An array of package links defining provided packages */ public function getProvides(); /** * Returns a set of links to packages which can alternatively be * satisfied by installing this package * * @return Link[] An array of package links defining replaced packages */ public function getReplaces(); /** * Returns a set of links to packages which are required to develop * this package. These are installed if in dev mode. * * @return Link[] An array of package links defining packages required for development */ public function getDevRequires(); /** * Returns a set of package names and reasons why they are useful in * combination with this package. * * @return array An array of package suggestions with descriptions */ public function getSuggests(); /** * Returns an associative array of autoloading rules * * {"": {""}} * * Type is either "psr-4", "psr-0", "classmap" or "files". Namespaces are mapped to * directories for autoloading using the type specified. * * @return array Mapping of autoloading rules */ public function getAutoload(); /** * Returns an associative array of dev autoloading rules * * {"": {""}} * * Type is either "psr-4", "psr-0", "classmap" or "files". Namespaces are mapped to * directories for autoloading using the type specified. * * @return array Mapping of dev autoloading rules */ public function getDevAutoload(); /** * Returns a list of directories which should get added to PHP's * include path. * * @return array */ public function getIncludePaths(); /** * Stores a reference to the repository that owns the package * * @param RepositoryInterface $repository */ public function setRepository(RepositoryInterface $repository); /** * Returns a reference to the repository that owns the package * * @return RepositoryInterface */ public function getRepository(); /** * Returns the package binaries * * @return array */ public function getBinaries(); /** * Returns package unique name, constructed from name and version. * * @return string */ public function getUniqueName(); /** * Returns the package notification url * * @return string */ public function getNotificationUrl(); /** * Converts the package into a readable and unique string * * @return string */ public function __toString(); /** * Converts the package into a pretty readable string * * @return string */ public function getPrettyString(); /** * Returns a list of patterns to exclude from package archives * * @return array */ public function getArchiveExcludes(); /** * Returns a list of options to download package dist files * * @return array */ public function getTransportOptions(); } composer-1.6.3/src/Composer/Package/RootAliasPackage.php000066400000000000000000000070751323436022200231510ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; /** * @author Jordi Boggiano */ class RootAliasPackage extends AliasPackage implements RootPackageInterface { public function __construct(RootPackageInterface $aliasOf, $version, $prettyVersion) { parent::__construct($aliasOf, $version, $prettyVersion); } /** * {@inheritDoc} */ public function getAliases() { return $this->aliasOf->getAliases(); } /** * {@inheritDoc} */ public function getMinimumStability() { return $this->aliasOf->getMinimumStability(); } /** * {@inheritDoc} */ public function getStabilityFlags() { return $this->aliasOf->getStabilityFlags(); } /** * {@inheritDoc} */ public function getReferences() { return $this->aliasOf->getReferences(); } /** * {@inheritDoc} */ public function getPreferStable() { return $this->aliasOf->getPreferStable(); } /** * {@inheritDoc} */ public function getConfig() { return $this->aliasOf->getConfig(); } /** * {@inheritDoc} */ public function setRequires(array $require) { $this->requires = $this->replaceSelfVersionDependencies($require, 'requires'); $this->aliasOf->setRequires($require); } /** * {@inheritDoc} */ public function setDevRequires(array $devRequire) { $this->devRequires = $this->replaceSelfVersionDependencies($devRequire, 'devRequires'); $this->aliasOf->setDevRequires($devRequire); } /** * {@inheritDoc} */ public function setConflicts(array $conflicts) { $this->conflicts = $this->replaceSelfVersionDependencies($conflicts, 'conflicts'); $this->aliasOf->setConflicts($conflicts); } /** * {@inheritDoc} */ public function setProvides(array $provides) { $this->provides = $this->replaceSelfVersionDependencies($provides, 'provides'); $this->aliasOf->setProvides($provides); } /** * {@inheritDoc} */ public function setReplaces(array $replaces) { $this->replaces = $this->replaceSelfVersionDependencies($replaces, 'replaces'); $this->aliasOf->setReplaces($replaces); } /** * {@inheritDoc} */ public function setRepositories($repositories) { $this->aliasOf->setRepositories($repositories); } /** * {@inheritDoc} */ public function setAutoload(array $autoload) { $this->aliasOf->setAutoload($autoload); } /** * {@inheritDoc} */ public function setDevAutoload(array $devAutoload) { $this->aliasOf->setDevAutoload($devAutoload); } /** * {@inheritDoc} */ public function setStabilityFlags(array $stabilityFlags) { $this->aliasOf->setStabilityFlags($stabilityFlags); } /** * {@inheritDoc} */ public function setSuggests(array $suggests) { $this->aliasOf->setSuggests($suggests); } /** * {@inheritDoc} */ public function setExtra(array $extra) { $this->aliasOf->setExtra($extra); } public function __clone() { parent::__clone(); $this->aliasOf = clone $this->aliasOf; } } composer-1.6.3/src/Composer/Package/RootPackage.php000066400000000000000000000051041323436022200221660ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; /** * The root package represents the project's composer.json and contains additional metadata * * @author Jordi Boggiano */ class RootPackage extends CompletePackage implements RootPackageInterface { protected $minimumStability = 'stable'; protected $preferStable = false; protected $stabilityFlags = array(); protected $config = array(); protected $references = array(); protected $aliases = array(); /** * Set the minimumStability * * @param string $minimumStability */ public function setMinimumStability($minimumStability) { $this->minimumStability = $minimumStability; } /** * {@inheritDoc} */ public function getMinimumStability() { return $this->minimumStability; } /** * Set the stabilityFlags * * @param array $stabilityFlags */ public function setStabilityFlags(array $stabilityFlags) { $this->stabilityFlags = $stabilityFlags; } /** * {@inheritDoc} */ public function getStabilityFlags() { return $this->stabilityFlags; } /** * Set the preferStable * * @param bool $preferStable */ public function setPreferStable($preferStable) { $this->preferStable = $preferStable; } /** * {@inheritDoc} */ public function getPreferStable() { return $this->preferStable; } /** * Set the config * * @param array $config */ public function setConfig(array $config) { $this->config = $config; } /** * {@inheritDoc} */ public function getConfig() { return $this->config; } /** * Set the references * * @param array $references */ public function setReferences(array $references) { $this->references = $references; } /** * {@inheritDoc} */ public function getReferences() { return $this->references; } /** * Set the aliases * * @param array $aliases */ public function setAliases(array $aliases) { $this->aliases = $aliases; } /** * {@inheritDoc} */ public function getAliases() { return $this->aliases; } } composer-1.6.3/src/Composer/Package/RootPackageInterface.php000066400000000000000000000062101323436022200240060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package; /** * Defines additional fields that are only needed for the root package * * @author Jordi Boggiano */ interface RootPackageInterface extends CompletePackageInterface { /** * Returns a set of package names and their aliases * * @return array */ public function getAliases(); /** * Returns the minimum stability of the package * * @return string */ public function getMinimumStability(); /** * Returns the stability flags to apply to dependencies * * array('foo/bar' => 'dev') * * @return array */ public function getStabilityFlags(); /** * Returns a set of package names and source references that must be enforced on them * * array('foo/bar' => 'abcd1234') * * @return array */ public function getReferences(); /** * Returns true if the root package prefers picking stable packages over unstable ones * * @return bool */ public function getPreferStable(); /** * Returns the root package's configuration * * @return array */ public function getConfig(); /** * Set the required packages * * @param Link[] $requires A set of package links */ public function setRequires(array $requires); /** * Set the recommended packages * * @param Link[] $devRequires A set of package links */ public function setDevRequires(array $devRequires); /** * Set the conflicting packages * * @param Link[] $conflicts A set of package links */ public function setConflicts(array $conflicts); /** * Set the provided virtual packages * * @param Link[] $provides A set of package links */ public function setProvides(array $provides); /** * Set the packages this one replaces * * @param Link[] $replaces A set of package links */ public function setReplaces(array $replaces); /** * Set the repositories * * @param array $repositories */ public function setRepositories($repositories); /** * Set the autoload mapping * * @param array $autoload Mapping of autoloading rules */ public function setAutoload(array $autoload); /** * Set the dev autoload mapping * * @param array $devAutoload Mapping of dev autoloading rules */ public function setDevAutoload(array $devAutoload); /** * Set the stabilityFlags * * @param array $stabilityFlags */ public function setStabilityFlags(array $stabilityFlags); /** * Set the suggested packages * * @param array $suggests A set of package names/comments */ public function setSuggests(array $suggests); /** * @param array $extra */ public function setExtra(array $extra); } composer-1.6.3/src/Composer/Package/Version/000077500000000000000000000000001323436022200207035ustar00rootroot00000000000000composer-1.6.3/src/Composer/Package/Version/VersionGuesser.php000066400000000000000000000274571323436022200244160ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Version; use Composer\Config; use Composer\Repository\Vcs\HgDriver; use Composer\IO\NullIO; use Composer\Semver\VersionParser as SemverVersionParser; use Composer\Util\Git as GitUtil; use Composer\Util\ProcessExecutor; use Composer\Util\Svn as SvnUtil; /** * Try to guess the current version number based on different VCS configuration. * * @author Jordi Boggiano * @author Samuel Roze */ class VersionGuesser { /** * @var Config */ private $config; /** * @var ProcessExecutor */ private $process; /** * @var SemverVersionParser */ private $versionParser; /** * @param Config $config * @param ProcessExecutor $process * @param SemverVersionParser $versionParser */ public function __construct(Config $config, ProcessExecutor $process, SemverVersionParser $versionParser) { $this->config = $config; $this->process = $process; $this->versionParser = $versionParser; } /** * @param array $packageConfig * @param string $path Path to guess into * * @return null|array versionData, 'version', 'pretty_version' and 'commit' keys */ public function guessVersion(array $packageConfig, $path) { if (function_exists('proc_open')) { $versionData = $this->guessGitVersion($packageConfig, $path); if (null !== $versionData && null !== $versionData['version']) { return $this->postprocess($versionData); } $versionData = $this->guessHgVersion($packageConfig, $path); if (null !== $versionData && null !== $versionData['version']) { return $this->postprocess($versionData); } $versionData = $this->guessFossilVersion($packageConfig, $path); if (null !== $versionData && null !== $versionData['version']) { return $this->postprocess($versionData); } $versionData = $this->guessSvnVersion($packageConfig, $path); if (null !== $versionData && null !== $versionData['version']) { return $this->postprocess($versionData); } } } private function postprocess(array $versionData) { if ('-dev' === substr($versionData['version'], -4) && preg_match('{\.9{7}}', $versionData['version'])) { $versionData['pretty_version'] = preg_replace('{(\.9{7})+}', '.x', $versionData['version']); } return $versionData; } private function guessGitVersion(array $packageConfig, $path) { GitUtil::cleanEnv(); $commit = null; $version = null; $prettyVersion = null; $isDetached = false; // try to fetch current version from git branch if (0 === $this->process->execute('git branch --no-color --no-abbrev -v', $output, $path)) { $branches = array(); $isFeatureBranch = false; // find current branch and collect all branch names foreach ($this->process->splitLines($output) as $branch) { if ($branch && preg_match('{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}', $branch, $match)) { if ($match[1] === '(no branch)' || substr($match[1], 0, 10) === '(detached ' || substr($match[1], 0, 17) === '(HEAD detached at') { $version = 'dev-' . $match[2]; $prettyVersion = $version; $isFeatureBranch = true; $isDetached = true; } else { $version = $this->versionParser->normalizeBranch($match[1]); $prettyVersion = 'dev-' . $match[1]; $isFeatureBranch = 0 === strpos($version, 'dev-'); } if ($match[2]) { $commit = $match[2]; } } if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) { if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+) .*$}', $branch, $match)) { $branches[] = $match[1]; } } } if ($isFeatureBranch) { // try to find the best (nearest) version branch to assume this feature's version $result = $this->guessFeatureVersion($packageConfig, $version, $branches, 'git rev-list %candidate%..%branch%', $path); $version = $result['version']; $prettyVersion = $result['pretty_version']; } } if (!$version || $isDetached) { $result = $this->versionFromGitTags($path); if ($result) { $version = $result['version']; $prettyVersion = $result['pretty_version']; } } if (!$commit) { $command = 'git log --pretty="%H" -n1 HEAD'; if (0 === $this->process->execute($command, $output, $path)) { $commit = trim($output) ?: null; } } return array('version' => $version, 'commit' => $commit, 'pretty_version' => $prettyVersion); } private function versionFromGitTags($path) { // try to fetch current version from git tags if (0 === $this->process->execute('git describe --exact-match --tags', $output, $path)) { try { $version = $this->versionParser->normalize(trim($output)); return array('version' => $version, 'pretty_version' => trim($output)); } catch (\Exception $e) { } } return null; } private function guessHgVersion(array $packageConfig, $path) { // try to fetch current version from hg branch if (0 === $this->process->execute('hg branch', $output, $path)) { $branch = trim($output); $version = $this->versionParser->normalizeBranch($branch); $isFeatureBranch = 0 === strpos($version, 'dev-'); if ('9999999-dev' === $version) { $version = 'dev-' . $branch; } if (!$isFeatureBranch) { return array('version' => $version, 'commit' => null, 'pretty_version' => $version); } // re-use the HgDriver to fetch branches (this properly includes bookmarks) $driver = new HgDriver(array('url' => $path), new NullIO(), $this->config, $this->process); $branches = array_keys($driver->getBranches()); // try to find the best (nearest) version branch to assume this feature's version $result = $this->guessFeatureVersion($packageConfig, $version, $branches, 'hg log -r "not ancestors(\'%candidate%\') and ancestors(\'%branch%\')" --template "{node}\\n"', $path); $result['commit'] = ''; return $result; } } private function guessFeatureVersion(array $packageConfig, $version, array $branches, $scmCmdline, $path) { $prettyVersion = $version; // ignore feature branches if they have no branch-alias or self.version is used // and find the branch they came from to use as a version instead if ((isset($packageConfig['extra']['branch-alias']) && !isset($packageConfig['extra']['branch-alias'][$version])) || strpos(json_encode($packageConfig), '"self.version"') ) { $branch = preg_replace('{^dev-}', '', $version); $length = PHP_INT_MAX; $nonFeatureBranches = ''; if (!empty($packageConfig['non-feature-branches'])) { $nonFeatureBranches = implode('|', $packageConfig['non-feature-branches']); } foreach ($branches as $candidate) { // return directly, if branch is configured to be non-feature branch if ($candidate === $branch && preg_match('{^(' . $nonFeatureBranches . ')$}', $candidate)) { break; } // do not compare against itself or other feature branches if ($candidate === $branch || !preg_match('{^(' . $nonFeatureBranches . '|master|trunk|default|develop|\d+\..+)$}', $candidate, $match)) { continue; } $cmdLine = str_replace(array('%candidate%', '%branch%'), array($candidate, $branch), $scmCmdline); if (0 !== $this->process->execute($cmdLine, $output, $path)) { continue; } if (strlen($output) < $length) { $length = strlen($output); $version = $this->versionParser->normalizeBranch($candidate); $prettyVersion = 'dev-' . $match[1]; if ('9999999-dev' === $version) { $version = $prettyVersion; } } } } return array('version' => $version, 'pretty_version' => $prettyVersion); } private function guessFossilVersion(array $packageConfig, $path) { $version = null; $prettyVersion = null; // try to fetch current version from fossil if (0 === $this->process->execute('fossil branch list', $output, $path)) { $branch = trim($output); $version = $this->versionParser->normalizeBranch($branch); $prettyVersion = 'dev-' . $branch; if ('9999999-dev' === $version) { $version = $prettyVersion; } } // try to fetch current version from fossil tags if (0 === $this->process->execute('fossil tag list', $output, $path)) { try { $version = $this->versionParser->normalize(trim($output)); $prettyVersion = trim($output); } catch (\Exception $e) { } } return array('version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion); } private function guessSvnVersion(array $packageConfig, $path) { SvnUtil::cleanEnv(); // try to fetch current version from svn if (0 === $this->process->execute('svn info --xml', $output, $path)) { $trunkPath = isset($packageConfig['trunk-path']) ? preg_quote($packageConfig['trunk-path'], '#') : 'trunk'; $branchesPath = isset($packageConfig['branches-path']) ? preg_quote($packageConfig['branches-path'], '#') : 'branches'; $tagsPath = isset($packageConfig['tags-path']) ? preg_quote($packageConfig['tags-path'], '#') : 'tags'; $urlPattern = '#.*/(' . $trunkPath . '|(' . $branchesPath . '|' . $tagsPath . ')/(.*))#'; if (preg_match($urlPattern, $output, $matches)) { if (isset($matches[2]) && ($branchesPath === $matches[2] || $tagsPath === $matches[2])) { // we are in a branches path $version = $this->versionParser->normalizeBranch($matches[3]); $prettyVersion = 'dev-' . $matches[3]; if ('9999999-dev' === $version) { $version = $prettyVersion; } return array('version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion); } $prettyVersion = trim($matches[1]); $version = $this->versionParser->normalize($prettyVersion); return array('version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion); } } } } composer-1.6.3/src/Composer/Package/Version/VersionParser.php000066400000000000000000000040541323436022200242210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Version; use Composer\Repository\PlatformRepository; use Composer\Semver\VersionParser as SemverVersionParser; class VersionParser extends SemverVersionParser { private static $constraints = array(); /** * {@inheritDoc} */ public function parseConstraints($constraints) { if (!isset(self::$constraints[$constraints])) { self::$constraints[$constraints] = parent::parseConstraints($constraints); } return self::$constraints[$constraints]; } /** * Parses an array of strings representing package/version pairs. * * The parsing results in an array of arrays, each of which * contain a 'name' key with value and optionally a 'version' key with value. * * @param array $pairs a set of package/version pairs separated by ":", "=" or " " * * @return array[] array of arrays containing a name and (if provided) a version */ public function parseNameVersionPairs(array $pairs) { $pairs = array_values($pairs); $result = array(); for ($i = 0, $count = count($pairs); $i < $count; $i++) { $pair = preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i])); if (false === strpos($pair, ' ') && isset($pairs[$i + 1]) && false === strpos($pairs[$i + 1], '/') && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $pairs[$i + 1])) { $pair .= ' '.$pairs[$i + 1]; $i++; } if (strpos($pair, ' ')) { list($name, $version) = explode(' ', $pair, 2); $result[] = array('name' => $name, 'version' => $version); } else { $result[] = array('name' => $pair); } } return $result; } } composer-1.6.3/src/Composer/Package/Version/VersionSelector.php000066400000000000000000000137121323436022200245460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Version; use Composer\DependencyResolver\Pool; use Composer\Package\BasePackage; use Composer\Package\PackageInterface; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Dumper\ArrayDumper; use Composer\Semver\Constraint\Constraint; /** * Selects the best possible version for a package * * @author Ryan Weaver * @author Jordi Boggiano */ class VersionSelector { private $pool; private $parser; public function __construct(Pool $pool) { $this->pool = $pool; } /** * Given a package name and optional version, returns the latest PackageInterface * that matches. * * @param string $packageName * @param string $targetPackageVersion * @param string $targetPhpVersion * @param string $preferredStability * @return PackageInterface|bool */ public function findBestCandidate($packageName, $targetPackageVersion = null, $targetPhpVersion = null, $preferredStability = 'stable') { $constraint = $targetPackageVersion ? $this->getParser()->parseConstraints($targetPackageVersion) : null; $candidates = $this->pool->whatProvides(strtolower($packageName), $constraint, true); if ($targetPhpVersion) { $phpConstraint = new Constraint('==', $this->getParser()->normalize($targetPhpVersion)); $candidates = array_filter($candidates, function ($pkg) use ($phpConstraint) { $reqs = $pkg->getRequires(); return !isset($reqs['php']) || $reqs['php']->getConstraint()->matches($phpConstraint); }); } if (!$candidates) { return false; } // select highest version if we have many $package = reset($candidates); $minPriority = BasePackage::$stabilities[$preferredStability]; foreach ($candidates as $candidate) { $candidatePriority = $candidate->getStabilityPriority(); $currentPriority = $package->getStabilityPriority(); // candidate is less stable than our preferred stability, // and current package is more stable than candidate, skip it if ($minPriority < $candidatePriority && $currentPriority < $candidatePriority) { continue; } // candidate is less stable than our preferred stability, // and current package is less stable than candidate, select candidate if ($minPriority < $candidatePriority && $candidatePriority < $currentPriority) { $package = $candidate; continue; } // candidate is more stable than our preferred stability, // and current package is less stable than preferred stability, select candidate if ($minPriority >= $candidatePriority && $minPriority < $currentPriority) { $package = $candidate; continue; } // select highest version of the two if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) { $package = $candidate; } } return $package; } /** * Given a concrete version, this returns a ~ constraint (when possible) * that should be used, for example, in composer.json. * * For example: * * 1.2.1 -> ^1.2 * * 1.2 -> ^1.2 * * v3.2.1 -> ^3.2 * * 2.0-beta.1 -> ^2.0@beta * * dev-master -> ^2.1@dev (dev version with alias) * * dev-master -> dev-master (dev versions are untouched) * * @param PackageInterface $package * @return string */ public function findRecommendedRequireVersion(PackageInterface $package) { $version = $package->getVersion(); if (!$package->isDev()) { return $this->transformVersion($version, $package->getPrettyVersion(), $package->getStability()); } $loader = new ArrayLoader($this->getParser()); $dumper = new ArrayDumper(); $extra = $loader->getBranchAlias($dumper->dump($package)); if ($extra) { $extra = preg_replace('{^(\d+\.\d+\.\d+)(\.9999999)-dev$}', '$1.0', $extra, -1, $count); if ($count) { $extra = str_replace('.9999999', '.0', $extra); return $this->transformVersion($extra, $extra, 'dev'); } } return $package->getPrettyVersion(); } private function transformVersion($version, $prettyVersion, $stability) { // attempt to transform 2.1.1 to 2.1 // this allows you to upgrade through minor versions $semanticVersionParts = explode('.', $version); // check to see if we have a semver-looking version if (count($semanticVersionParts) == 4 && preg_match('{^0\D?}', $semanticVersionParts[3])) { // remove the last parts (i.e. the patch version number and any extra) if ($semanticVersionParts[0] === '0') { unset($semanticVersionParts[3]); } else { unset($semanticVersionParts[2], $semanticVersionParts[3]); } $version = implode('.', $semanticVersionParts); } else { return $prettyVersion; } // append stability flag if not default if ($stability != 'stable') { $version .= '@'.$stability; } // 2.1 -> ^2.1 return '^' . $version; } private function getParser() { if ($this->parser === null) { $this->parser = new VersionParser(); } return $this->parser; } } composer-1.6.3/src/Composer/Plugin/000077500000000000000000000000001323436022200171615ustar00rootroot00000000000000composer-1.6.3/src/Composer/Plugin/Capability/000077500000000000000000000000001323436022200212425ustar00rootroot00000000000000composer-1.6.3/src/Composer/Plugin/Capability/Capability.php000066400000000000000000000007451323436022200240420ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin\Capability; /** * Marker interface for Plugin capabilities. * Every new Capability which is added to the Plugin API must implement this interface. * * @api */ interface Capability { } composer-1.6.3/src/Composer/Plugin/Capability/CommandProvider.php000066400000000000000000000015371323436022200250520ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin\Capability; /** * Commands Provider Interface * * This capability will receive an array with 'composer' and 'io' keys as * constructor argument. Those contain Composer\Composer and Composer\IO\IOInterface * instances. It also contains a 'plugin' key containing the plugin instance that * created the capability. * * @author Jérémy Derussé */ interface CommandProvider extends Capability { /** * Retrieves an array of commands * * @return \Composer\Command\BaseCommand[] */ public function getCommands(); } composer-1.6.3/src/Composer/Plugin/Capable.php000066400000000000000000000022331323436022200212210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; /** * Plugins which need to expose various implementations * of the Composer Plugin Capabilities must have their * declared Plugin class implementing this interface. * * @api */ interface Capable { /** * Method by which a Plugin announces its API implementations, through an array * with a special structure. * * The key must be a string, representing a fully qualified class/interface name * which Composer Plugin API exposes. * The value must be a string as well, representing the fully qualified class name * of the implementing class. * * @tutorial * * return array( * 'Composer\Plugin\Capability\CommandProvider' => 'My\CommandProvider', * 'Composer\Plugin\Capability\Validator' => 'My\Validator', * ); * * @return string[] */ public function getCapabilities(); } composer-1.6.3/src/Composer/Plugin/CommandEvent.php000066400000000000000000000036551323436022200222630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; use Composer\EventDispatcher\Event; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * An event for all commands. * * @author Nils Adermann */ class CommandEvent extends Event { /** * @var string */ private $commandName; /** * @var InputInterface */ private $input; /** * @var OutputInterface */ private $output; /** * Constructor. * * @param string $name The event name * @param string $commandName The command name * @param InputInterface $input * @param OutputInterface $output * @param array $args Arguments passed by the user * @param array $flags Optional flags to pass data not as argument */ public function __construct($name, $commandName, $input, $output, array $args = array(), array $flags = array()) { parent::__construct($name, $args, $flags); $this->commandName = $commandName; $this->input = $input; $this->output = $output; } /** * Returns the command input interface * * @return InputInterface */ public function getInput() { return $this->input; } /** * Retrieves the command output interface * * @return OutputInterface */ public function getOutput() { return $this->output; } /** * Retrieves the name of the command being run * * @return string */ public function getCommandName() { return $this->commandName; } } composer-1.6.3/src/Composer/Plugin/PluginEvents.php000066400000000000000000000021621323436022200223160ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; /** * The Plugin Events. * * @author Nils Adermann */ class PluginEvents { /** * The INIT event occurs after a Composer instance is done being initialized * * The event listener method receives a * Composer\EventDispatcher\Event instance. * * @var string */ const INIT = 'init'; /** * The COMMAND event occurs as a command begins * * The event listener method receives a * Composer\Plugin\CommandEvent instance. * * @var string */ const COMMAND = 'command'; /** * The PRE_FILE_DOWNLOAD event occurs before downloading a file * * The event listener method receives a * Composer\Plugin\PreFileDownloadEvent instance. * * @var string */ const PRE_FILE_DOWNLOAD = 'pre-file-download'; } composer-1.6.3/src/Composer/Plugin/PluginInterface.php000066400000000000000000000014521323436022200227530ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; use Composer\Composer; use Composer\IO\IOInterface; /** * Plugin interface * * @author Nils Adermann */ interface PluginInterface { /** * Version number of the internal composer-plugin-api package * * @var string */ const PLUGIN_API_VERSION = '1.1.0'; /** * Apply plugin modifications to Composer * * @param Composer $composer * @param IOInterface $io */ public function activate(Composer $composer, IOInterface $io); } composer-1.6.3/src/Composer/Plugin/PluginManager.php000066400000000000000000000370471323436022200224360ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; use Composer\Composer; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\IO\IOInterface; use Composer\Package\Package; use Composer\Package\Version\VersionParser; use Composer\Repository\RepositoryInterface; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Semver\Constraint\Constraint; use Composer\DependencyResolver\Pool; use Composer\Plugin\Capability\Capability; /** * Plugin manager * * @author Nils Adermann * @author Jordi Boggiano */ class PluginManager { protected $composer; protected $io; protected $globalComposer; protected $versionParser; protected $disablePlugins = false; protected $plugins = array(); protected $registeredPlugins = array(); private static $classCounter = 0; /** * Initializes plugin manager * * @param IOInterface $io * @param Composer $composer * @param Composer $globalComposer * @param bool $disablePlugins */ public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false) { $this->io = $io; $this->composer = $composer; $this->globalComposer = $globalComposer; $this->versionParser = new VersionParser(); $this->disablePlugins = $disablePlugins; } /** * Loads all plugins from currently installed plugin packages */ public function loadInstalledPlugins() { if ($this->disablePlugins) { return; } $repo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; if ($repo) { $this->loadRepository($repo); } if ($globalRepo) { $this->loadRepository($globalRepo); } } /** * Gets all currently active plugin instances * * @return array plugins */ public function getPlugins() { return $this->plugins; } /** * Gets global composer or null when main composer is not fully loaded * * @return Composer|null */ public function getGlobalComposer() { return $this->globalComposer; } /** * Register a plugin package, activate it etc. * * If it's of type composer-installer it is registered as an installer * instead for BC * * @param PackageInterface $package * @param bool $failOnMissingClasses By default this silently skips plugins that can not be found, but if set to true it fails with an exception * * @throws \UnexpectedValueException */ public function registerPackage(PackageInterface $package, $failOnMissingClasses = false) { if ($this->disablePlugins) { return; } if ($package->getType() === 'composer-plugin') { $requiresComposer = null; foreach ($package->getRequires() as $link) { /** @var Link $link */ if ('composer-plugin-api' === $link->getTarget()) { $requiresComposer = $link->getConstraint(); break; } } if (!$requiresComposer) { throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package."); } $currentPluginApiVersion = $this->getPluginApiVersion(); $currentPluginApiConstraint = new Constraint('==', $this->versionParser->normalize($currentPluginApiVersion)); if ($requiresComposer->getPrettyString() === '1.0.0' && $this->getPluginApiVersion() === '1.0.0') { $this->io->writeError('The "' . $package->getName() . '" plugin requires composer-plugin-api 1.0.0, this *WILL* break in the future and it should be fixed ASAP (require ^1.0 for example).'); } elseif (!$requiresComposer->matches($currentPluginApiConstraint)) { $this->io->writeError('The "' . $package->getName() . '" plugin was skipped because it requires a Plugin API version ("' . $requiresComposer->getPrettyString() . '") that does not match your Composer installation ("' . $currentPluginApiVersion . '"). You may need to run composer update with the "--no-plugins" option.'); return; } } $oldInstallerPlugin = ($package->getType() === 'composer-installer'); if (in_array($package->getName(), $this->registeredPlugins)) { return; } $extra = $package->getExtra(); if (empty($extra['class'])) { throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.'); } $classes = is_array($extra['class']) ? $extra['class'] : array($extra['class']); $localRepo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; $pool = new Pool('dev'); $pool->addRepository($localRepo); if ($globalRepo) { $pool->addRepository($globalRepo); } $autoloadPackages = array($package->getName() => $package); $autoloadPackages = $this->collectDependencies($pool, $autoloadPackages, $package); $generator = $this->composer->getAutoloadGenerator(); $autoloads = array(); foreach ($autoloadPackages as $autoloadPackage) { $downloadPath = $this->getInstallPath($autoloadPackage, ($globalRepo && $globalRepo->hasPackage($autoloadPackage))); $autoloads[] = array($autoloadPackage, $downloadPath); } $map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0')); $classLoader = $generator->createLoader($map); $classLoader->register(); foreach ($classes as $class) { if (class_exists($class, false)) { $class = trim($class, '\\'); $path = $classLoader->findFile($class); $code = file_get_contents($path); $separatorPos = strrpos($class, '\\'); $className = $class; if ($separatorPos) { $className = substr($class, $separatorPos + 1); } $code = preg_replace('{^((?:final\s+)?(?:\s*))class\s+('.preg_quote($className).')}mi', '$1class $2_composer_tmp'.self::$classCounter, $code, 1); $code = str_replace('__FILE__', var_export($path, true), $code); $code = str_replace('__DIR__', var_export(dirname($path), true), $code); $code = str_replace('__CLASS__', var_export($class, true), $code); $code = preg_replace('/^\s*<\?(php)?/i', '', $code, 1); eval($code); $class .= '_composer_tmp'.self::$classCounter; self::$classCounter++; } if ($oldInstallerPlugin) { $installer = new $class($this->io, $this->composer); $this->composer->getInstallationManager()->addInstaller($installer); } elseif (class_exists($class)) { $plugin = new $class(); $this->addPlugin($plugin); $this->registeredPlugins[] = $package->getName(); } elseif ($failOnMissingClasses) { throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class); } } } /** * Returns the version of the internal composer-plugin-api package. * * @return string */ protected function getPluginApiVersion() { return PluginInterface::PLUGIN_API_VERSION; } /** * Adds a plugin, activates it and registers it with the event dispatcher * * Ideally plugin packages should be registered via registerPackage, but if you use Composer * programmatically and want to register a plugin class directly this is a valid way * to do it. * * @param PluginInterface $plugin plugin instance */ public function addPlugin(PluginInterface $plugin) { $this->io->writeError('Loading plugin '.get_class($plugin), true, IOInterface::DEBUG); $this->plugins[] = $plugin; $plugin->activate($this->composer, $this->io); if ($plugin instanceof EventSubscriberInterface) { $this->composer->getEventDispatcher()->addSubscriber($plugin); } } /** * Load all plugins and installers from a repository * * Note that plugins in the specified repository that rely on events that * have fired prior to loading will be missed. This means you likely want to * call this method as early as possible. * * @param RepositoryInterface $repo Repository to scan for plugins to install * * @throws \RuntimeException */ private function loadRepository(RepositoryInterface $repo) { foreach ($repo->getPackages() as $package) { /** @var PackageInterface $package */ if ($package instanceof AliasPackage) { continue; } if ('composer-plugin' === $package->getType()) { $this->registerPackage($package); // Backward compatibility } elseif ('composer-installer' === $package->getType()) { $this->registerPackage($package); } } } /** * Recursively generates a map of package names to packages for all deps * * @param Pool $pool Package pool of installed packages * @param array $collected Current state of the map for recursion * @param PackageInterface $package The package to analyze * * @return array Map of package names to packages */ private function collectDependencies(Pool $pool, array $collected, PackageInterface $package) { $requires = array_merge( $package->getRequires(), $package->getDevRequires() ); foreach ($requires as $requireLink) { $requiredPackage = $this->lookupInstalledPackage($pool, $requireLink); if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) { $collected[$requiredPackage->getName()] = $requiredPackage; $collected = $this->collectDependencies($pool, $collected, $requiredPackage); } } return $collected; } /** * Resolves a package link to a package in the installed pool * * Since dependencies are already installed this should always find one. * * @param Pool $pool Pool of installed packages only * @param Link $link Package link to look up * * @return PackageInterface|null The found package */ private function lookupInstalledPackage(Pool $pool, Link $link) { $packages = $pool->whatProvides($link->getTarget(), $link->getConstraint()); return (!empty($packages)) ? $packages[0] : null; } /** * Retrieves the path a package is installed to. * * @param PackageInterface $package * @param bool $global Whether this is a global package * * @return string Install path */ private function getInstallPath(PackageInterface $package, $global = false) { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } return $this->globalComposer->getInstallationManager()->getInstallPath($package); } /** * @param PluginInterface $plugin * @param string $capability * @throws \RuntimeException On empty or non-string implementation class name value * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it */ protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability) { if (!($plugin instanceof Capable)) { return null; } $capabilities = (array) $plugin->getCapabilities(); if (!empty($capabilities[$capability]) && is_string($capabilities[$capability]) && trim($capabilities[$capability])) { return trim($capabilities[$capability]); } if ( array_key_exists($capability, $capabilities) && (empty($capabilities[$capability]) || !is_string($capabilities[$capability]) || !trim($capabilities[$capability])) ) { throw new \UnexpectedValueException('Plugin '.get_class($plugin).' provided invalid capability class name(s), got '.var_export($capabilities[$capability], 1)); } } /** * @param PluginInterface $plugin * @param string $capabilityClassName The fully qualified name of the API interface which the plugin may provide * an implementation of. * @param array $ctorArgs Arguments passed to Capability's constructor. * Keeping it an array will allow future values to be passed w\o changing the signature. * @return null|Capability */ public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = array()) { if ($capabilityClass = $this->getCapabilityImplementationClassName($plugin, $capabilityClassName)) { if (!class_exists($capabilityClass)) { throw new \RuntimeException("Cannot instantiate Capability, as class $capabilityClass from plugin ".get_class($plugin)." does not exist."); } $ctorArgs['plugin'] = $plugin; $capabilityObj = new $capabilityClass($ctorArgs); // FIXME these could use is_a and do the check *before* instantiating once drop support for php<5.3.9 if (!$capabilityObj instanceof Capability || !$capabilityObj instanceof $capabilityClassName) { throw new \RuntimeException( 'Class ' . $capabilityClass . ' must implement both Composer\Plugin\Capability\Capability and '. $capabilityClassName . '.' ); } return $capabilityObj; } } /** * @param string $capabilityClassName The fully qualified name of the API interface which the plugin may provide * an implementation of. * @param array $ctorArgs Arguments passed to Capability's constructor. * Keeping it an array will allow future values to be passed w\o changing the signature. * @return Capability[] */ public function getPluginCapabilities($capabilityClassName, array $ctorArgs = array()) { $capabilities = array(); foreach ($this->getPlugins() as $plugin) { if ($capability = $this->getPluginCapability($plugin, $capabilityClassName, $ctorArgs)) { $capabilities[] = $capability; } } return $capabilities; } } composer-1.6.3/src/Composer/Plugin/PreFileDownloadEvent.php000066400000000000000000000030671323436022200237200ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; use Composer\EventDispatcher\Event; use Composer\Util\RemoteFilesystem; /** * The pre file download event. * * @author Nils Adermann */ class PreFileDownloadEvent extends Event { /** * @var RemoteFilesystem */ private $rfs; /** * @var string */ private $processedUrl; /** * Constructor. * * @param string $name The event name * @param RemoteFilesystem $rfs * @param string $processedUrl */ public function __construct($name, RemoteFilesystem $rfs, $processedUrl) { parent::__construct($name); $this->rfs = $rfs; $this->processedUrl = $processedUrl; } /** * Returns the remote filesystem * * @return RemoteFilesystem */ public function getRemoteFilesystem() { return $this->rfs; } /** * Sets the remote filesystem * * @param RemoteFilesystem $rfs */ public function setRemoteFilesystem(RemoteFilesystem $rfs) { $this->rfs = $rfs; } /** * Retrieves the processed URL this remote filesystem will be used for * * @return string */ public function getProcessedUrl() { return $this->processedUrl; } } composer-1.6.3/src/Composer/Question/000077500000000000000000000000001323436022200175325ustar00rootroot00000000000000composer-1.6.3/src/Composer/Question/StrictConfirmationQuestion.php000066400000000000000000000051531323436022200256200ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Question; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Question\Question; /** * Represents a yes/no question * Enforces strict responses rather than non-standard answers counting as default * Based on Symfony\Component\Console\Question\ConfirmationQuestion * * @author Theo Tonge */ class StrictConfirmationQuestion extends Question { private $trueAnswerRegex; private $falseAnswerRegex; /** * Constructor.s * * @param string $question The question to ask to the user * @param bool $default The default answer to return, true or false * @param string $trueAnswerRegex A regex to match the "yes" answer * @param string $falseAnswerRegex A regex to match the "no" answer */ public function __construct($question, $default = true, $trueAnswerRegex = '/^y(?:es)?$/i', $falseAnswerRegex = '/^no?$/i') { parent::__construct($question, (bool) $default); $this->trueAnswerRegex = $trueAnswerRegex; $this->falseAnswerRegex = $falseAnswerRegex; $this->setNormalizer($this->getDefaultNormalizer()); $this->setValidator($this->getDefaultValidator()); } /** * Returns the default answer normalizer. * * @return callable */ private function getDefaultNormalizer() { $default = $this->getDefault(); $trueRegex = $this->trueAnswerRegex; $falseRegex = $this->falseAnswerRegex; return function ($answer) use ($default, $trueRegex, $falseRegex) { if (is_bool($answer)) { return $answer; } if (empty($answer) && !empty($default)) { return $default; } if (preg_match($trueRegex, $answer)) { return true; } if (preg_match($falseRegex, $answer)) { return false; } return null; }; } /** * Returns the default answer validator. * * @return callable */ private function getDefaultValidator() { return function ($answer) { if (!is_bool($answer)) { throw new InvalidArgumentException('Please answer yes, y, no, or n.'); } return $answer; }; } } composer-1.6.3/src/Composer/Repository/000077500000000000000000000000001323436022200201025ustar00rootroot00000000000000composer-1.6.3/src/Composer/Repository/ArrayRepository.php000066400000000000000000000131261323436022200237740ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\CompletePackageInterface; use Composer\Package\Version\VersionParser; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\Constraint; /** * A repository implementation that simply stores packages in an array * * @author Nils Adermann */ class ArrayRepository extends BaseRepository { /** @var PackageInterface[] */ protected $packages; public function __construct(array $packages = array()) { foreach ($packages as $package) { $this->addPackage($package); } } /** * {@inheritDoc} */ public function findPackage($name, $constraint) { $name = strtolower($name); if (!$constraint instanceof ConstraintInterface) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($constraint); } foreach ($this->getPackages() as $package) { if ($name === $package->getName()) { $pkgConstraint = new Constraint('==', $package->getVersion()); if ($constraint->matches($pkgConstraint)) { return $package; } } } return null; } /** * {@inheritDoc} */ public function findPackages($name, $constraint = null) { // normalize name $name = strtolower($name); $packages = array(); if (null !== $constraint && !$constraint instanceof ConstraintInterface) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($constraint); } foreach ($this->getPackages() as $package) { if ($name === $package->getName()) { $pkgConstraint = new Constraint('==', $package->getVersion()); if (null === $constraint || $constraint->matches($pkgConstraint)) { $packages[] = $package; } } } return $packages; } /** * {@inheritDoc} */ public function search($query, $mode = 0, $type = null) { $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i'; $matches = array(); foreach ($this->getPackages() as $package) { $name = $package->getName(); if (isset($matches[$name])) { continue; } if (preg_match($regex, $name) || ($mode === self::SEARCH_FULLTEXT && $package instanceof CompletePackageInterface && preg_match($regex, implode(' ', (array) $package->getKeywords()) . ' ' . $package->getDescription())) ) { if (null !== $type && $package->getType() !== $type) { continue; } $matches[$name] = array( 'name' => $package->getPrettyName(), 'description' => $package instanceof CompletePackageInterface ? $package->getDescription() : null, ); } } return array_values($matches); } /** * {@inheritDoc} */ public function hasPackage(PackageInterface $package) { $packageId = $package->getUniqueName(); foreach ($this->getPackages() as $repoPackage) { if ($packageId === $repoPackage->getUniqueName()) { return true; } } return false; } /** * Adds a new package to the repository * * @param PackageInterface $package */ public function addPackage(PackageInterface $package) { if (null === $this->packages) { $this->initialize(); } $package->setRepository($this); $this->packages[] = $package; if ($package instanceof AliasPackage) { $aliasedPackage = $package->getAliasOf(); if (null === $aliasedPackage->getRepository()) { $this->addPackage($aliasedPackage); } } } protected function createAliasPackage(PackageInterface $package, $alias, $prettyAlias) { return new AliasPackage($package instanceof AliasPackage ? $package->getAliasOf() : $package, $alias, $prettyAlias); } /** * Removes package from repository. * * @param PackageInterface $package package instance */ public function removePackage(PackageInterface $package) { $packageId = $package->getUniqueName(); foreach ($this->getPackages() as $key => $repoPackage) { if ($packageId === $repoPackage->getUniqueName()) { array_splice($this->packages, $key, 1); return; } } } /** * {@inheritDoc} */ public function getPackages() { if (null === $this->packages) { $this->initialize(); } return $this->packages; } /** * Returns the number of packages in this repository * * @return int Number of packages */ public function count() { return count($this->packages); } /** * Initializes the packages array. Mostly meant as an extension point. */ protected function initialize() { $this->packages = array(); } } composer-1.6.3/src/Composer/Repository/ArtifactRepository.php000066400000000000000000000116101323436022200244470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Loader\LoaderInterface; /** * @author Serge Smertin */ class ArtifactRepository extends ArrayRepository implements ConfigurableRepositoryInterface { /** @var LoaderInterface */ protected $loader; protected $lookup; protected $repoConfig; private $io; public function __construct(array $repoConfig, IOInterface $io) { parent::__construct(); if (!extension_loaded('zip')) { throw new \RuntimeException('The artifact repository requires PHP\'s zip extension'); } $this->loader = new ArrayLoader(); $this->lookup = $repoConfig['url']; $this->io = $io; $this->repoConfig = $repoConfig; } public function getRepoConfig() { return $this->repoConfig; } protected function initialize() { parent::initialize(); $this->scanDirectory($this->lookup); } private function scanDirectory($path) { $io = $this->io; $directory = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS); $iterator = new \RecursiveIteratorIterator($directory); $regex = new \RegexIterator($iterator, '/^.+\.(zip|phar)$/i'); foreach ($regex as $file) { /* @var $file \SplFileInfo */ if (!$file->isFile()) { continue; } $package = $this->getComposerInformation($file); if (!$package) { $io->writeError("File {$file->getBasename()} doesn't seem to hold a package", true, IOInterface::VERBOSE); continue; } $template = 'Found package %s (%s) in file %s'; $io->writeError(sprintf($template, $package->getName(), $package->getPrettyVersion(), $file->getBasename()), true, IOInterface::VERBOSE); $this->addPackage($package); } } /** * Find a file by name, returning the one that has the shortest path. * * @param \ZipArchive $zip * @param $filename * @return bool|int */ private function locateFile(\ZipArchive $zip, $filename) { $indexOfShortestMatch = false; $lengthOfShortestMatch = -1; for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); if (strcmp(basename($stat['name']), $filename) === 0) { $directoryName = dirname($stat['name']); if ($directoryName == '.') { //if composer.json is in root directory //it has to be the one to use. return $i; } if (strpos($directoryName, '\\') !== false || strpos($directoryName, '/') !== false) { //composer.json files below first directory are rejected continue; } $length = strlen($stat['name']); if ($indexOfShortestMatch === false || $length < $lengthOfShortestMatch) { //Check it's not a directory. $contents = $zip->getFromIndex($i); if ($contents !== false) { $indexOfShortestMatch = $i; $lengthOfShortestMatch = $length; } } } } return $indexOfShortestMatch; } private function getComposerInformation(\SplFileInfo $file) { $zip = new \ZipArchive(); $zip->open($file->getPathname()); if (0 == $zip->numFiles) { return false; } $foundFileIndex = $this->locateFile($zip, 'composer.json'); if (false === $foundFileIndex) { return false; } $configurationFileName = $zip->getNameIndex($foundFileIndex); $composerFile = "zip://{$file->getPathname()}#$configurationFileName"; $json = file_get_contents($composerFile); $package = JsonFile::parseJson($json, $composerFile); $package['dist'] = array( 'type' => 'zip', 'url' => strtr($file->getPathname(), '\\', '/'), 'shasum' => sha1_file($file->getRealPath()), ); try { $package = $this->loader->load($package); } catch (\UnexpectedValueException $e) { throw new \UnexpectedValueException('Failed loading package in '.$file.': '.$e->getMessage(), 0, $e); } return $package; } } composer-1.6.3/src/Composer/Repository/BaseRepository.php000066400000000000000000000171611323436022200235730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\RootPackageInterface; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\Constraint; use Composer\Package\Link; /** * Common ancestor class for generic repository functionality. * * @author Niels Keurentjes */ abstract class BaseRepository implements RepositoryInterface { /** * Returns a list of links causing the requested needle packages to be installed, as an associative array with the * dependent's name as key, and an array containing in order the PackageInterface and Link describing the relationship * as values. If recursive lookup was requested a third value is returned containing an identically formed array up * to the root package. That third value will be false in case a circular recursion was detected. * * @param string|string[] $needle The package name(s) to inspect. * @param ConstraintInterface|null $constraint Optional constraint to filter by. * @param bool $invert Whether to invert matches to discover reasons for the package *NOT* to be installed. * @param bool $recurse Whether to recursively expand the requirement tree up to the root package. * @param string[] $packagesFound Used internally when recurring * @return array An associative array of arrays as described above. */ public function getDependents($needle, $constraint = null, $invert = false, $recurse = true, $packagesFound = null) { $needles = (array) $needle; $results = array(); // initialize the array with the needles before any recursion occurs if (null === $packagesFound) { $packagesFound = $needles; } // locate root package for use below $rootPackage = null; foreach ($this->getPackages() as $package) { if ($package instanceof RootPackageInterface) { $rootPackage = $package; break; } } // Loop over all currently installed packages. foreach ($this->getPackages() as $package) { $links = $package->getRequires(); // each loop needs its own "tree" as we want to show the complete dependent set of every needle // without warning all the time about finding circular deps $packagesInTree = $packagesFound; // Replacements are considered valid reasons for a package to be installed during forward resolution if (!$invert) { $links += $package->getReplaces(); } // Require-dev is only relevant for the root package if ($package instanceof RootPackageInterface) { $links += $package->getDevRequires(); } // Cross-reference all discovered links to the needles foreach ($links as $link) { foreach ($needles as $needle) { if ($link->getTarget() === $needle) { if ($constraint === null || ($link->getConstraint()->matches($constraint) === !$invert)) { // already displayed this node's dependencies, cutting short if (in_array($link->getSource(), $packagesInTree)) { $results[$link->getSource()] = array($package, $link, false); continue; } $packagesInTree[] = $link->getSource(); $dependents = $recurse ? $this->getDependents($link->getSource(), null, false, true, $packagesInTree) : array(); $results[$link->getSource()] = array($package, $link, $dependents); } } } } // When inverting, we need to check for conflicts of the needles against installed packages if ($invert && in_array($package->getName(), $needles)) { foreach ($package->getConflicts() as $link) { foreach ($this->findPackages($link->getTarget()) as $pkg) { $version = new Constraint('=', $pkg->getVersion()); if ($link->getConstraint()->matches($version) === $invert) { $results[] = array($package, $link, false); } } } } // When inverting, we need to check for conflicts of the needles' requirements against installed packages if ($invert && $constraint && in_array($package->getName(), $needles) && $constraint->matches(new Constraint('=', $package->getVersion()))) { foreach ($package->getRequires() as $link) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) { if ($this->findPackage($link->getTarget(), $link->getConstraint())) { continue; } $platformPkg = $this->findPackage($link->getTarget(), '*'); $description = $platformPkg ? 'but '.$platformPkg->getPrettyVersion().' is installed' : 'but it is missing'; $results[] = array($package, new Link($package->getName(), $link->getTarget(), null, 'requires', $link->getPrettyConstraint().' '.$description), false); continue; } foreach ($this->getPackages() as $pkg) { if (!in_array($link->getTarget(), $pkg->getNames())) { continue; } $version = new Constraint('=', $pkg->getVersion()); if (!$link->getConstraint()->matches($version)) { // if we have a root package (we should but can not guarantee..) we show // the root requires as well to perhaps allow to find an issue there if ($rootPackage) { foreach (array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires()) as $rootReq) { if (in_array($rootReq->getTarget(), $pkg->getNames()) && !$rootReq->getConstraint()->matches($link->getConstraint())) { $results[] = array($package, $link, false); $results[] = array($rootPackage, $rootReq, false); continue 3; } } $results[] = array($package, $link, false); $results[] = array($rootPackage, new Link($rootPackage->getName(), $link->getTarget(), null, 'does not require', 'but ' . $pkg->getPrettyVersion() . ' is installed'), false); } else { // no root so let's just print whatever we found $results[] = array($package, $link, false); } } continue 2; } } } } ksort($results); return $results; } } composer-1.6.3/src/Composer/Repository/ComposerRepository.php000066400000000000000000000762071323436022200245160ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\Loader\ArrayLoader; use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Package\Version\VersionParser; use Composer\DependencyResolver\Pool; use Composer\Json\JsonFile; use Composer\Cache; use Composer\Config; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Util\RemoteFilesystem; use Composer\Plugin\PluginEvents; use Composer\Plugin\PreFileDownloadEvent; use Composer\EventDispatcher\EventDispatcher; use Composer\Downloader\TransportException; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\Constraint; /** * @author Jordi Boggiano */ class ComposerRepository extends ArrayRepository implements ConfigurableRepositoryInterface { protected $config; protected $repoConfig; protected $options; protected $url; protected $baseUrl; protected $io; protected $rfs; protected $cache; protected $notifyUrl; protected $searchUrl; protected $hasProviders = false; protected $providersUrl; protected $lazyProvidersUrl; protected $providerListing; protected $providers = array(); protected $providersByUid = array(); protected $loader; protected $rootAliases; protected $allowSslDowngrade = false; protected $eventDispatcher; protected $sourceMirrors; protected $distMirrors; private $degradedMode = false; private $rootData; private $hasPartialPackages; private $partialPackagesByName; public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, RemoteFilesystem $rfs = null) { parent::__construct(); if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) { // assume http as the default protocol $repoConfig['url'] = 'http://'.$repoConfig['url']; } $repoConfig['url'] = rtrim($repoConfig['url'], '/'); if ('https?' === substr($repoConfig['url'], 0, 6)) { $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6); } $urlBits = parse_url($repoConfig['url']); if ($urlBits === false || empty($urlBits['scheme'])) { throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']); } if (!isset($repoConfig['options'])) { $repoConfig['options'] = array(); } if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) { $this->allowSslDowngrade = true; } $this->config = $config; $this->options = $repoConfig['options']; $this->url = $repoConfig['url']; $this->baseUrl = rtrim(preg_replace('{(?:/[^/\\\\]+\.json)?(?:[?#].*)?$}', '', $this->url), '/'); $this->io = $io; $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$'); $this->loader = new ArrayLoader(); if ($rfs && $this->options) { $rfs = clone $rfs; $rfs->setOptions($this->options); } $this->rfs = $rfs ?: Factory::createRemoteFilesystem($this->io, $this->config, $this->options); $this->eventDispatcher = $eventDispatcher; $this->repoConfig = $repoConfig; } public function getRepoConfig() { return $this->repoConfig; } public function setRootAliases(array $rootAliases) { $this->rootAliases = $rootAliases; } /** * {@inheritDoc} */ public function findPackage($name, $constraint) { if (!$this->hasProviders()) { return parent::findPackage($name, $constraint); } $name = strtolower($name); if (!$constraint instanceof ConstraintInterface) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($constraint); } foreach ($this->getProviderNames() as $providerName) { if ($name === $providerName) { $packages = $this->whatProvides(new Pool('dev'), $providerName); foreach ($packages as $package) { if ($name === $package->getName()) { $pkgConstraint = new Constraint('==', $package->getVersion()); if ($constraint->matches($pkgConstraint)) { return $package; } } } break; } } } /** * {@inheritDoc} */ public function findPackages($name, $constraint = null) { if (!$this->hasProviders()) { return parent::findPackages($name, $constraint); } // normalize name $name = strtolower($name); if (null !== $constraint && !$constraint instanceof ConstraintInterface) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($constraint); } $packages = array(); foreach ($this->getProviderNames() as $providerName) { if ($name === $providerName) { $candidates = $this->whatProvides(new Pool('dev'), $providerName); foreach ($candidates as $package) { if ($name === $package->getName()) { $pkgConstraint = new Constraint('==', $package->getVersion()); if (null === $constraint || $constraint->matches($pkgConstraint)) { $packages[] = $package; } } } break; } } return $packages; } public function getPackages() { if ($this->hasProviders()) { throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.'); } return parent::getPackages(); } /** * {@inheritDoc} */ public function search($query, $mode = 0, $type = null) { $this->loadRootServerFile(); if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) { $url = str_replace(array('%query%', '%type%'), array($query, $type), $this->searchUrl); $hostname = parse_url($url, PHP_URL_HOST) ?: $url; $json = $this->rfs->getContents($hostname, $url, false); $results = JsonFile::parseJson($json, $url); return $results['results']; } if ($this->hasProviders()) { $results = array(); $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i'; foreach ($this->getProviderNames() as $name) { if (preg_match($regex, $name)) { $results[] = array('name' => $name); } } return $results; } return parent::search($query, $mode); } public function getProviderNames() { $this->loadRootServerFile(); if (null === $this->providerListing) { $this->loadProviderListings($this->loadRootServerFile()); } if ($this->lazyProvidersUrl) { // Can not determine list of provided packages for lazy repositories return array(); } if ($this->providersUrl) { return array_keys($this->providerListing); } return array(); } protected function configurePackageTransportOptions(PackageInterface $package) { foreach ($package->getDistUrls() as $url) { if (strpos($url, $this->baseUrl) === 0) { $package->setTransportOptions($this->options); return; } } } public function hasProviders() { $this->loadRootServerFile(); return $this->hasProviders; } public function resetPackageIds() { foreach ($this->providersByUid as $package) { if ($package instanceof AliasPackage) { $package->getAliasOf()->setId(-1); } $package->setId(-1); } } /** * @param Pool $pool * @param string $name package name * @param bool $bypassFilters If set to true, this bypasses the stability filtering, and forces a recompute without cache * @return array|mixed */ public function whatProvides(Pool $pool, $name, $bypassFilters = false) { if (isset($this->providers[$name]) && !$bypassFilters) { return $this->providers[$name]; } if ($this->hasPartialPackages && null === $this->partialPackagesByName) { $this->initializePartialPackages(); } if (!$this->hasPartialPackages || !isset($this->partialPackagesByName[$name])) { // skip platform packages, root package and composer-plugin-api if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name || 'composer-plugin-api' === $name) { return array(); } if (null === $this->providerListing) { $this->loadProviderListings($this->loadRootServerFile()); } $useLastModifiedCheck = false; if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) { $hash = null; $url = str_replace('%package%', $name, $this->lazyProvidersUrl); $cacheKey = 'provider-'.strtr($name, '/', '$').'.json'; $useLastModifiedCheck = true; } elseif ($this->providersUrl) { // package does not exist in this repo if (!isset($this->providerListing[$name])) { return array(); } $hash = $this->providerListing[$name]['sha256']; $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl); $cacheKey = 'provider-'.strtr($name, '/', '$').'.json'; } else { return array(); } $packages = null; if ($cacheKey) { if (!$useLastModifiedCheck && $hash && $this->cache->sha256($cacheKey) === $hash) { $packages = json_decode($this->cache->read($cacheKey), true); } elseif ($useLastModifiedCheck) { if ($contents = $this->cache->read($cacheKey)) { $contents = json_decode($contents, true); if (isset($contents['last-modified'])) { $response = $this->fetchFileIfLastModified($url, $cacheKey, $contents['last-modified']); if (true === $response) { $packages = $contents; } elseif ($response) { $packages = $response; } } } } } if (!$packages) { try { $packages = $this->fetchFile($url, $cacheKey, $hash, $useLastModifiedCheck); } catch (TransportException $e) { // 404s are acceptable for lazy provider repos if ($e->getStatusCode() === 404 && $this->lazyProvidersUrl) { $packages = array('packages' => array()); } else { throw $e; } } } $loadingPartialPackage = false; } else { $packages = array('packages' => array('versions' => $this->partialPackagesByName[$name])); $loadingPartialPackage = true; } $this->providers[$name] = array(); foreach ($packages['packages'] as $versions) { foreach ($versions as $version) { if (!$loadingPartialPackage && $this->hasPartialPackages && isset($this->partialPackagesByName[$version['name']])) { continue; } // avoid loading the same objects twice if (isset($this->providersByUid[$version['uid']])) { // skip if already assigned if (!isset($this->providers[$name][$version['uid']])) { // expand alias in two packages if ($this->providersByUid[$version['uid']] instanceof AliasPackage) { $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf(); $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']]; } else { $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]; } // check for root aliases if (isset($this->providersByUid[$version['uid'].'-root'])) { $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root']; } } } else { if (!$bypassFilters && !$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) { continue; } // load acceptable packages in the providers $package = $this->createPackage($version, 'Composer\Package\CompletePackage'); $package->setRepository($this); if ($package instanceof AliasPackage) { $aliased = $package->getAliasOf(); $aliased->setRepository($this); $this->providers[$name][$version['uid']] = $aliased; $this->providers[$name][$version['uid'].'-alias'] = $package; // override provider with its alias so it can be expanded in the if block above $this->providersByUid[$version['uid']] = $package; } else { $this->providers[$name][$version['uid']] = $package; $this->providersByUid[$version['uid']] = $package; } // handle root package aliases unset($rootAliasData); if (isset($this->rootAliases[$package->getName()][$package->getVersion()])) { $rootAliasData = $this->rootAliases[$package->getName()][$package->getVersion()]; } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()])) { $rootAliasData = $this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()]; } if (isset($rootAliasData)) { $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']); $alias->setRepository($this); $this->providers[$name][$version['uid'].'-root'] = $alias; $this->providersByUid[$version['uid'].'-root'] = $alias; } } } } $result = $this->providers[$name]; // clean up the cache because otherwise using this puts the repo in an inconsistent state with a polluted unfiltered cache // which is likely not an issue but might cause hard to track behaviors depending on how the repo is used if ($bypassFilters) { foreach ($this->providers[$name] as $uid => $provider) { unset($this->providersByUid[$uid]); } unset($this->providers[$name]); } return $result; } /** * {@inheritDoc} */ protected function initialize() { parent::initialize(); $repoData = $this->loadDataFromServer(); foreach ($repoData as $package) { $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage')); } } /** * Adds a new package to the repository * * @param PackageInterface $package */ public function addPackage(PackageInterface $package) { parent::addPackage($package); $this->configurePackageTransportOptions($package); } protected function loadRootServerFile() { if (null !== $this->rootData) { return $this->rootData; } if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) { throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url); } $jsonUrlParts = parse_url($this->url); if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '.json')) { $jsonUrl = $this->url; } else { $jsonUrl = $this->url . '/packages.json'; } $data = $this->fetchFile($jsonUrl, 'packages.json'); if (!empty($data['notify-batch'])) { $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']); } elseif (!empty($data['notify'])) { $this->notifyUrl = $this->canonicalizeUrl($data['notify']); } if (!empty($data['search'])) { $this->searchUrl = $this->canonicalizeUrl($data['search']); } if (!empty($data['mirrors'])) { foreach ($data['mirrors'] as $mirror) { if (!empty($mirror['git-url'])) { $this->sourceMirrors['git'][] = array('url' => $mirror['git-url'], 'preferred' => !empty($mirror['preferred'])); } if (!empty($mirror['hg-url'])) { $this->sourceMirrors['hg'][] = array('url' => $mirror['hg-url'], 'preferred' => !empty($mirror['preferred'])); } if (!empty($mirror['dist-url'])) { $this->distMirrors[] = array( 'url' => $this->canonicalizeUrl($mirror['dist-url']), 'preferred' => !empty($mirror['preferred']), ); } } } if (!empty($data['providers-lazy-url'])) { $this->lazyProvidersUrl = $this->canonicalizeUrl($data['providers-lazy-url']); $this->hasProviders = true; $this->hasPartialPackages = !empty($data['packages']) && is_array($data['packages']); } if ($this->allowSslDowngrade) { $this->url = str_replace('https://', 'http://', $this->url); $this->baseUrl = str_replace('https://', 'http://', $this->baseUrl); } if (!empty($data['providers-url'])) { $this->providersUrl = $this->canonicalizeUrl($data['providers-url']); $this->hasProviders = true; } if (!empty($data['providers']) || !empty($data['providers-includes'])) { $this->hasProviders = true; } // force values for packagist if (preg_match('{^https?://packagist.org/?$}i', $this->url) && !empty($this->repoConfig['force-lazy-providers'])) { $this->url = 'https://packagist.org'; $this->baseUrl = 'https://packagist.org'; $this->lazyProvidersUrl = $this->canonicalizeUrl('https://packagist.org/p/%package%.json'); $this->providersUrl = null; } elseif (!empty($this->repoConfig['force-lazy-providers'])) { $this->lazyProvidersUrl = $this->canonicalizeUrl('/p/%package%.json'); $this->providersUrl = null; } return $this->rootData = $data; } protected function canonicalizeUrl($url) { if ('/' === $url[0]) { return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url); } return $url; } protected function loadDataFromServer() { $data = $this->loadRootServerFile(); return $this->loadIncludes($data); } protected function loadProviderListings($data) { if (isset($data['providers'])) { if (!is_array($this->providerListing)) { $this->providerListing = array(); } $this->providerListing = array_merge($this->providerListing, $data['providers']); } if ($this->providersUrl && isset($data['provider-includes'])) { $includes = $data['provider-includes']; foreach ($includes as $include => $metadata) { $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include); $cacheKey = str_replace(array('%hash%','$'), '', $include); if ($this->cache->sha256($cacheKey) === $metadata['sha256']) { $includedData = json_decode($this->cache->read($cacheKey), true); } else { $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']); } $this->loadProviderListings($includedData); } } } protected function loadIncludes($data) { $packages = array(); // legacy repo handling if (!isset($data['packages']) && !isset($data['includes'])) { foreach ($data as $pkg) { foreach ($pkg['versions'] as $metadata) { $packages[] = $metadata; } } return $packages; } if (isset($data['packages'])) { foreach ($data['packages'] as $package => $versions) { foreach ($versions as $version => $metadata) { $packages[] = $metadata; } } } if (isset($data['includes'])) { foreach ($data['includes'] as $include => $metadata) { if ($this->cache->sha1($include) === $metadata['sha1']) { $includedData = json_decode($this->cache->read($include), true); } else { $includedData = $this->fetchFile($include); } $packages = array_merge($packages, $this->loadIncludes($includedData)); } } return $packages; } protected function createPackage(array $data, $class = 'Composer\Package\CompletePackage') { try { if (!isset($data['notification-url'])) { $data['notification-url'] = $this->notifyUrl; } $package = $this->loader->load($data, $class); if (isset($this->sourceMirrors[$package->getSourceType()])) { $package->setSourceMirrors($this->sourceMirrors[$package->getSourceType()]); } $package->setDistMirrors($this->distMirrors); $this->configurePackageTransportOptions($package); return $package; } catch (\Exception $e) { throw new \RuntimeException('Could not load package '.(isset($data['name']) ? $data['name'] : json_encode($data)).' in '.$this->url.': ['.get_class($e).'] '.$e->getMessage(), 0, $e); } } protected function fetchFile($filename, $cacheKey = null, $sha256 = null, $storeLastModifiedTime = false) { if (null === $cacheKey) { $cacheKey = $filename; $filename = $this->baseUrl.'/'.$filename; } // url-encode $ signs in URLs as bad proxies choke on them if (($pos = strpos($filename, '$')) && preg_match('{^https?://.*}i', $filename)) { $filename = substr($filename, 0, $pos) . '%24' . substr($filename, $pos + 1); } $retries = 3; while ($retries--) { try { $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename); if ($this->eventDispatcher) { $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent); } $hostname = parse_url($filename, PHP_URL_HOST) ?: $filename; $rfs = $preFileDownloadEvent->getRemoteFilesystem(); $json = $rfs->getContents($hostname, $filename, false); if ($sha256 && $sha256 !== hash('sha256', $json)) { // undo downgrade before trying again if http seems to be hijacked or modifying content somehow if ($this->allowSslDowngrade) { $this->url = str_replace('http://', 'https://', $this->url); $this->baseUrl = str_replace('http://', 'https://', $this->baseUrl); $filename = str_replace('http://', 'https://', $filename); } if ($retries) { usleep(100000); continue; } // TODO use scarier wording once we know for sure it doesn't do false positives anymore throw new RepositorySecurityException('The contents of '.$filename.' do not match its signature. This could indicate a man-in-the-middle attack or e.g. antivirus software corrupting files. Try running composer again and report this if you think it is a mistake.'); } $data = JsonFile::parseJson($json, $filename); if (!empty($data['warning'])) { $this->io->writeError('Warning from '.$this->url.': '.$data['warning'].''); } if (!empty($data['info'])) { $this->io->writeError('Info from '.$this->url.': '.$data['info'].''); } if ($cacheKey) { if ($storeLastModifiedTime) { $lastModifiedDate = $rfs->findHeaderValue($rfs->getLastHeaders(), 'last-modified'); if ($lastModifiedDate) { $data['last-modified'] = $lastModifiedDate; $json = json_encode($data); } } $this->cache->write($cacheKey, $json); } break; } catch (\Exception $e) { if ($e instanceof TransportException && $e->getStatusCode() === 404) { throw $e; } if ($retries) { usleep(100000); continue; } if ($e instanceof RepositorySecurityException) { throw $e; } if ($cacheKey && ($contents = $this->cache->read($cacheKey))) { if (!$this->degradedMode) { $this->io->writeError(''.$e->getMessage().''); $this->io->writeError(''.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date'); } $this->degradedMode = true; $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey); break; } throw $e; } } return $data; } protected function fetchFileIfLastModified($filename, $cacheKey, $lastModifiedTime) { $retries = 3; while ($retries--) { try { $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename); if ($this->eventDispatcher) { $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent); } $hostname = parse_url($filename, PHP_URL_HOST) ?: $filename; $rfs = $preFileDownloadEvent->getRemoteFilesystem(); $options = array('http' => array('header' => array('If-Modified-Since: '.$lastModifiedTime))); $json = $rfs->getContents($hostname, $filename, false, $options); if ($json === '' && $rfs->findStatusCode($rfs->getLastHeaders()) === 304) { return true; } $data = JsonFile::parseJson($json, $filename); if (!empty($data['warning'])) { $this->io->writeError('Warning from '.$this->url.': '.$data['warning'].''); } if (!empty($data['info'])) { $this->io->writeError('Info from '.$this->url.': '.$data['info'].''); } $lastModifiedDate = $rfs->findHeaderValue($rfs->getLastHeaders(), 'last-modified'); if ($lastModifiedDate) { $data['last-modified'] = $lastModifiedDate; $json = json_encode($data); } $this->cache->write($cacheKey, $json); return $data; } catch (\Exception $e) { if ($e instanceof TransportException && $e->getStatusCode() === 404) { throw $e; } if ($retries) { usleep(100000); continue; } if (!$this->degradedMode) { $this->io->writeError(''.$e->getMessage().''); $this->io->writeError(''.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date'); } $this->degradedMode = true; return true; } } } /** * This initializes the packages key of a partial packages.json that contain some packages inlined + a providers-lazy-url * * This should only be called once */ private function initializePartialPackages() { $rootData = $this->loadRootServerFile(); $this->partialPackagesByName = array(); foreach ($rootData['packages'] as $package => $versions) { $package = strtolower($package); foreach ($versions as $version) { $this->partialPackagesByName[$package][] = $version; if (!empty($version['provide']) && is_array($version['provide'])) { foreach ($version['provide'] as $provided => $providedVersion) { $this->partialPackagesByName[strtolower($provided)][] = $version; } } if (!empty($version['replace']) && is_array($version['replace'])) { foreach ($version['replace'] as $provided => $providedVersion) { $this->partialPackagesByName[strtolower($provided)][] = $version; } } } } // wipe rootData as it is fully consumed at this point and this saves some memory $this->rootData = true; } } composer-1.6.3/src/Composer/Repository/CompositeRepository.php000066400000000000000000000075271323436022200246700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\PackageInterface; /** * Composite repository. * * @author Beau Simensen */ class CompositeRepository extends BaseRepository { /** * List of repositories * @var array */ private $repositories; /** * Constructor * @param array $repositories */ public function __construct(array $repositories) { $this->repositories = array(); foreach ($repositories as $repo) { $this->addRepository($repo); } } /** * Returns all the wrapped repositories * * @return array */ public function getRepositories() { return $this->repositories; } /** * {@inheritdoc} */ public function hasPackage(PackageInterface $package) { foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ if ($repository->hasPackage($package)) { return true; } } return false; } /** * {@inheritdoc} */ public function findPackage($name, $constraint) { foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $package = $repository->findPackage($name, $constraint); if (null !== $package) { return $package; } } return null; } /** * {@inheritdoc} */ public function findPackages($name, $constraint = null) { $packages = array(); foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $packages[] = $repository->findPackages($name, $constraint); } return $packages ? call_user_func_array('array_merge', $packages) : array(); } /** * {@inheritdoc} */ public function search($query, $mode = 0, $type = null) { $matches = array(); foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $matches[] = $repository->search($query, $mode, $type); } return $matches ? call_user_func_array('array_merge', $matches) : array(); } /** * {@inheritdoc} */ public function getPackages() { $packages = array(); foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $packages[] = $repository->getPackages(); } return $packages ? call_user_func_array('array_merge', $packages) : array(); } /** * {@inheritdoc} */ public function removePackage(PackageInterface $package) { foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $repository->removePackage($package); } } /** * {@inheritdoc} */ public function count() { $total = 0; foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ $total += $repository->count(); } return $total; } /** * Add a repository. * @param RepositoryInterface $repository */ public function addRepository(RepositoryInterface $repository) { if ($repository instanceof self) { foreach ($repository->getRepositories() as $repo) { $this->addRepository($repo); } } else { $this->repositories[] = $repository; } } } composer-1.6.3/src/Composer/Repository/ConfigurableRepositoryInterface.php000066400000000000000000000007361323436022200271420ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Configurable repository interface. * * @author Lukas Homza */ interface ConfigurableRepositoryInterface { public function getRepoConfig(); } composer-1.6.3/src/Composer/Repository/FilesystemRepository.php000066400000000000000000000043501323436022200250410ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Json\JsonFile; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Dumper\ArrayDumper; /** * Filesystem repository. * * @author Konstantin Kudryashov * @author Jordi Boggiano */ class FilesystemRepository extends WritableArrayRepository { private $file; /** * Initializes filesystem repository. * * @param JsonFile $repositoryFile repository json file */ public function __construct(JsonFile $repositoryFile) { parent::__construct(); $this->file = $repositoryFile; } /** * Initializes repository (reads file, or remote address). */ protected function initialize() { parent::initialize(); if (!$this->file->exists()) { return; } try { $packages = $this->file->read(); if (!is_array($packages)) { throw new \UnexpectedValueException('Could not parse package list from the repository'); } } catch (\Exception $e) { throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage()); } $loader = new ArrayLoader(null, true); foreach ($packages as $packageData) { $package = $loader->load($packageData); $this->addPackage($package); } } public function reload() { $this->packages = null; $this->initialize(); } /** * Writes writable repository. */ public function write() { $data = array(); $dumper = new ArrayDumper(); foreach ($this->getCanonicalPackages() as $package) { $data[] = $dumper->dump($package); } usort($data, function ($a, $b) { return strcmp($a['name'], $b['name']); }); $this->file->write($data); } } composer-1.6.3/src/Composer/Repository/InstalledArrayRepository.php000066400000000000000000000011101323436022200256220ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Installed array repository. * * This is used for serving the RootPackage inside an in-memory InstalledRepository * * @author Jordi Boggiano */ class InstalledArrayRepository extends WritableArrayRepository implements InstalledRepositoryInterface { } composer-1.6.3/src/Composer/Repository/InstalledFilesystemRepository.php000066400000000000000000000007701323436022200267030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Installed filesystem repository. * * @author Jordi Boggiano */ class InstalledFilesystemRepository extends FilesystemRepository implements InstalledRepositoryInterface { } composer-1.6.3/src/Composer/Repository/InstalledRepositoryInterface.php000066400000000000000000000011031323436022200264460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Installable repository interface. * * Just used to tag installed repositories so the base classes can act differently on Alias packages * * @author Jordi Boggiano */ interface InstalledRepositoryInterface extends WritableRepositoryInterface { } composer-1.6.3/src/Composer/Repository/InvalidRepositoryException.php000066400000000000000000000007371323436022200261670ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Exception thrown when a package repository is utterly broken * * @author Jordi Boggiano */ class InvalidRepositoryException extends \Exception { } composer-1.6.3/src/Composer/Repository/PackageRepository.php000066400000000000000000000031341323436022200242470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Loader\ValidatingArrayLoader; /** * Package repository. * * @author Jordi Boggiano */ class PackageRepository extends ArrayRepository { private $config; /** * Initializes filesystem repository. * * @param array $config package definition */ public function __construct(array $config) { parent::__construct(); $this->config = $config['package']; // make sure we have an array of package definitions if (!is_numeric(key($this->config))) { $this->config = array($this->config); } } /** * Initializes repository (reads file, or remote address). */ protected function initialize() { parent::initialize(); $loader = new ValidatingArrayLoader(new ArrayLoader(null, true), false); foreach ($this->config as $package) { try { $package = $loader->load($package); } catch (\Exception $e) { throw new InvalidRepositoryException('A repository of type "package" contains an invalid package definition: '.$e->getMessage()."\n\nInvalid package definition:\n".json_encode($package)); } $this->addPackage($package); } } } composer-1.6.3/src/Composer/Repository/PathRepository.php000066400000000000000000000122221323436022200236060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Config; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; /** * This repository allows installing local packages that are not necessarily under their own VCS. * * The local packages will be symlinked when possible, else they will be copied. * * @code * "require": { * "/": "*" * }, * "repositories": [ * { * "type": "path", * "url": "../../relative/path/to/package/" * }, * { * "type": "path", * "url": "/absolute/path/to/package/" * }, * { * "type": "path", * "url": "/absolute/path/to/several/packages/*" * }, * { * "type": "path", * "url": "../../relative/path/to/package/", * "options": { * "symlink": false * } * }, * ] * @endcode * * @author Samuel Roze * @author Johann Reinke */ class PathRepository extends ArrayRepository implements ConfigurableRepositoryInterface { /** * @var ArrayLoader */ private $loader; /** * @var VersionGuesser */ private $versionGuesser; /** * @var string */ private $url; /** * @var array */ private $repoConfig; /** * @var ProcessExecutor */ private $process; /** * @var array */ private $options; /** * Initializes path repository. * * @param array $repoConfig * @param IOInterface $io * @param Config $config */ public function __construct(array $repoConfig, IOInterface $io, Config $config) { if (!isset($repoConfig['url'])) { throw new \RuntimeException('You must specify the `url` configuration for the path repository'); } $this->loader = new ArrayLoader(null, true); $this->url = Platform::expandPath($repoConfig['url']); $this->process = new ProcessExecutor($io); $this->versionGuesser = new VersionGuesser($config, $this->process, new VersionParser()); $this->repoConfig = $repoConfig; $this->options = isset($repoConfig['options']) ? $repoConfig['options'] : array(); parent::__construct(); } public function getRepoConfig() { return $this->repoConfig; } /** * Initializes path repository. * * This method will basically read the folder and add the found package. */ protected function initialize() { parent::initialize(); foreach ($this->getUrlMatches() as $url) { $path = realpath($url) . DIRECTORY_SEPARATOR; $composerFilePath = $path.'composer.json'; if (!file_exists($composerFilePath)) { continue; } $json = file_get_contents($composerFilePath); $package = JsonFile::parseJson($json, $composerFilePath); $package['dist'] = array( 'type' => 'path', 'url' => $url, 'reference' => sha1($json . serialize($this->options)), ); $package['transport-options'] = $this->options; // carry over the root package version if this path repo is in the same git repository as root package if (!isset($package['version']) && ($rootVersion = getenv('COMPOSER_ROOT_VERSION'))) { if ( 0 === $this->process->execute('git rev-parse HEAD', $ref1, $path) && 0 === $this->process->execute('git rev-parse HEAD', $ref2) && $ref1 === $ref2 ) { $package['version'] = $rootVersion; } } if (!isset($package['version'])) { $versionData = $this->versionGuesser->guessVersion($package, $path); $package['version'] = $versionData['version'] ?: 'dev-master'; } $output = ''; if (is_dir($path . DIRECTORY_SEPARATOR . '.git') && 0 === $this->process->execute('git log -n1 --pretty=%H', $output, $path)) { $package['dist']['reference'] = trim($output); } $package = $this->loader->load($package); $this->addPackage($package); } } /** * Get a list of all (possibly relative) path names matching given url (supports globbing). * * @return string[] */ private function getUrlMatches() { // Ensure environment-specific path separators are normalized to URL separators return array_map(function ($val) { return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/'); }, glob($this->url, GLOB_MARK | GLOB_ONLYDIR)); } } composer-1.6.3/src/Composer/Repository/Pear/000077500000000000000000000000001323436022200207715ustar00rootroot00000000000000composer-1.6.3/src/Composer/Repository/Pear/BaseChannelReader.php000066400000000000000000000047371323436022200250030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; use Composer\Util\RemoteFilesystem; /** * Base PEAR Channel reader. * * Provides xml namespaces and red * * @author Alexey Prilipko */ abstract class BaseChannelReader { /** * PEAR REST Interface namespaces */ const CHANNEL_NS = 'http://pear.php.net/channel-1.0'; const ALL_CATEGORIES_NS = 'http://pear.php.net/dtd/rest.allcategories'; const CATEGORY_PACKAGES_INFO_NS = 'http://pear.php.net/dtd/rest.categorypackageinfo'; const ALL_PACKAGES_NS = 'http://pear.php.net/dtd/rest.allpackages'; const ALL_RELEASES_NS = 'http://pear.php.net/dtd/rest.allreleases'; const PACKAGE_INFO_NS = 'http://pear.php.net/dtd/rest.package'; /** @var RemoteFilesystem */ private $rfs; protected function __construct(RemoteFilesystem $rfs) { $this->rfs = $rfs; } /** * Read content from remote filesystem. * * @param $origin string server * @param $path string relative path to content * @throws \UnexpectedValueException * @return \SimpleXMLElement */ protected function requestContent($origin, $path) { $url = rtrim($origin, '/') . '/' . ltrim($path, '/'); $content = $this->rfs->getContents($origin, $url, false); if (!$content) { throw new \UnexpectedValueException('The PEAR channel at ' . $url . ' did not respond.'); } return str_replace('http://pear.php.net/rest/', 'https://pear.php.net/rest/', $content); } /** * Read xml content from remote filesystem * * @param $origin string server * @param $path string relative path to content * @throws \UnexpectedValueException * @return \SimpleXMLElement */ protected function requestXml($origin, $path) { // http://components.ez.no/p/packages.xml is malformed. to read it we must ignore parsing errors. $xml = simplexml_load_string($this->requestContent($origin, $path), "SimpleXMLElement", LIBXML_NOERROR); if (false === $xml) { throw new \UnexpectedValueException(sprintf('The PEAR channel at ' . $origin . ' is broken. (Invalid XML at file `%s`)', $path)); } return $xml; } } composer-1.6.3/src/Composer/Repository/Pear/ChannelInfo.php000066400000000000000000000023021323436022200236630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * PEAR channel info * * @author Alexey Prilipko */ class ChannelInfo { private $name; private $alias; private $packages; /** * @param string $name * @param string $alias * @param PackageInfo[] $packages */ public function __construct($name, $alias, array $packages) { $this->name = $name; $this->alias = $alias; $this->packages = $packages; } /** * Name of the channel * * @return string */ public function getName() { return $this->name; } /** * Alias of the channel * * @return string */ public function getAlias() { return $this->alias; } /** * List of channel packages * * @return PackageInfo[] */ public function getPackages() { return $this->packages; } } composer-1.6.3/src/Composer/Repository/Pear/ChannelReader.php000066400000000000000000000062201323436022200241750ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; use Composer\Util\RemoteFilesystem; /** * PEAR Channel package reader. * * Reads channel packages info from and builds Package's * * @author Alexey Prilipko */ class ChannelReader extends BaseChannelReader { /** @var array of ('xpath test' => 'rest implementation') */ private $readerMap; public function __construct(RemoteFilesystem $rfs) { parent::__construct($rfs); $rest10reader = new ChannelRest10Reader($rfs); $rest11reader = new ChannelRest11Reader($rfs); $this->readerMap = array( 'REST1.3' => $rest11reader, 'REST1.2' => $rest11reader, 'REST1.1' => $rest11reader, 'REST1.0' => $rest10reader, ); } /** * Reads PEAR channel through REST interface and builds list of packages * * @param $url string PEAR Channel url * @throws \UnexpectedValueException * @return ChannelInfo */ public function read($url) { $xml = $this->requestXml($url, "/channel.xml"); $channelName = (string) $xml->name; $channelAlias = (string) $xml->suggestedalias; $supportedVersions = array_keys($this->readerMap); $selectedRestVersion = $this->selectRestVersion($xml, $supportedVersions); if (!$selectedRestVersion) { throw new \UnexpectedValueException(sprintf('PEAR repository %s does not supports any of %s protocols.', $url, implode(', ', $supportedVersions))); } $reader = $this->readerMap[$selectedRestVersion['version']]; $packageDefinitions = $reader->read($selectedRestVersion['baseUrl']); return new ChannelInfo($channelName, $channelAlias, $packageDefinitions); } /** * Reads channel supported REST interfaces and selects one of them * * @param $channelXml \SimpleXMLElement * @param $supportedVersions string[] supported PEAR REST protocols * @return array|null hash with selected version and baseUrl */ private function selectRestVersion($channelXml, $supportedVersions) { $channelXml->registerXPathNamespace('ns', self::CHANNEL_NS); foreach ($supportedVersions as $version) { $xpathTest = "ns:servers/ns:*/ns:rest/ns:baseurl[@type='{$version}']"; $testResult = $channelXml->xpath($xpathTest); foreach ($testResult as $result) { // Choose first https:// option. $result = (string) $result; if (preg_match('{^https://}i', $result)) { return array('version' => $version, 'baseUrl' => $result); } } // Fallback to non-https if it does not exist. if (count($testResult) > 0) { return array('version' => $version, 'baseUrl' => (string) $testResult[0]); } } return null; } } composer-1.6.3/src/Composer/Repository/Pear/ChannelRest10Reader.php000066400000000000000000000113571323436022200252030ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; use Composer\Downloader\TransportException; /** * Read PEAR packages using REST 1.0 interface * * At version 1.0 package descriptions read from: * {baseUrl}/p/packages.xml * {baseUrl}/p/{package}/info.xml * {baseUrl}/p/{package}/allreleases.xml * {baseUrl}/p/{package}/deps.{version}.txt * * @author Alexey Prilipko */ class ChannelRest10Reader extends BaseChannelReader { private $dependencyReader; public function __construct($rfs) { parent::__construct($rfs); $this->dependencyReader = new PackageDependencyParser(); } /** * Reads package descriptions using PEAR Rest 1.0 interface * * @param $baseUrl string base Url interface * * @return PackageInfo[] */ public function read($baseUrl) { return $this->readPackages($baseUrl); } /** * Read list of packages from * {baseUrl}/p/packages.xml * * @param $baseUrl string * @return PackageInfo[] */ private function readPackages($baseUrl) { $result = array(); $xmlPath = '/p/packages.xml'; $xml = $this->requestXml($baseUrl, $xmlPath); $xml->registerXPathNamespace('ns', self::ALL_PACKAGES_NS); foreach ($xml->xpath('ns:p') as $node) { $packageName = (string) $node; $packageInfo = $this->readPackage($baseUrl, $packageName); $result[] = $packageInfo; } return $result; } /** * Read package info from * {baseUrl}/p/{package}/info.xml * * @param $baseUrl string * @param $packageName string * @return PackageInfo */ private function readPackage($baseUrl, $packageName) { $xmlPath = '/p/' . strtolower($packageName) . '/info.xml'; $xml = $this->requestXml($baseUrl, $xmlPath); $xml->registerXPathNamespace('ns', self::PACKAGE_INFO_NS); $channelName = (string) $xml->c; $packageName = (string) $xml->n; $license = (string) $xml->l; $shortDescription = (string) $xml->s; $description = (string) $xml->d; return new PackageInfo( $channelName, $packageName, $license, $shortDescription, $description, $this->readPackageReleases($baseUrl, $packageName) ); } /** * Read package releases from * {baseUrl}/p/{package}/allreleases.xml * * @param $baseUrl string * @param $packageName string * @throws \Composer\Downloader\TransportException|\Exception * @return ReleaseInfo[] hash array with keys as version numbers */ private function readPackageReleases($baseUrl, $packageName) { $result = array(); try { $xmlPath = '/r/' . strtolower($packageName) . '/allreleases.xml'; $xml = $this->requestXml($baseUrl, $xmlPath); $xml->registerXPathNamespace('ns', self::ALL_RELEASES_NS); foreach ($xml->xpath('ns:r') as $node) { $releaseVersion = (string) $node->v; $releaseStability = (string) $node->s; try { $result[$releaseVersion] = new ReleaseInfo( $releaseStability, $this->readPackageReleaseDependencies($baseUrl, $packageName, $releaseVersion) ); } catch (TransportException $exception) { if ($exception->getCode() != 404) { throw $exception; } } } } catch (TransportException $exception) { if ($exception->getCode() != 404) { throw $exception; } } return $result; } /** * Read package dependencies from * {baseUrl}/p/{package}/deps.{version}.txt * * @param $baseUrl string * @param $packageName string * @param $version string * @return DependencyInfo[] */ private function readPackageReleaseDependencies($baseUrl, $packageName, $version) { $dependencyReader = new PackageDependencyParser(); $depthPath = '/r/' . strtolower($packageName) . '/deps.' . $version . '.txt'; $content = $this->requestContent($baseUrl, $depthPath); $dependencyArray = unserialize($content); return $dependencyReader->buildDependencyInfo($dependencyArray); } } composer-1.6.3/src/Composer/Repository/Pear/ChannelRest11Reader.php000066400000000000000000000100011323436022200251650ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * Read PEAR packages using REST 1.1 interface * * At version 1.1 package descriptions read from: * {baseUrl}/c/categories.xml * {baseUrl}/c/{category}/packagesinfo.xml * * @author Alexey Prilipko */ class ChannelRest11Reader extends BaseChannelReader { private $dependencyReader; public function __construct($rfs) { parent::__construct($rfs); $this->dependencyReader = new PackageDependencyParser(); } /** * Reads package descriptions using PEAR Rest 1.1 interface * * @param $baseUrl string base Url interface * * @return PackageInfo[] */ public function read($baseUrl) { return $this->readChannelPackages($baseUrl); } /** * Read list of channel categories from * {baseUrl}/c/categories.xml * * @param $baseUrl string * @return PackageInfo[] */ private function readChannelPackages($baseUrl) { $result = array(); $xml = $this->requestXml($baseUrl, "/c/categories.xml"); $xml->registerXPathNamespace('ns', self::ALL_CATEGORIES_NS); foreach ($xml->xpath('ns:c') as $node) { $categoryName = (string) $node; $categoryPackages = $this->readCategoryPackages($baseUrl, $categoryName); $result = array_merge($result, $categoryPackages); } return $result; } /** * Read packages from * {baseUrl}/c/{category}/packagesinfo.xml * * @param $baseUrl string * @param $categoryName string * @return PackageInfo[] */ private function readCategoryPackages($baseUrl, $categoryName) { $result = array(); $categoryPath = '/c/'.urlencode($categoryName).'/packagesinfo.xml'; $xml = $this->requestXml($baseUrl, $categoryPath); $xml->registerXPathNamespace('ns', self::CATEGORY_PACKAGES_INFO_NS); foreach ($xml->xpath('ns:pi') as $node) { $packageInfo = $this->parsePackage($node); $result[] = $packageInfo; } return $result; } /** * Parses package node. * * @param $packageInfo \SimpleXMLElement xml element describing package * @return PackageInfo */ private function parsePackage($packageInfo) { $packageInfo->registerXPathNamespace('ns', self::CATEGORY_PACKAGES_INFO_NS); $channelName = (string) $packageInfo->p->c; $packageName = (string) $packageInfo->p->n; $license = (string) $packageInfo->p->l; $shortDescription = (string) $packageInfo->p->s; $description = (string) $packageInfo->p->d; $dependencies = array(); foreach ($packageInfo->xpath('ns:deps') as $node) { $dependencyVersion = (string) $node->v; $dependencyArray = unserialize((string) $node->d); $dependencyInfo = $this->dependencyReader->buildDependencyInfo($dependencyArray); $dependencies[$dependencyVersion] = $dependencyInfo; } $releases = array(); $releasesInfo = $packageInfo->xpath('ns:a/ns:r'); if ($releasesInfo) { foreach ($releasesInfo as $node) { $releaseVersion = (string) $node->v; $releaseStability = (string) $node->s; $releases[$releaseVersion] = new ReleaseInfo( $releaseStability, isset($dependencies[$releaseVersion]) ? $dependencies[$releaseVersion] : new DependencyInfo(array(), array()) ); } } return new PackageInfo( $channelName, $packageName, $license, $shortDescription, $description, $releases ); } } composer-1.6.3/src/Composer/Repository/Pear/DependencyConstraint.php000066400000000000000000000023401323436022200256240ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * PEAR package release dependency info * * @author Alexey Prilipko */ class DependencyConstraint { private $type; private $constraint; private $channelName; private $packageName; /** * @param string $type * @param string $constraint * @param string $channelName * @param string $packageName */ public function __construct($type, $constraint, $channelName, $packageName) { $this->type = $type; $this->constraint = $constraint; $this->channelName = $channelName; $this->packageName = $packageName; } public function getChannelName() { return $this->channelName; } public function getConstraint() { return $this->constraint; } public function getPackageName() { return $this->packageName; } public function getType() { return $this->type; } } composer-1.6.3/src/Composer/Repository/Pear/DependencyInfo.php000066400000000000000000000022331323436022200243740ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * PEAR package release dependency info * * @author Alexey Prilipko */ class DependencyInfo { private $requires; private $optionals; /** * @param DependencyConstraint[] $requires list of requires/conflicts/replaces * @param array $optionals [groupName => DependencyConstraint[]] list of optional groups */ public function __construct($requires, $optionals) { $this->requires = $requires; $this->optionals = $optionals; } /** * @return DependencyConstraint[] list of requires/conflicts/replaces */ public function getRequires() { return $this->requires; } /** * @return array [groupName => DependencyConstraint[]] list of optional groups */ public function getOptionals() { return $this->optionals; } } composer-1.6.3/src/Composer/Repository/Pear/PackageDependencyParser.php000066400000000000000000000252361323436022200262210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * Read PEAR packages using REST 1.0 interface * * @author Alexey Prilipko */ class PackageDependencyParser { /** * Builds dependency information. It detects used package.xml format. * * @param $depArray array * @return DependencyInfo */ public function buildDependencyInfo($depArray) { if (!is_array($depArray)) { return new DependencyInfo(array(), array()); } if (!$this->isHash($depArray)) { return new DependencyInfo($this->buildDependency10Info($depArray), array()); } return $this->buildDependency20Info($depArray); } /** * Builds dependency information from package.xml 1.0 format * * https://pear.php.net/manual/en/guide.developers.package2.dependencies.php * * package.xml 1.0 format consists of array of * { type="php|os|sapi|ext|pkg" rel="has|not|eq|ge|gt|le|lt" optional="yes" * channel="channelName" name="extName|packageName" } * * @param $depArray array Dependency data in package.xml 1.0 format * @return DependencyConstraint[] */ private function buildDependency10Info($depArray) { static $dep10toOperatorMap = array('has' => '==', 'eq' => '==', 'ge' => '>=', 'gt' => '>', 'le' => '<=', 'lt' => '<', 'not' => '!='); $result = array(); foreach ($depArray as $depItem) { if (empty($depItem['rel']) || !array_key_exists($depItem['rel'], $dep10toOperatorMap)) { // 'unknown rel type:' . $depItem['rel']; continue; } $depType = !empty($depItem['optional']) && 'yes' == $depItem['optional'] ? 'optional' : 'required'; $depType = 'not' == $depItem['rel'] ? 'conflicts' : $depType; $depVersion = !empty($depItem['version']) ? $this->parseVersion($depItem['version']) : '*'; // has & not are special operators that does not requires version $depVersionConstraint = ('has' == $depItem['rel'] || 'not' == $depItem['rel']) && '*' == $depVersion ? '*' : $dep10toOperatorMap[$depItem['rel']] . $depVersion; switch ($depItem['type']) { case 'php': $depChannelName = 'php'; $depPackageName = ''; break; case 'pkg': $depChannelName = !empty($depItem['channel']) ? $depItem['channel'] : 'pear.php.net'; $depPackageName = $depItem['name']; break; case 'ext': $depChannelName = 'ext'; $depPackageName = $depItem['name']; break; case 'os': case 'sapi': $depChannelName = ''; $depPackageName = ''; break; default: $depChannelName = ''; $depPackageName = ''; break; } if ('' != $depChannelName) { $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } } return $result; } /** * Builds dependency information from package.xml 2.0 format * * @param $depArray array Dependency data in package.xml 1.0 format * @return DependencyInfo */ private function buildDependency20Info($depArray) { $result = array(); $optionals = array(); $defaultOptionals = array(); foreach ($depArray as $depType => $depTypeGroup) { if (!is_array($depTypeGroup)) { continue; } if ('required' == $depType || 'optional' == $depType) { foreach ($depTypeGroup as $depItemType => $depItem) { switch ($depItemType) { case 'php': $result[] = new DependencyConstraint( $depType, $this->parse20VersionConstraint($depItem), 'php', '' ); break; case 'package': $deps = $this->buildDepPackageConstraints($depItem, $depType); $result = array_merge($result, $deps); break; case 'extension': $deps = $this->buildDepExtensionConstraints($depItem, $depType); $result = array_merge($result, $deps); break; case 'subpackage': $deps = $this->buildDepPackageConstraints($depItem, 'replaces'); $defaultOptionals += $deps; break; case 'os': case 'pearinstaller': break; default: break; } } } elseif ('group' == $depType) { if ($this->isHash($depTypeGroup)) { $depTypeGroup = array($depTypeGroup); } foreach ($depTypeGroup as $depItem) { $groupName = $depItem['attribs']['name']; if (!isset($optionals[$groupName])) { $optionals[$groupName] = array(); } if (isset($depItem['subpackage'])) { $optionals[$groupName] += $this->buildDepPackageConstraints($depItem['subpackage'], 'replaces'); } else { $result += $this->buildDepPackageConstraints($depItem['package'], 'optional'); } } } } if (count($defaultOptionals) > 0) { $optionals['*'] = $defaultOptionals; } return new DependencyInfo($result, $optionals); } /** * Builds dependency constraint of 'extension' type * * @param $depItem array dependency constraint or array of dependency constraints * @param $depType string target type of building constraint. * @return DependencyConstraint[] */ private function buildDepExtensionConstraints($depItem, $depType) { if ($this->isHash($depItem)) { $depItem = array($depItem); } $result = array(); foreach ($depItem as $subDepItem) { $depChannelName = 'ext'; $depPackageName = $subDepItem['name']; $depVersionConstraint = $this->parse20VersionConstraint($subDepItem); $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } return $result; } /** * Builds dependency constraint of 'package' type * * @param $depItem array dependency constraint or array of dependency constraints * @param $depType string target type of building constraint. * @return DependencyConstraint[] */ private function buildDepPackageConstraints($depItem, $depType) { if ($this->isHash($depItem)) { $depItem = array($depItem); } $result = array(); foreach ($depItem as $subDepItem) { if (!array_key_exists('channel', $subDepItem)) { $subDepItem['channel'] = $subDepItem['uri']; } $depChannelName = $subDepItem['channel']; $depPackageName = $subDepItem['name']; $depVersionConstraint = $this->parse20VersionConstraint($subDepItem); if (isset($subDepItem['conflicts'])) { $depType = 'conflicts'; } $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } return $result; } /** * Parses version constraint * * @param array $data array containing several 'min', 'max', 'has', 'exclude' and other keys. * @return string */ private function parse20VersionConstraint(array $data) { static $dep20toOperatorMap = array('has' => '==', 'min' => '>=', 'max' => '<=', 'exclude' => '!='); $versions = array(); $values = array_intersect_key($data, $dep20toOperatorMap); if (0 == count($values)) { return '*'; } if (isset($values['min']) && isset($values['exclude']) && $data['min'] == $data['exclude']) { $versions[] = '>' . $this->parseVersion($values['min']); } elseif (isset($values['max']) && isset($values['exclude']) && $data['max'] == $data['exclude']) { $versions[] = '<' . $this->parseVersion($values['max']); } else { foreach ($values as $op => $version) { if ('exclude' == $op && is_array($version)) { foreach ($version as $versionPart) { $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($versionPart); } } else { $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($version); } } } return implode(',', $versions); } /** * Softened version parser * * @param $version * @return null|string */ private function parseVersion($version) { if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?}i', $version, $matches)) { $version = $matches[1] .(!empty($matches[2]) ? $matches[2] : '.0') .(!empty($matches[3]) ? $matches[3] : '.0') .(!empty($matches[4]) ? $matches[4] : '.0'); return $version; } return null; } /** * Test if array is associative or hash type * * @param array $array * @return bool */ private function isHash(array $array) { return !array_key_exists(1, $array) && !array_key_exists(0, $array); } } composer-1.6.3/src/Composer/Repository/Pear/PackageInfo.php000066400000000000000000000041121323436022200236470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * PEAR Package info * * @author Alexey Prilipko */ class PackageInfo { private $channelName; private $packageName; private $license; private $shortDescription; private $description; private $releases; /** * @param string $channelName * @param string $packageName * @param string $license * @param string $shortDescription * @param string $description * @param ReleaseInfo[] $releases associative array maps release version to release info */ public function __construct($channelName, $packageName, $license, $shortDescription, $description, $releases) { $this->channelName = $channelName; $this->packageName = $packageName; $this->license = $license; $this->shortDescription = $shortDescription; $this->description = $description; $this->releases = $releases; } /** * @return string the package channel name */ public function getChannelName() { return $this->channelName; } /** * @return string the package name */ public function getPackageName() { return $this->packageName; } /** * @return string the package description */ public function getDescription() { return $this->description; } /** * @return string the package short description */ public function getShortDescription() { return $this->shortDescription; } /** * @return string the package license */ public function getLicense() { return $this->license; } /** * @return ReleaseInfo[] */ public function getReleases() { return $this->releases; } } composer-1.6.3/src/Composer/Repository/Pear/ReleaseInfo.php000066400000000000000000000020021323436022200236700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Pear; /** * PEAR package release info * * @author Alexey Prilipko */ class ReleaseInfo { private $stability; private $dependencyInfo; /** * @param string $stability * @param DependencyInfo $dependencyInfo */ public function __construct($stability, $dependencyInfo) { $this->stability = $stability; $this->dependencyInfo = $dependencyInfo; } /** * @return DependencyInfo release dependencies */ public function getDependencyInfo() { return $this->dependencyInfo; } /** * @return string release stability */ public function getStability() { return $this->stability; } } composer-1.6.3/src/Composer/Repository/PearRepository.php000066400000000000000000000210471323436022200236060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\IO\IOInterface; use Composer\Semver\VersionParser as SemverVersionParser; use Composer\Package\Version\VersionParser; use Composer\Repository\Pear\ChannelReader; use Composer\Package\CompletePackage; use Composer\Repository\Pear\ChannelInfo; use Composer\EventDispatcher\EventDispatcher; use Composer\Package\Link; use Composer\Semver\Constraint\Constraint; use Composer\Util\RemoteFilesystem; use Composer\Config; use Composer\Factory; /** * Builds list of package from PEAR channel. * * Packages read from channel are named as 'pear-{channelName}/{packageName}' * and has aliased as 'pear-{channelAlias}/{packageName}' * * @author Benjamin Eberlei * @author Jordi Boggiano */ class PearRepository extends ArrayRepository implements ConfigurableRepositoryInterface { private $url; private $io; private $rfs; private $versionParser; private $repoConfig; /** @var string vendor makes additional alias for each channel as {prefix}/{packagename}. It allows smoother * package transition to composer-like repositories. */ private $vendorAlias; public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $dispatcher = null, RemoteFilesystem $rfs = null) { parent::__construct(); if (!preg_match('{^https?://}', $repoConfig['url'])) { $repoConfig['url'] = 'http://'.$repoConfig['url']; } $urlBits = parse_url($repoConfig['url']); if (empty($urlBits['scheme']) || empty($urlBits['host'])) { throw new \UnexpectedValueException('Invalid url given for PEAR repository: '.$repoConfig['url']); } $this->url = rtrim($repoConfig['url'], '/'); $this->io = $io; $this->rfs = $rfs ?: Factory::createRemoteFilesystem($this->io, $config); $this->vendorAlias = isset($repoConfig['vendor-alias']) ? $repoConfig['vendor-alias'] : null; $this->versionParser = new VersionParser(); $this->repoConfig = $repoConfig; } public function getRepoConfig() { return $this->repoConfig; } protected function initialize() { parent::initialize(); $this->io->writeError('Initializing PEAR repository '.$this->url); $reader = new ChannelReader($this->rfs); try { $channelInfo = $reader->read($this->url); } catch (\Exception $e) { $this->io->writeError('PEAR repository from '.$this->url.' could not be loaded. '.$e->getMessage().''); return; } $packages = $this->buildComposerPackages($channelInfo, $this->versionParser); foreach ($packages as $package) { $this->addPackage($package); } } /** * Builds CompletePackages from PEAR package definition data. * * @param ChannelInfo $channelInfo * @param SemverVersionParser $versionParser * @return CompletePackage */ private function buildComposerPackages(ChannelInfo $channelInfo, SemverVersionParser $versionParser) { $result = array(); foreach ($channelInfo->getPackages() as $packageDefinition) { foreach ($packageDefinition->getReleases() as $version => $releaseInfo) { try { $normalizedVersion = $versionParser->normalize($version); } catch (\UnexpectedValueException $e) { $this->io->writeError('Could not load '.$packageDefinition->getPackageName().' '.$version.': '.$e->getMessage(), true, IOInterface::VERBOSE); continue; } $composerPackageName = $this->buildComposerPackageName($packageDefinition->getChannelName(), $packageDefinition->getPackageName()); // distribution url must be read from /r/{packageName}/{version}.xml::/r/g:text() // but this location is 'de-facto' standard $urlBits = parse_url($this->url); $scheme = (isset($urlBits['scheme']) && 'https' === $urlBits['scheme'] && extension_loaded('openssl')) ? 'https' : 'http'; $distUrl = "{$scheme}://{$packageDefinition->getChannelName()}/get/{$packageDefinition->getPackageName()}-{$version}.tgz"; $requires = array(); $suggests = array(); $conflicts = array(); $replaces = array(); // alias package only when its channel matches repository channel, // cause we've know only repository channel alias if ($channelInfo->getName() == $packageDefinition->getChannelName()) { $composerPackageAlias = $this->buildComposerPackageName($channelInfo->getAlias(), $packageDefinition->getPackageName()); $aliasConstraint = new Constraint('==', $normalizedVersion); $replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint); } // alias package with user-specified prefix. it makes private pear channels looks like composer's. if (!empty($this->vendorAlias) && ($this->vendorAlias != 'pear-'.$channelInfo->getAlias() || $channelInfo->getName() != $packageDefinition->getChannelName()) ) { $composerPackageAlias = "{$this->vendorAlias}/{$packageDefinition->getPackageName()}"; $aliasConstraint = new Constraint('==', $normalizedVersion); $replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint); } foreach ($releaseInfo->getDependencyInfo()->getRequires() as $dependencyConstraint) { $dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName()); $constraint = $versionParser->parseConstraints($dependencyConstraint->getConstraint()); $link = new Link($composerPackageName, $dependencyPackageName, $constraint, $dependencyConstraint->getType(), $dependencyConstraint->getConstraint()); switch ($dependencyConstraint->getType()) { case 'required': $requires[] = $link; break; case 'conflicts': $conflicts[] = $link; break; case 'replaces': $replaces[] = $link; break; } } foreach ($releaseInfo->getDependencyInfo()->getOptionals() as $group => $dependencyConstraints) { foreach ($dependencyConstraints as $dependencyConstraint) { $dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName()); $suggests[$group.'-'.$dependencyPackageName] = $dependencyConstraint->getConstraint(); } } $package = new CompletePackage($composerPackageName, $normalizedVersion, $version); $package->setType('pear-library'); $package->setDescription($packageDefinition->getDescription()); $package->setLicense(array($packageDefinition->getLicense())); $package->setDistType('file'); $package->setDistUrl($distUrl); $package->setAutoload(array('classmap' => array(''))); $package->setIncludePaths(array('/')); $package->setRequires($requires); $package->setConflicts($conflicts); $package->setSuggests($suggests); $package->setReplaces($replaces); $result[] = $package; } } return $result; } private function buildComposerPackageName($channelName, $packageName) { if ('php' === $channelName) { return "php"; } if ('ext' === $channelName) { return "ext-{$packageName}"; } return "pear-{$channelName}/{$packageName}"; } } composer-1.6.3/src/Composer/Repository/PlatformRepository.php000066400000000000000000000251101323436022200244760ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\XdebugHandler; use Composer\Package\CompletePackage; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; use Composer\Plugin\PluginInterface; use Composer\Util\Silencer; /** * @author Jordi Boggiano */ class PlatformRepository extends ArrayRepository { const PLATFORM_PACKAGE_REGEX = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[^/ ]+)$}i'; private $versionParser; /** * Defines overrides so that the platform can be mocked * * Should be an array of package name => version number mappings * * @var array */ private $overrides = array(); public function __construct(array $packages = array(), array $overrides = array()) { foreach ($overrides as $name => $version) { $this->overrides[strtolower($name)] = array('name' => $name, 'version' => $version); } parent::__construct($packages); } protected function initialize() { parent::initialize(); $this->versionParser = new VersionParser(); // Add each of the override versions as options. // Later we might even replace the extensions instead. foreach ($this->overrides as $override) { // Check that it's a platform package. if (!preg_match(self::PLATFORM_PACKAGE_REGEX, $override['name'])) { throw new \InvalidArgumentException('Invalid platform package name in config.platform: '.$override['name']); } $this->addOverriddenPackage($override); } $prettyVersion = PluginInterface::PLUGIN_API_VERSION; $version = $this->versionParser->normalize($prettyVersion); $composerPluginApi = new CompletePackage('composer-plugin-api', $version, $prettyVersion); $composerPluginApi->setDescription('The Composer Plugin API'); $this->addPackage($composerPluginApi); try { $prettyVersion = PHP_VERSION; $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', PHP_VERSION); $version = $this->versionParser->normalize($prettyVersion); } $php = new CompletePackage('php', $version, $prettyVersion); $php->setDescription('The PHP interpreter'); $this->addPackage($php); if (PHP_DEBUG) { $phpdebug = new CompletePackage('php-debug', $version, $prettyVersion); $phpdebug->setDescription('The PHP interpreter, with debugging symbols'); $this->addPackage($phpdebug); } if (defined('PHP_ZTS') && PHP_ZTS) { $phpzts = new CompletePackage('php-zts', $version, $prettyVersion); $phpzts->setDescription('The PHP interpreter, with Zend Thread Safety'); $this->addPackage($phpzts); } if (PHP_INT_SIZE === 8) { $php64 = new CompletePackage('php-64bit', $version, $prettyVersion); $php64->setDescription('The PHP interpreter, 64bit'); $this->addPackage($php64); } // The AF_INET6 constant is only defined if ext-sockets is available but // IPv6 support might still be available. if (defined('AF_INET6') || Silencer::call('inet_pton', '::') !== false) { $phpIpv6 = new CompletePackage('php-ipv6', $version, $prettyVersion); $phpIpv6->setDescription('The PHP interpreter, with IPv6 support'); $this->addPackage($phpIpv6); } $loadedExtensions = get_loaded_extensions(); // Extensions scanning foreach ($loadedExtensions as $name) { if (in_array($name, array('standard', 'Core'))) { continue; } $reflExt = new \ReflectionExtension($name); $prettyVersion = $reflExt->getVersion(); $this->addExtension($name, $prettyVersion); } // Check for xdebug in a restarted process if (!in_array('xdebug', $loadedExtensions, true) && ($prettyVersion = strval(getenv(XdebugHandler::ENV_VERSION)))) { $this->addExtension('xdebug', $prettyVersion); } // Another quick loop, just for possible libraries // Doing it this way to know that functions or constants exist before // relying on them. foreach ($loadedExtensions as $name) { $prettyVersion = null; $description = 'The '.$name.' PHP library'; switch ($name) { case 'curl': $curlVersion = curl_version(); $prettyVersion = $curlVersion['version']; break; case 'iconv': $prettyVersion = ICONV_VERSION; break; case 'intl': $name = 'ICU'; if (defined('INTL_ICU_VERSION')) { $prettyVersion = INTL_ICU_VERSION; } else { $reflector = new \ReflectionExtension('intl'); ob_start(); $reflector->info(); $output = ob_get_clean(); preg_match('/^ICU version => (.*)$/m', $output, $matches); $prettyVersion = $matches[1]; } break; case 'libxml': $prettyVersion = LIBXML_DOTTED_VERSION; break; case 'openssl': $prettyVersion = preg_replace_callback('{^(?:OpenSSL|LibreSSL)?\s*([0-9.]+)([a-z]*).*}i', function ($match) { if (empty($match[2])) { return $match[1]; } // OpenSSL versions add another letter when they reach Z. // e.g. OpenSSL 0.9.8zh 3 Dec 2015 if (!preg_match('{^z*[a-z]$}', $match[2])) { // 0.9.8abc is garbage return 0; } $len = strlen($match[2]); $patchVersion = ($len - 1) * 26; // All Z $patchVersion += ord($match[2][$len - 1]) - 96; return $match[1].'.'.$patchVersion; }, OPENSSL_VERSION_TEXT); $description = OPENSSL_VERSION_TEXT; break; case 'pcre': $prettyVersion = preg_replace('{^(\S+).*}', '$1', PCRE_VERSION); break; case 'uuid': $prettyVersion = phpversion('uuid'); break; case 'xsl': $prettyVersion = LIBXSLT_DOTTED_VERSION; break; default: // None handled extensions have no special cases, skip continue 2; } try { $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { continue; } $lib = new CompletePackage('lib-'.$name, $version, $prettyVersion); $lib->setDescription($description); $this->addPackage($lib); } if (defined('HHVM_VERSION')) { try { $prettyVersion = HHVM_VERSION; $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', HHVM_VERSION); $version = $this->versionParser->normalize($prettyVersion); } $hhvm = new CompletePackage('hhvm', $version, $prettyVersion); $hhvm->setDescription('The HHVM Runtime (64bit)'); $this->addPackage($hhvm); } } /** * {@inheritDoc} */ public function addPackage(PackageInterface $package) { // Skip if overridden if (isset($this->overrides[$package->getName()])) { $overrider = $this->findPackage($package->getName(), '*'); $overrider->setDescription($overrider->getDescription().' (actual: '.$package->getPrettyVersion().')'); return; } // Skip if PHP is overridden and we are adding a php-* package if (isset($this->overrides['php']) && 0 === strpos($package->getName(), 'php-')) { $overrider = $this->addOverriddenPackage($this->overrides['php'], $package->getPrettyName()); $overrider->setDescription($overrider->getDescription().' (actual: '.$package->getPrettyVersion().')'); return; } parent::addPackage($package); } private function addOverriddenPackage(array $override, $name = null) { $version = $this->versionParser->normalize($override['version']); $package = new CompletePackage($name ?: $override['name'], $version, $override['version']); $package->setDescription('Package overridden via config.platform'); $package->setExtra(array('config.platform' => true)); parent::addPackage($package); return $package; } /** * Parses the version and adds a new package to the repository * * @param string $name * @param null|string $prettyVersion */ private function addExtension($name, $prettyVersion) { $extraDescription = null; try { $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { $extraDescription = ' (actual version: '.$prettyVersion.')'; if (preg_match('{^(\d+\.\d+\.\d+(?:\.\d+)?)}', $prettyVersion, $match)) { $prettyVersion = $match[1]; } else { $prettyVersion = '0'; } $version = $this->versionParser->normalize($prettyVersion); } $packageName = $this->buildPackageName($name); $ext = new CompletePackage($packageName, $version, $prettyVersion); $ext->setDescription('The '.$name.' PHP extension'.$extraDescription); $this->addPackage($ext); } private function buildPackageName($name) { return 'ext-' . str_replace(' ', '-', $name); } } composer-1.6.3/src/Composer/Repository/RepositoryFactory.php000066400000000000000000000153321323436022200243260ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Util\RemoteFilesystem; use Composer\Json\JsonFile; /** * @author Jordi Boggiano */ class RepositoryFactory { /** * @param IOInterface $io * @param Config $config * @param string $repository * @param bool $allowFilesystem * @return array|mixed */ public static function configFromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false) { if (0 === strpos($repository, 'http')) { $repoConfig = array('type' => 'composer', 'url' => $repository); } elseif ("json" === pathinfo($repository, PATHINFO_EXTENSION)) { $json = new JsonFile($repository, Factory::createRemoteFilesystem($io, $config)); $data = $json->read(); if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) { $repoConfig = array('type' => 'composer', 'url' => 'file://' . strtr(realpath($repository), '\\', '/')); } elseif ($allowFilesystem) { $repoConfig = array('type' => 'filesystem', 'json' => $json); } else { throw new \InvalidArgumentException("Invalid repository URL ($repository) given. This file does not contain a valid composer repository."); } } elseif ('{' === substr($repository, 0, 1)) { // assume it is a json object that makes a repo config $repoConfig = JsonFile::parseJson($repository); } else { throw new \InvalidArgumentException("Invalid repository url ($repository) given. Has to be a .json file, an http url or a JSON object."); } return $repoConfig; } /** * @param IOInterface $io * @param Config $config * @param string $repository * @param bool $allowFilesystem * @return RepositoryInterface */ public static function fromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false) { $repoConfig = static::configFromString($io, $config, $repository, $allowFilesystem); return static::createRepo($io, $config, $repoConfig); } /** * @param IOInterface $io * @param Config $config * @param array $repoConfig * @return RepositoryInterface */ public static function createRepo(IOInterface $io, Config $config, array $repoConfig) { $rm = static::manager($io, $config, null, Factory::createRemoteFilesystem($io, $config)); $repos = static::createRepos($rm, array($repoConfig)); return reset($repos); } /** * @param IOInterface|null $io * @param Config|null $config * @param RepositoryManager|null $rm * @return RepositoryInterface[] */ public static function defaultRepos(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null) { if (!$config) { $config = Factory::createConfig($io); } if (!$rm) { if (!$io) { throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager'); } $rm = static::manager($io, $config, null, Factory::createRemoteFilesystem($io, $config)); } return static::createRepos($rm, $config->getRepositories()); } /** * @param IOInterface $io * @param Config $config * @param EventDispatcher $eventDispatcher * @param RemoteFilesystem $rfs * @return RepositoryManager */ public static function manager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, RemoteFilesystem $rfs = null) { $rm = new RepositoryManager($io, $config, $eventDispatcher, $rfs); $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository'); $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository'); $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository'); $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('git-bitbucket', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('github', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('fossil', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('hg-bitbucket', 'Composer\Repository\VcsRepository'); $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository'); $rm->setRepositoryClass('path', 'Composer\Repository\PathRepository'); return $rm; } /** * @return RepositoryInterface[] */ private static function createRepos(RepositoryManager $rm, array $repoConfigs) { $repos = array(); foreach ($repoConfigs as $index => $repo) { if (is_string($repo)) { throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given'); } if (!is_array($repo)) { throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.gettype($repo).' given'); } if (!isset($repo['type'])) { throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined'); } $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index; while (isset($repos[$name])) { $name .= '2'; } if ($repo['type'] === 'filesystem') { $repos[$name] = new FilesystemRepository($repo['json']); } else { $repos[$name] = $rm->createRepository($repo['type'], $repo, $index); } } return $repos; } } composer-1.6.3/src/Composer/Repository/RepositoryInterface.php000066400000000000000000000042721323436022200246200ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\PackageInterface; /** * Repository interface. * * @author Nils Adermann * @author Konstantin Kudryashov * @author Jordi Boggiano */ interface RepositoryInterface extends \Countable { const SEARCH_FULLTEXT = 0; const SEARCH_NAME = 1; /** * Checks if specified package registered (installed). * * @param PackageInterface $package package instance * * @return bool */ public function hasPackage(PackageInterface $package); /** * Searches for the first match of a package by name and version. * * @param string $name package name * @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against * * @return PackageInterface|null */ public function findPackage($name, $constraint); /** * Searches for all packages matching a name and optionally a version. * * @param string $name package name * @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against * * @return PackageInterface[] */ public function findPackages($name, $constraint = null); /** * Returns list of registered packages. * * @return PackageInterface[] */ public function getPackages(); /** * Searches the repository for packages containing the query * * @param string $query search query * @param int $mode a set of SEARCH_* constants to search on, implementations should do a best effort only * * @return \array[] an array of array('name' => '...', 'description' => '...') */ public function search($query, $mode = 0); } composer-1.6.3/src/Composer/Repository/RepositoryManager.php000066400000000000000000000126541323436022200242750ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\IO\IOInterface; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Package\PackageInterface; use Composer\Util\RemoteFilesystem; /** * Repositories manager. * * @author Jordi Boggiano * @author Konstantin Kudryashov * @author François Pluchino */ class RepositoryManager { private $localRepository; private $repositories = array(); private $repositoryClasses = array(); private $io; private $config; private $eventDispatcher; private $rfs; public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, RemoteFilesystem $rfs = null) { $this->io = $io; $this->config = $config; $this->eventDispatcher = $eventDispatcher; $this->rfs = $rfs; } /** * Searches for a package by it's name and version in managed repositories. * * @param string $name package name * @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against * * @return PackageInterface|null */ public function findPackage($name, $constraint) { foreach ($this->repositories as $repository) { if ($package = $repository->findPackage($name, $constraint)) { return $package; } } return null; } /** * Searches for all packages matching a name and optionally a version in managed repositories. * * @param string $name package name * @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against * * @return array */ public function findPackages($name, $constraint) { $packages = array(); foreach ($this->repositories as $repository) { $packages = array_merge($packages, $repository->findPackages($name, $constraint)); } return $packages; } /** * Adds repository * * @param RepositoryInterface $repository repository instance */ public function addRepository(RepositoryInterface $repository) { $this->repositories[] = $repository; } /** * Adds a repository to the beginning of the chain * * This is useful when injecting additional repositories that should trump Packagist, e.g. from a plugin. * * @param RepositoryInterface $repository repository instance */ public function prependRepository(RepositoryInterface $repository) { array_unshift($this->repositories, $repository); } /** * Returns a new repository for a specific installation type. * * @param string $type repository type * @param array $config repository configuration * @param string $name repository name * @throws \InvalidArgumentException if repository for provided type is not registered * @return RepositoryInterface */ public function createRepository($type, $config, $name = null) { if (!isset($this->repositoryClasses[$type])) { throw new \InvalidArgumentException('Repository type is not registered: '.$type); } if (isset($config['packagist']) && false === $config['packagist']) { $this->io->writeError('Repository "'.$name.'" ('.json_encode($config).') has a packagist key which should be in its own repository definition'); } $class = $this->repositoryClasses[$type]; $reflMethod = new \ReflectionMethod($class, '__construct'); $params = $reflMethod->getParameters(); if (isset($params[4]) && $params[4]->getClass() && $params[4]->getClass()->getName() === 'Composer\Util\RemoteFilesystem') { return new $class($config, $this->io, $this->config, $this->eventDispatcher, $this->rfs); } return new $class($config, $this->io, $this->config, $this->eventDispatcher); } /** * Stores repository class for a specific installation type. * * @param string $type installation type * @param string $class class name of the repo implementation */ public function setRepositoryClass($type, $class) { $this->repositoryClasses[$type] = $class; } /** * Returns all repositories, except local one. * * @return array */ public function getRepositories() { return $this->repositories; } /** * Sets local repository for the project. * * @param WritableRepositoryInterface $repository repository instance */ public function setLocalRepository(WritableRepositoryInterface $repository) { $this->localRepository = $repository; } /** * Returns local repository for the project. * * @return WritableRepositoryInterface */ public function getLocalRepository() { return $this->localRepository; } } composer-1.6.3/src/Composer/Repository/RepositorySecurityException.php000066400000000000000000000007421323436022200264040ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; /** * Thrown when a security problem, like a broken or missing signature * * @author Eric Daspet */ class RepositorySecurityException extends \Exception { } composer-1.6.3/src/Composer/Repository/Vcs/000077500000000000000000000000001323436022200206355ustar00rootroot00000000000000composer-1.6.3/src/Composer/Repository/Vcs/BitbucketDriver.php000066400000000000000000000312761323436022200244470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Downloader\TransportException; use Composer\Json\JsonFile; use Composer\Util\Bitbucket; abstract class BitbucketDriver extends VcsDriver { /** @var Cache */ protected $cache; protected $owner; protected $repository; protected $hasIssues; protected $rootIdentifier; protected $tags; protected $branches; protected $infoCache = array(); protected $branchesUrl = ''; protected $tagsUrl = ''; protected $homeUrl = ''; protected $website = ''; protected $cloneHttpsUrl = ''; /** * @var VcsDriver */ protected $fallbackDriver; /** @var string|null if set either git or hg */ protected $vcsType; /** * {@inheritDoc} */ public function initialize() { preg_match('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)$#', $this->url, $match); $this->owner = $match[1]; $this->repository = $match[2]; $this->originUrl = 'bitbucket.org'; $this->cache = new Cache( $this->io, implode('/', array( $this->config->get('cache-repo-dir'), $this->originUrl, $this->owner, $this->repository, )) ); } /** * {@inheritDoc} */ public function getUrl() { if ($this->fallbackDriver) { return $this->fallbackDriver->getUrl(); } return $this->cloneHttpsUrl; } /** * Attempts to fetch the repository data via the BitBucket API and * sets some parameters which are used in other methods * * @return bool */ protected function getRepoData() { $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s?%s', $this->owner, $this->repository, http_build_query( array('fields' => '-project,-owner'), null, '&' ) ); $repoData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource, true), $resource); if ($this->fallbackDriver) { return false; } $this->parseCloneUrls($repoData['links']['clone']); $this->hasIssues = !empty($repoData['has_issues']); $this->branchesUrl = $repoData['links']['branches']['href']; $this->tagsUrl = $repoData['links']['tags']['href']; $this->homeUrl = $repoData['links']['html']['href']; $this->website = $repoData['website']; $this->vcsType = $repoData['scm']; return true; } /** * {@inheritDoc} */ public function getComposerInformation($identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getComposerInformation($identifier); } if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } $composer = $this->getBaseComposerInformation($identifier); // specials for bitbucket if (!isset($composer['support']['source'])) { $label = array_search( $identifier, $this->getTags() ) ?: array_search( $identifier, $this->getBranches() ) ?: $identifier; if (array_key_exists($label, $tags = $this->getTags())) { $hash = $tags[$label]; } elseif (array_key_exists($label, $branches = $this->getBranches())) { $hash = $branches[$label]; } if (! isset($hash)) { $composer['support']['source'] = sprintf( 'https://%s/%s/%s/src', $this->originUrl, $this->owner, $this->repository ); } else { $composer['support']['source'] = sprintf( 'https://%s/%s/%s/src/%s/?at=%s', $this->originUrl, $this->owner, $this->repository, $hash, $label ); } } if (!isset($composer['support']['issues']) && $this->hasIssues) { $composer['support']['issues'] = sprintf( 'https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository ); } if (!isset($composer['homepage'])) { $composer['homepage'] = empty($this->website) ? $this->homeUrl : $this->website; } $this->infoCache[$identifier] = $composer; if ($this->shouldCache($identifier)) { $this->cache->write($identifier, json_encode($composer)); } } return $this->infoCache[$identifier]; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getFileContent($file, $identifier); } $resource = sprintf( 'https://api.bitbucket.org/1.0/repositories/%s/%s/raw/%s/%s', $this->owner, $this->repository, $identifier, $file ); return $this->getContentsWithOAuthCredentials($resource); } /** * {@inheritdoc} */ public function getChangeDate($identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getChangeDate($identifier); } $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s/commit/%s?fields=date', $this->owner, $this->repository, $identifier ); $commit = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource); return new \DateTime($commit['date']); } /** * {@inheritDoc} */ public function getSource($identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getSource($identifier); } return array('type' => $this->vcsType, 'url' => $this->getUrl(), 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getDist($identifier); } $url = sprintf( 'https://bitbucket.org/%s/%s/get/%s.zip', $this->owner, $this->repository, $identifier ); return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => ''); } /** * {@inheritDoc} */ public function getTags() { if ($this->fallbackDriver) { return $this->fallbackDriver->getTags(); } if (null === $this->tags) { $this->tags = array(); $resource = sprintf( '%s?%s', $this->tagsUrl, http_build_query( array( 'pagelen' => 100, 'fields' => 'values.name,values.target.hash,next', 'sort' => '-target.date', ), null, '&' ) ); $hasNext = true; while ($hasNext) { $tagsData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource); foreach ($tagsData['values'] as $data) { $this->tags[$data['name']] = $data['target']['hash']; } if (empty($tagsData['next'])) { $hasNext = false; } else { $resource = $tagsData['next']; } } if ($this->vcsType === 'hg') { unset($this->tags['tip']); } } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if ($this->fallbackDriver) { return $this->fallbackDriver->getBranches(); } if (null === $this->branches) { $this->branches = array(); $resource = sprintf( '%s?%s', $this->branchesUrl, http_build_query( array( 'pagelen' => 100, 'fields' => 'values.name,values.target.hash,values.heads,next', 'sort' => '-target.date', ), null, '&' ) ); $hasNext = true; while ($hasNext) { $branchData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource); foreach ($branchData['values'] as $data) { // skip headless branches which seem to be deleted branches that bitbucket nevertheless returns in the API if ($this->vcsType === 'hg' && empty($data['heads'])) { continue; } $this->branches[$data['name']] = $data['target']['hash']; } if (empty($branchData['next'])) { $hasNext = false; } else { $resource = $branchData['next']; } } } return $this->branches; } /** * Get the remote content. * * @param string $url The URL of content * @param bool $fetchingRepoData * * @return mixed The result */ protected function getContentsWithOAuthCredentials($url, $fetchingRepoData = false) { try { return parent::getContents($url); } catch (TransportException $e) { $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process, $this->remoteFilesystem); if (403 === $e->getCode() || (401 === $e->getCode() && strpos($e->getMessage(), 'Could not authenticate against') === 0)) { if (!$this->io->hasAuthentication($this->originUrl) && $bitbucketUtil->authorizeOAuth($this->originUrl) ) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { return $this->attemptCloneFallback(); } } throw $e; } } /** * Generate an SSH URL * * @return string */ abstract protected function generateSshUrl(); protected function attemptCloneFallback() { try { $this->setupFallbackDriver($this->generateSshUrl()); } catch (\RuntimeException $e) { $this->fallbackDriver = null; $this->io->writeError( 'Failed to clone the ' . $this->generateSshUrl() . ' repository, try running in interactive mode' . ' so that you can enter your Bitbucket OAuth consumer credentials' ); throw $e; } } /** * @param string $url * @return void */ abstract protected function setupFallbackDriver($url); /** * @param array $cloneLinks * @return void */ protected function parseCloneUrls(array $cloneLinks) { foreach ($cloneLinks as $cloneLink) { if ($cloneLink['name'] === 'https') { // Format: https://(user@)bitbucket.org/{user}/{repo} // Strip username from URL (only present in clone URL's for private repositories) $this->cloneHttpsUrl = preg_replace('/https:\/\/([^@]+@)?/', 'https://', $cloneLink['href']); } } } /** * @return array|null */ protected function getMainBranchData() { $resource = sprintf( 'https://api.bitbucket.org/1.0/repositories/%s/%s/main-branch', $this->owner, $this->repository ); return JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource); } } composer-1.6.3/src/Composer/Repository/Vcs/FossilDriver.php000066400000000000000000000157511323436022200237720ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\IO\IOInterface; /** * @author BohwaZ */ class FossilDriver extends VcsDriver { protected $tags; protected $branches; protected $rootIdentifier; protected $repoFile; protected $checkoutDir; protected $infoCache = array(); /** * {@inheritDoc} */ public function initialize() { // Make sure fossil is installed and reachable. $this->checkFossil(); // Ensure we are allowed to use this URL by config. $this->config->prohibitUrlByConfig($this->url, $this->io); // Only if url points to a locally accessible directory, assume it's the checkout directory. // Otherwise, it should be something fossil can clone from. if (Filesystem::isLocalPath($this->url) && is_dir($this->url)) { $this->checkoutDir = $this->url; } else { $localName = preg_replace('{[^a-z0-9]}i', '-', $this->url); $this->repoFile = $this->config->get('cache-repo-dir') . '/' . $localName . '.fossil'; $this->checkoutDir = $this->config->get('cache-vcs-dir') . '/' . $localName . '/'; $this->updateLocalRepo(); } $this->getTags(); $this->getBranches(); } /** * Check that fossil can be invoked via command line. */ protected function checkFossil() { if (0 !== $this->process->execute('fossil version', $ignoredOutput)) { throw new \RuntimeException("fossil was not found, check that it is installed and in your PATH env.\n\n" . $this->process->getErrorOutput()); } } /** * Clone or update existing local fossil repository. */ protected function updateLocalRepo() { $fs = new Filesystem(); $fs->ensureDirectoryExists($this->checkoutDir); if (!is_writable(dirname($this->checkoutDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$this->checkoutDir.'" directory is not writable by the current user.'); } // update the repo if it is a valid fossil repository if (is_file($this->repoFile) && is_dir($this->checkoutDir) && 0 === $this->process->execute('fossil info', $output, $this->checkoutDir)) { if (0 !== $this->process->execute('fossil pull', $output, $this->checkoutDir)) { $this->io->writeError('Failed to update '.$this->url.', package information from this repository may be outdated ('.$this->process->getErrorOutput().')'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->checkoutDir); $fs->remove($this->repoFile); $fs->ensureDirectoryExists($this->checkoutDir); if (0 !== $this->process->execute(sprintf('fossil clone %s %s', ProcessExecutor::escape($this->url), ProcessExecutor::escape($this->repoFile)), $output)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to clone '.$this->url.' to repository ' . $this->repoFile . "\n\n" .$output); } if (0 !== $this->process->execute(sprintf('fossil open %s', ProcessExecutor::escape($this->repoFile)), $output, $this->checkoutDir)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to open repository '.$this->repoFile.' in ' . $this->checkoutDir . "\n\n" .$output); } } } /** * {@inheritDoc} */ public function getRootIdentifier() { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'trunk'; } return $this->rootIdentifier; } /** * {@inheritDoc} */ public function getUrl() { return $this->url; } /** * {@inheritDoc} */ public function getSource($identifier) { return array('type' => 'fossil', 'url' => $this->getUrl(), 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { return null; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { $command = sprintf('fossil cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($command, $content, $this->checkoutDir); if (!trim($content)) { return null; } return $content; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { $this->process->execute('fossil finfo -b -n 1 composer.json', $output, $this->checkoutDir); list($ckout, $date, $message) = explode(' ', trim($output), 3); return new \DateTime($date, new \DateTimeZone('UTC')); } /** * {@inheritDoc} */ public function getTags() { if (null === $this->tags) { $tags = array(); $this->process->execute('fossil tag list', $output, $this->checkoutDir); foreach ($this->process->splitLines($output) as $tag) { $tags[$tag] = $tag; } $this->tags = $tags; } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if (null === $this->branches) { $branches = array(); $bookmarks = array(); $this->process->execute('fossil branch list', $output, $this->checkoutDir); foreach ($this->process->splitLines($output) as $branch) { $branch = trim(preg_replace('/^\*/', '', trim($branch))); $branches[$branch] = $branch; } $this->branches = $branches; } return $this->branches; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (preg_match('#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i', $url)) { return true; } if (preg_match('!/fossil/|\.fossil!', $url)) { return true; } // local filesystem if (Filesystem::isLocalPath($url)) { $url = Filesystem::getPlatformPath($url); if (!is_dir($url)) { return false; } $process = new ProcessExecutor(); // check whether there is a fossil repo in that path if ($process->execute('fossil info', $output, $url) === 0) { return true; } } return false; } } composer-1.6.3/src/Composer/Repository/Vcs/GitBitbucketDriver.php000066400000000000000000000045141323436022200251060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\IO\IOInterface; /** * @author Per Bernhardt */ class GitBitbucketDriver extends BitbucketDriver { /** * {@inheritDoc} */ public function getRootIdentifier() { if ($this->fallbackDriver) { return $this->fallbackDriver->getRootIdentifier(); } if (null === $this->rootIdentifier) { if (! $this->getRepoData()) { return $this->fallbackDriver->getRootIdentifier(); } if ($this->vcsType !== 'git') { throw new \RuntimeException( $this->url.' does not appear to be a git repository, use '. $this->cloneHttpsUrl.' if this is a mercurial bitbucket repository' ); } $mainBranchData = $this->getMainBranchData(); $this->rootIdentifier = !empty($mainBranchData['name']) ? $mainBranchData['name'] : 'master'; } return $this->rootIdentifier; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (!preg_match('#^https?://bitbucket\.org/([^/]+)/(.+?)\.git$#', $url)) { return false; } if (!extension_loaded('openssl')) { $io->writeError('Skipping Bitbucket git driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } /** * {@inheritdoc} */ protected function setupFallbackDriver($url) { $this->fallbackDriver = new GitDriver( array('url' => $url), $this->io, $this->config, $this->process, $this->remoteFilesystem ); $this->fallbackDriver->initialize(); } /** * {@inheritdoc} */ protected function generateSshUrl() { return 'git@' . $this->originUrl . ':' . $this->owner.'/'.$this->repository.'.git'; } } composer-1.6.3/src/Composer/Repository/Vcs/GitDriver.php000066400000000000000000000146761323436022200232630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\Util\Git as GitUtil; use Composer\IO\IOInterface; use Composer\Cache; use Composer\Config; /** * @author Jordi Boggiano */ class GitDriver extends VcsDriver { protected $cache; protected $tags; protected $branches; protected $rootIdentifier; protected $repoDir; protected $infoCache = array(); /** * {@inheritDoc} */ public function initialize() { if (Filesystem::isLocalPath($this->url)) { $this->url = preg_replace('{[\\/]\.git/?$}', '', $this->url); $this->repoDir = $this->url; $cacheUrl = realpath($this->url); } else { $this->repoDir = $this->config->get('cache-vcs-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; GitUtil::cleanEnv(); $fs = new Filesystem(); $fs->ensureDirectoryExists(dirname($this->repoDir)); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.dirname($this->repoDir).'" directory is not writable by the current user.'); } if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) { throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.'); } $gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs); if (!$gitUtil->syncMirror($this->url, $this->repoDir)) { $this->io->writeError('Failed to update '.$this->url.', package information from this repository may be outdated'); } $cacheUrl = $this->url; } $this->getTags(); $this->getBranches(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $cacheUrl)); } /** * {@inheritDoc} */ public function getRootIdentifier() { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'master'; // select currently checked out branch if master is not available $this->process->execute('git branch --no-color', $output, $this->repoDir); $branches = $this->process->splitLines($output); if (!in_array('* master', $branches)) { foreach ($branches as $branch) { if ($branch && preg_match('{^\* +(\S+)}', $branch, $match)) { $this->rootIdentifier = $match[1]; break; } } } } return $this->rootIdentifier; } /** * {@inheritDoc} */ public function getUrl() { return $this->url; } /** * {@inheritDoc} */ public function getSource($identifier) { return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { return null; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { $resource = sprintf('%s:%s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute(sprintf('git show %s', $resource), $content, $this->repoDir); if (!trim($content)) { return null; } return $content; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { $this->process->execute(sprintf( 'git log -1 --format=%%at %s', ProcessExecutor::escape($identifier) ), $output, $this->repoDir); return new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); } /** * {@inheritDoc} */ public function getTags() { if (null === $this->tags) { $this->tags = array(); $this->process->execute('git show-ref --tags --dereference', $output, $this->repoDir); foreach ($output = $this->process->splitLines($output) as $tag) { if ($tag && preg_match('{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}', $tag, $match)) { $this->tags[$match[2]] = $match[1]; } } } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if (null === $this->branches) { $branches = array(); $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir); foreach ($this->process->splitLines($output) as $branch) { if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) { if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) { $branches[$match[1]] = $match[2]; } } } $this->branches = $branches; } return $this->branches; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (preg_match('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $url)) { return true; } // local filesystem if (Filesystem::isLocalPath($url)) { $url = Filesystem::getPlatformPath($url); if (!is_dir($url)) { return false; } $process = new ProcessExecutor($io); // check whether there is a git repo in that path if ($process->execute('git tag', $output, $url) === 0) { return true; } } if (!$deep) { return false; } $process = new ProcessExecutor($io); return $process->execute('git ls-remote --heads ' . ProcessExecutor::escape($url), $output) === 0; } } composer-1.6.3/src/Composer/Repository/Vcs/GitHubDriver.php000066400000000000000000000416521323436022200237140ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\Downloader\TransportException; use Composer\Json\JsonFile; use Composer\Cache; use Composer\IO\IOInterface; use Composer\Util\GitHub; /** * @author Jordi Boggiano */ class GitHubDriver extends VcsDriver { protected $cache; protected $owner; protected $repository; protected $tags; protected $branches; protected $rootIdentifier; protected $repoData; protected $hasIssues; protected $infoCache = array(); protected $isPrivate = false; /** * Git Driver * * @var GitDriver */ protected $gitDriver; /** * {@inheritDoc} */ public function initialize() { preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\.git|/)?$#', $this->url, $match); $this->owner = $match[3]; $this->repository = $match[4]; $this->originUrl = !empty($match[1]) ? $match[1] : $match[2]; if ($this->originUrl === 'www.github.com') { $this->originUrl = 'github.com'; } $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository); if (isset($this->repoConfig['no-api']) && $this->repoConfig['no-api']) { $this->setupGitDriver($this->url); return; } $this->fetchRootIdentifier(); } public function getRepositoryUrl() { return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository; } /** * {@inheritDoc} */ public function getRootIdentifier() { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); } return $this->rootIdentifier; } /** * {@inheritDoc} */ public function getUrl() { if ($this->gitDriver) { return $this->gitDriver->getUrl(); } return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git'; } /** * {@inheritDoc} */ protected function getApiUrl() { if ('github.com' === $this->originUrl) { $apiUrl = 'api.github.com'; } else { $apiUrl = $this->originUrl . '/api/v3'; } return 'https://' . $apiUrl; } /** * {@inheritDoc} */ public function getSource($identifier) { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); } if ($this->isPrivate) { // Private GitHub repositories should be accessed using the // SSH version of the URL. $url = $this->generateSshUrl(); } else { $url = $this->getUrl(); } return array('type' => 'git', 'url' => $url, 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier; return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => ''); } /** * {@inheritDoc} */ public function getComposerInformation($identifier) { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); } if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } $composer = $this->getBaseComposerInformation($identifier); if ($composer) { // specials for github if (!isset($composer['support']['source'])) { $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier; $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label); } if (!isset($composer['support']['issues']) && $this->hasIssues) { $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository); } } if ($this->shouldCache($identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); } $notFoundRetries = 2; while ($notFoundRetries) { try { $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/' . $file . '?ref='.urlencode($identifier); $resource = JsonFile::parseJson($this->getContents($resource)); if (empty($resource['content']) || $resource['encoding'] !== 'base64' || !($content = base64_decode($resource['content']))) { throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier); } return $content; } catch (TransportException $e) { if (404 !== $e->getCode()) { throw $e; } // TODO should be removed when possible // retry fetching if github returns a 404 since they happen randomly $notFoundRetries--; return null; } } return null; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); } $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier); $commit = JsonFile::parseJson($this->getContents($resource), $resource); return new \DateTime($commit['commit']['committer']['date']); } /** * {@inheritDoc} */ public function getTags() { if ($this->gitDriver) { return $this->gitDriver->getTags(); } if (null === $this->tags) { $this->tags = array(); $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/tags?per_page=100'; do { $tagsData = JsonFile::parseJson($this->getContents($resource), $resource); foreach ($tagsData as $tag) { $this->tags[$tag['name']] = $tag['commit']['sha']; } $resource = $this->getNextPage(); } while ($resource); } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if ($this->gitDriver) { return $this->gitDriver->getBranches(); } if (null === $this->branches) { $this->branches = array(); $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100'; $branchBlacklist = array('gh-pages'); do { $branchData = JsonFile::parseJson($this->getContents($resource), $resource); foreach ($branchData as $branch) { $name = substr($branch['ref'], 11); if (!in_array($name, $branchBlacklist)) { $this->branches[$name] = $branch['object']['sha']; } } $resource = $this->getNextPage(); } while ($resource); } return $this->branches; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (!preg_match('#^((?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) { return false; } $originUrl = !empty($matches[2]) ? $matches[2] : $matches[3]; if (!in_array(preg_replace('{^www\.}i', '', $originUrl), $config->get('github-domains'))) { return false; } if (!extension_loaded('openssl')) { $io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } /** * Gives back the loaded /repos// result * * @return array|null */ public function getRepoData() { $this->fetchRootIdentifier(); return $this->repoData; } /** * Generate an SSH URL * * @return string */ protected function generateSshUrl() { return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git'; } /** * {@inheritDoc} */ protected function getContents($url, $fetchingRepoData = false) { try { return parent::getContents($url); } catch (TransportException $e) { $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->remoteFilesystem); switch ($e->getCode()) { case 401: case 404: // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404 if (!$fetchingRepoData) { throw $e; } if ($gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive()) { return $this->attemptCloneFallback(); } $scopesIssued = array(); $scopesNeeded = array(); if ($headers = $e->getHeaders()) { if ($scopes = $this->remoteFilesystem->findHeaderValue($headers, 'X-OAuth-Scopes')) { $scopesIssued = explode(' ', $scopes); } if ($scopes = $this->remoteFilesystem->findHeaderValue($headers, 'X-Accepted-OAuth-Scopes')) { $scopesNeeded = explode(' ', $scopes); } } $scopesFailed = array_diff($scopesNeeded, $scopesIssued); // non-authenticated requests get no scopesNeeded, so ask for credentials // authenticated requests which failed some scopes should ask for new credentials too if (!$headers || !count($scopesNeeded) || count($scopesFailed)) { $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata ('.$this->url.')'); } return parent::getContents($url); case 403: if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { return $this->attemptCloneFallback(); } $rateLimited = false; foreach ($e->getHeaders() as $header) { if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) { $rateLimited = true; } } if (!$this->io->hasAuthentication($this->originUrl)) { if (!$this->io->isInteractive()) { $this->io->writeError('GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit'); throw $e; } $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit ('.$this->url.')'); return parent::getContents($url); } if ($rateLimited) { $rateLimit = $this->getRateLimit($e->getHeaders()); $this->io->writeError(sprintf( 'GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests', $rateLimit['limit'], $rateLimit['reset'] )); } throw $e; default: throw $e; } } } /** * Extract ratelimit from response. * * @param array $headers Headers from Composer\Downloader\TransportException. * * @return array Associative array with the keys limit and reset. */ protected function getRateLimit(array $headers) { $rateLimit = array( 'limit' => '?', 'reset' => '?', ); foreach ($headers as $header) { $header = trim($header); if (false === strpos($header, 'X-RateLimit-')) { continue; } list($type, $value) = explode(':', $header, 2); switch ($type) { case 'X-RateLimit-Limit': $rateLimit['limit'] = (int) trim($value); break; case 'X-RateLimit-Reset': $rateLimit['reset'] = date('Y-m-d H:i:s', (int) trim($value)); break; } } return $rateLimit; } /** * Fetch root identifier from GitHub * * @throws TransportException */ protected function fetchRootIdentifier() { if ($this->repoData) { return; } $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository; $this->repoData = JsonFile::parseJson($this->getContents($repoDataUrl, true), $repoDataUrl); if (null === $this->repoData && null !== $this->gitDriver) { return; } $this->owner = $this->repoData['owner']['login']; $this->repository = $this->repoData['name']; $this->isPrivate = !empty($this->repoData['private']); if (isset($this->repoData['default_branch'])) { $this->rootIdentifier = $this->repoData['default_branch']; } elseif (isset($this->repoData['master_branch'])) { $this->rootIdentifier = $this->repoData['master_branch']; } else { $this->rootIdentifier = 'master'; } $this->hasIssues = !empty($this->repoData['has_issues']); } protected function attemptCloneFallback() { $this->isPrivate = true; try { // If this repository may be private (hard to say for sure, // GitHub returns 404 for private repositories) and we // cannot ask for authentication credentials (because we // are not interactive) then we fallback to GitDriver. $this->setupGitDriver($this->generateSshUrl()); return; } catch (\RuntimeException $e) { $this->gitDriver = null; $this->io->writeError('Failed to clone the '.$this->generateSshUrl().' repository, try running in interactive mode so that you can enter your GitHub credentials'); throw $e; } } protected function setupGitDriver($url) { $this->gitDriver = new GitDriver( array('url' => $url), $this->io, $this->config, $this->process, $this->remoteFilesystem ); $this->gitDriver->initialize(); } protected function getNextPage() { $headers = $this->remoteFilesystem->getLastHeaders(); foreach ($headers as $header) { if (preg_match('{^link:\s*(.+?)\s*$}i', $header, $match)) { $links = explode(',', $match[1]); foreach ($links as $link) { if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) { return $match[1]; } } } } } } composer-1.6.3/src/Composer/Repository/Vcs/GitLabDriver.php000066400000000000000000000352701323436022200236730ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\Cache; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Downloader\TransportException; use Composer\Util\RemoteFilesystem; use Composer\Util\GitLab; /** * Driver for GitLab API, use the Git driver for local checkouts. * * @author Henrik Bjørnskov * @author Jérôme Tamarelle */ class GitLabDriver extends VcsDriver { private $scheme; private $namespace; private $repository; /** * @var array Project data returned by GitLab API */ private $project; /** * @var array Keeps commits returned by GitLab API */ private $commits = array(); /** * @var array List of tag => reference */ private $tags; /** * @var array List of branch => reference */ private $branches; /** * Git Driver * * @var GitDriver */ protected $gitDriver; /** * Defaults to true unless we can make sure it is public * * @var bool defines whether the repo is private or not */ private $isPrivate = true; /** * @var int port number */ protected $portNumber; const URL_REGEX = '#^(?:(?Phttps?)://(?P.+?)(?::(?P[0-9]+))?/|git@(?P[^:]+):)(?P.+)/(?P[^/]+?)(?:\.git|/)?$#'; /** * Extracts information from the repository url. * * SSH urls use https by default. Set "secure-http": false on the repository config to use http instead. * * {@inheritDoc} */ public function initialize() { if (!preg_match(self::URL_REGEX, $this->url, $match)) { throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.'); } $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2']; $configuredDomains = $this->config->get('gitlab-domains'); $urlParts = explode('/', $match['parts']); $this->scheme = !empty($match['scheme']) ? $match['scheme'] : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https') ; $this->originUrl = $this->determineOrigin($configuredDomains, $guessedDomain, $urlParts); if (!empty($match['port']) && true === is_numeric($match['port'])) { // If it is an HTTP based URL, and it has a port $this->portNumber = (int) $match['port']; } $this->namespace = implode('/', $urlParts); $this->repository = preg_replace('#(\.git)$#', '', $match['repo']); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository); $this->fetchProject(); } /** * Updates the RemoteFilesystem instance. * Mainly useful for tests. * * @internal */ public function setRemoteFilesystem(RemoteFilesystem $remoteFilesystem) { $this->remoteFilesystem = $remoteFilesystem; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); } // Convert the root identifier to a cachable commit id if (!preg_match('{[a-f0-9]{40}}i', $identifier)) { $branches = $this->getBranches(); if (isset($branches[$identifier])) { $identifier = $branches[$identifier]; } } $resource = $this->getApiUrl().'/repository/files/'.$this->urlEncodeAll($file).'/raw?ref='.$identifier; try { $content = $this->getContents($resource); } catch (TransportException $e) { if ($e->getCode() !== 404) { throw $e; } return null; } return $content; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); } if (isset($this->commits[$identifier])) { return new \DateTime($this->commits[$identifier]['committed_date']); } return new \DateTime(); } /** * {@inheritDoc} */ public function getRepositoryUrl() { return $this->isPrivate ? $this->project['ssh_url_to_repo'] : $this->project['http_url_to_repo']; } /** * {@inheritDoc} */ public function getUrl() { if ($this->gitDriver) { return $this->gitDriver->getUrl(); } return $this->project['web_url']; } /** * {@inheritDoc} */ public function getDist($identifier) { $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier; return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => ''); } /** * {@inheritDoc} */ public function getSource($identifier) { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); } return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier); } /** * {@inheritDoc} */ public function getRootIdentifier() { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); } return $this->project['default_branch']; } /** * {@inheritDoc} */ public function getBranches() { if ($this->gitDriver) { return $this->gitDriver->getBranches(); } if (!$this->branches) { $this->branches = $this->getReferences('branches'); } return $this->branches; } /** * {@inheritDoc} */ public function getTags() { if ($this->gitDriver) { return $this->gitDriver->getTags(); } if (!$this->tags) { $this->tags = $this->getReferences('tags'); } return $this->tags; } /** * @return string Base URL for GitLab API v3 */ public function getApiUrl() { $domainName = $this->originUrl; $portNumber = (true === is_numeric($this->portNumber)) ? sprintf(':%s', $this->portNumber) : ''; return $this->scheme.'://'.$domainName.$portNumber.'/api/v4/projects/'.$this->urlEncodeAll($this->namespace).'%2F'.$this->urlEncodeAll($this->repository); } /** * Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.` * * @param string $string * @return string */ private function urlEncodeAll($string) { $encoded = ''; for ($i = 0; isset($string[$i]); $i++) { $character = $string[$i]; if (!ctype_alnum($character) && !in_array($character, array('-', '_'), true)) { $character = '%' . sprintf('%02X', ord($character)); } $encoded .= $character; } return $encoded; } /** * @param string $type * * @return string[] where keys are named references like tags or branches and the value a sha */ protected function getReferences($type) { $perPage = 100; $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage; $references = array(); do { $data = JsonFile::parseJson($this->getContents($resource), $resource); foreach ($data as $datum) { $references[$datum['name']] = $datum['commit']['id']; // Keep the last commit date of a reference to avoid // unnecessary API call when retrieving the composer file. $this->commits[$datum['commit']['id']] = $datum['commit']; } if (count($data) >= $perPage) { $resource = $this->getNextPage(); } else { $resource = false; } } while ($resource); return $references; } protected function fetchProject() { // we need to fetch the default branch from the api $resource = $this->getApiUrl(); $this->project = JsonFile::parseJson($this->getContents($resource, true), $resource); if (isset($this->project['visibility'])) { $this->isPrivate = $this->project['visibility'] !== 'public'; } else { // client is not authendicated, therefore repository has to be public $this->isPrivate = false; } } protected function attemptCloneFallback() { try { if ($this->isPrivate === false) { $url = $this->generatePublicUrl(); } else { $url = $this->generateSshUrl(); } // If this repository may be private and we // cannot ask for authentication credentials (because we // are not interactive) then we fallback to GitDriver. $this->setupGitDriver($url); return; } catch (\RuntimeException $e) { $this->gitDriver = null; $this->io->writeError('Failed to clone the '.$url.' repository, try running in interactive mode so that you can enter your credentials'); throw $e; } } /** * Generate an SSH URL * * @return string */ protected function generateSshUrl() { return 'git@' . $this->originUrl . ':'.$this->namespace.'/'.$this->repository.'.git'; } protected function generatePublicUrl() { return $this->scheme . '://' . $this->originUrl . '/'.$this->namespace.'/'.$this->repository.'.git'; } protected function setupGitDriver($url) { $this->gitDriver = new GitDriver( array('url' => $url), $this->io, $this->config, $this->process, $this->remoteFilesystem ); $this->gitDriver->initialize(); } /** * {@inheritDoc} */ protected function getContents($url, $fetchingRepoData = false) { try { $res = parent::getContents($url); if ($fetchingRepoData) { $json = JsonFile::parseJson($res, $url); // force auth as the unauthenticated version of the API is broken if (!isset($json['default_branch'])) { if (!empty($json['id'])) { $this->isPrivate = false; } throw new TransportException('GitLab API seems to not be authenticated as it did not return a default_branch', 401); } } return $res; } catch (TransportException $e) { $gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->remoteFilesystem); switch ($e->getCode()) { case 401: case 404: // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404 if (!$fetchingRepoData) { throw $e; } if ($gitLabUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive()) { return $this->attemptCloneFallback(); } $this->io->writeError('Failed to download ' . $this->namespace . '/' . $this->repository . ':' . $e->getMessage() . ''); $gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata ('.$this->url.')'); return parent::getContents($url); case 403: if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { return $this->attemptCloneFallback(); } throw $e; default: throw $e; } } } /** * Uses the config `gitlab-domains` to see if the driver supports the url for the * repository given. * * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (!preg_match(self::URL_REGEX, $url, $match)) { return false; } $scheme = !empty($match['scheme']) ? $match['scheme'] : null; $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2']; $urlParts = explode('/', $match['parts']); if (false === self::determineOrigin((array) $config->get('gitlab-domains'), $guessedDomain, $urlParts)) { return false; } if ('https' === $scheme && !extension_loaded('openssl')) { $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } private function getNextPage() { $headers = $this->remoteFilesystem->getLastHeaders(); foreach ($headers as $header) { if (preg_match('{^link:\s*(.+?)\s*$}i', $header, $match)) { $links = explode(',', $match[1]); foreach ($links as $link) { if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) { return $match[1]; } } } } } /** * @param array $configuredDomains * @param string $guessedDomain * @param array $urlParts * @return bool|string */ private static function determineOrigin(array $configuredDomains, $guessedDomain, array &$urlParts) { if (in_array($guessedDomain, $configuredDomains)) { return $guessedDomain; } while (null !== ($part = array_shift($urlParts))) { $guessedDomain .= '/' . $part; if (in_array($guessedDomain, $configuredDomains)) { return $guessedDomain; } } return false; } } composer-1.6.3/src/Composer/Repository/Vcs/HgBitbucketDriver.php000066400000000000000000000045061323436022200247220ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\IO\IOInterface; /** * @author Per Bernhardt */ class HgBitbucketDriver extends BitbucketDriver { /** * {@inheritDoc} */ public function getRootIdentifier() { if ($this->fallbackDriver) { return $this->fallbackDriver->getRootIdentifier(); } if (null === $this->rootIdentifier) { if (! $this->getRepoData()) { return $this->fallbackDriver->getRootIdentifier(); } if ($this->vcsType !== 'hg') { throw new \RuntimeException( $this->url.' does not appear to be a mercurial repository, use '. $this->cloneHttpsUrl.' if this is a git bitbucket repository' ); } $mainBranchData = $this->getMainBranchData(); $this->rootIdentifier = !empty($mainBranchData['name']) ? $mainBranchData['name'] : 'default'; } return $this->rootIdentifier; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (!preg_match('#^https?://bitbucket\.org/([^/]+)/([^/]+)/?$#', $url)) { return false; } if (!extension_loaded('openssl')) { $io->writeError('Skipping Bitbucket hg driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } /** * {@inheritdoc} */ protected function setupFallbackDriver($url) { $this->fallbackDriver = new HgDriver( array('url' => $url), $this->io, $this->config, $this->process, $this->remoteFilesystem ); $this->fallbackDriver->initialize(); } /** * {@inheritdoc} */ protected function generateSshUrl() { return 'ssh://hg@' . $this->originUrl . '/' . $this->owner.'/'.$this->repository; } } composer-1.6.3/src/Composer/Repository/Vcs/HgDriver.php000066400000000000000000000155741323436022200230740ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\IO\IOInterface; /** * @author Per Bernhardt */ class HgDriver extends VcsDriver { protected $tags; protected $branches; protected $rootIdentifier; protected $repoDir; protected $infoCache = array(); /** * {@inheritDoc} */ public function initialize() { if (Filesystem::isLocalPath($this->url)) { $this->repoDir = $this->url; } else { $cacheDir = $this->config->get('cache-vcs-dir'); $this->repoDir = $cacheDir . '/' . preg_replace('{[^a-z0-9]}i', '-', $this->url) . '/'; $fs = new Filesystem(); $fs->ensureDirectoryExists($cacheDir); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$cacheDir.'" directory is not writable by the current user.'); } // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($this->url, $this->io); // update the repo if it is a valid hg repository if (is_dir($this->repoDir) && 0 === $this->process->execute('hg summary', $output, $this->repoDir)) { if (0 !== $this->process->execute('hg pull', $output, $this->repoDir)) { $this->io->writeError('Failed to update '.$this->url.', package information from this repository may be outdated ('.$this->process->getErrorOutput().')'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->repoDir); if (0 !== $this->process->execute(sprintf('hg clone --noupdate %s %s', ProcessExecutor::escape($this->url), ProcessExecutor::escape($this->repoDir)), $output, $cacheDir)) { $output = $this->process->getErrorOutput(); if (0 !== $this->process->execute('hg --version', $ignoredOutput)) { throw new \RuntimeException('Failed to clone '.$this->url.', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException('Failed to clone '.$this->url.', could not read packages from it' . "\n\n" .$output); } } } $this->getTags(); $this->getBranches(); } /** * {@inheritDoc} */ public function getRootIdentifier() { if (null === $this->rootIdentifier) { $this->process->execute(sprintf('hg tip --template "{node}"'), $output, $this->repoDir); $output = $this->process->splitLines($output); $this->rootIdentifier = $output[0]; } return $this->rootIdentifier; } /** * {@inheritDoc} */ public function getUrl() { return $this->url; } /** * {@inheritDoc} */ public function getSource($identifier) { return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { return null; } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($resource, $content, $this->repoDir); if (!trim($content)) { return; } return $content; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { $this->process->execute( sprintf( 'hg log --template "{date|rfc3339date}" -r %s', ProcessExecutor::escape($identifier) ), $output, $this->repoDir ); return new \DateTime(trim($output), new \DateTimeZone('UTC')); } /** * {@inheritDoc} */ public function getTags() { if (null === $this->tags) { $tags = array(); $this->process->execute('hg tags', $output, $this->repoDir); foreach ($this->process->splitLines($output) as $tag) { if ($tag && preg_match('(^([^\s]+)\s+\d+:(.*)$)', $tag, $match)) { $tags[$match[1]] = $match[2]; } } unset($tags['tip']); $this->tags = $tags; } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if (null === $this->branches) { $branches = array(); $bookmarks = array(); $this->process->execute('hg branches', $output, $this->repoDir); foreach ($this->process->splitLines($output) as $branch) { if ($branch && preg_match('(^([^\s]+)\s+\d+:([a-f0-9]+))', $branch, $match)) { $branches[$match[1]] = $match[2]; } } $this->process->execute('hg bookmarks', $output, $this->repoDir); foreach ($this->process->splitLines($output) as $branch) { if ($branch && preg_match('(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)', $branch, $match)) { $bookmarks[$match[1]] = $match[2]; } } // Branches will have preference over bookmarks $this->branches = array_merge($bookmarks, $branches); } return $this->branches; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (preg_match('#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $url)) { return true; } // local filesystem if (Filesystem::isLocalPath($url)) { $url = Filesystem::getPlatformPath($url); if (!is_dir($url)) { return false; } $process = new ProcessExecutor(); // check whether there is a hg repo in that path if ($process->execute('hg summary', $output, $url) === 0) { return true; } } if (!$deep) { return false; } $processExecutor = new ProcessExecutor(); $exit = $processExecutor->execute(sprintf('hg identify %s', ProcessExecutor::escape($url)), $ignored); return $exit === 0; } } composer-1.6.3/src/Composer/Repository/Vcs/PerforceDriver.php000066400000000000000000000071541323436022200242760ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\IO\IOInterface; use Composer\Util\ProcessExecutor; use Composer\Util\Perforce; /** * @author Matt Whittom */ class PerforceDriver extends VcsDriver { protected $depot; protected $branch; /** @var Perforce */ protected $perforce; /** * {@inheritDoc} */ public function initialize() { $this->depot = $this->repoConfig['depot']; $this->branch = ''; if (!empty($this->repoConfig['branch'])) { $this->branch = $this->repoConfig['branch']; } $this->initPerforce($this->repoConfig); $this->perforce->p4Login(); $this->perforce->checkStream(); $this->perforce->writeP4ClientSpec(); $this->perforce->connectClient(); return true; } private function initPerforce($repoConfig) { if (!empty($this->perforce)) { return; } $repoDir = $this->config->get('cache-vcs-dir') . '/' . $this->depot; $this->perforce = Perforce::create($repoConfig, $this->getUrl(), $repoDir, $this->process, $this->io); } /** * {@inheritdoc} */ public function getFileContent($file, $identifier) { return $this->perforce->getFileContent($file, $identifier); } /** * {@inheritdoc} */ public function getChangeDate($identifier) { return null; } /** * {@inheritDoc} */ public function getRootIdentifier() { return $this->branch; } /** * {@inheritDoc} */ public function getBranches() { return $this->perforce->getBranches(); } /** * {@inheritDoc} */ public function getTags() { return $this->perforce->getTags(); } /** * {@inheritDoc} */ public function getDist($identifier) { return null; } /** * {@inheritDoc} */ public function getSource($identifier) { $source = array( 'type' => 'perforce', 'url' => $this->repoConfig['url'], 'reference' => $identifier, 'p4user' => $this->perforce->getUser(), ); return $source; } /** * {@inheritDoc} */ public function getUrl() { return $this->url; } /** * {@inheritDoc} */ public function hasComposerFile($identifier) { $composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier); $composerInfoIdentifier = $identifier; return !empty($composerInfo); } /** * {@inheritDoc} */ public function getContents($url) { return false; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if ($deep || preg_match('#\b(perforce|p4)\b#i', $url)) { return Perforce::checkServerExists($url, new ProcessExecutor($io)); } return false; } /** * {@inheritDoc} */ public function cleanup() { $this->perforce->cleanupClientSpec(); $this->perforce = null; } public function getDepot() { return $this->depot; } public function getBranch() { return $this->branch; } } composer-1.6.3/src/Composer/Repository/Vcs/SvnDriver.php000066400000000000000000000264171323436022200233020ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Config; use Composer\Json\JsonFile; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\Util\Svn as SvnUtil; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; /** * @author Jordi Boggiano * @author Till Klampaeckel */ class SvnDriver extends VcsDriver { /** * @var Cache */ protected $cache; protected $baseUrl; protected $tags; protected $branches; protected $rootIdentifier; protected $infoCache = array(); protected $trunkPath = 'trunk'; protected $branchesPath = 'branches'; protected $tagsPath = 'tags'; protected $packagePath = ''; protected $cacheCredentials = true; /** * @var \Composer\Util\Svn */ private $util; /** * {@inheritDoc} */ public function initialize() { $this->url = $this->baseUrl = rtrim(self::normalizeUrl($this->url), '/'); SvnUtil::cleanEnv(); if (isset($this->repoConfig['trunk-path'])) { $this->trunkPath = $this->repoConfig['trunk-path']; } if (isset($this->repoConfig['branches-path'])) { $this->branchesPath = $this->repoConfig['branches-path']; } if (isset($this->repoConfig['tags-path'])) { $this->tagsPath = $this->repoConfig['tags-path']; } if (array_key_exists('svn-cache-credentials', $this->repoConfig)) { $this->cacheCredentials = (bool) $this->repoConfig['svn-cache-credentials']; } if (isset($this->repoConfig['package-path'])) { $this->packagePath = '/' . trim($this->repoConfig['package-path'], '/'); } if (false !== ($pos = strrpos($this->url, '/' . $this->trunkPath))) { $this->baseUrl = substr($this->url, 0, $pos); } $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->baseUrl)); $this->getBranches(); $this->getTags(); } /** * {@inheritDoc} */ public function getRootIdentifier() { return $this->rootIdentifier ?: $this->trunkPath; } /** * {@inheritDoc} */ public function getUrl() { return $this->url; } /** * {@inheritDoc} */ public function getSource($identifier) { return array('type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier); } /** * {@inheritDoc} */ public function getDist($identifier) { return null; } /** * {@inheritdoc} */ public function getComposerInformation($identifier) { if (!isset($this->infoCache[$identifier])) { if ($res = $this->cache->read($identifier.'.json')) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } $composer = $this->getBaseComposerInformation($identifier); $this->cache->write($identifier.'.json', json_encode($composer)); $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } /** * @param string $file * @param string $identifier */ public function getFileContent($file, $identifier) { $identifier = '/' . trim($identifier, '/') . '/'; preg_match('{^(.+?)(@\d+)?/$}', $identifier, $match); if (!empty($match[2])) { $path = $match[1]; $rev = $match[2]; } else { $path = $identifier; $rev = ''; } try { $resource = $path.$file; $output = $this->execute('svn cat', $this->baseUrl . $resource . $rev); if (!trim($output)) { return null; } } catch (\RuntimeException $e) { throw new TransportException($e->getMessage()); } return $output; } /** * {@inheritdoc} */ public function getChangeDate($identifier) { $identifier = '/' . trim($identifier, '/') . '/'; preg_match('{^(.+?)(@\d+)?/$}', $identifier, $match); if (!empty($match[2])) { $path = $match[1]; $rev = $match[2]; } else { $path = $identifier; $rev = ''; } $output = $this->execute('svn info', $this->baseUrl . $path . $rev); foreach ($this->process->splitLines($output) as $line) { if ($line && preg_match('{^Last Changed Date: ([^(]+)}', $line, $match)) { return new \DateTime($match[1], new \DateTimeZone('UTC')); } } return null; } /** * {@inheritDoc} */ public function getTags() { if (null === $this->tags) { $this->tags = array(); if ($this->tagsPath !== false) { $output = $this->execute('svn ls --verbose', $this->baseUrl . '/' . $this->tagsPath); if ($output) { foreach ($this->process->splitLines($output) as $line) { $line = trim($line); if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if (isset($match[1]) && isset($match[2]) && $match[2] !== './') { $this->tags[rtrim($match[2], '/')] = $this->buildIdentifier( '/' . $this->tagsPath . '/' . $match[2], $match[1] ); } } } } } } return $this->tags; } /** * {@inheritDoc} */ public function getBranches() { if (null === $this->branches) { $this->branches = array(); if (false === $this->trunkPath) { $trunkParent = $this->baseUrl . '/'; } else { $trunkParent = $this->baseUrl . '/' . $this->trunkPath; } $output = $this->execute('svn ls --verbose', $trunkParent); if ($output) { foreach ($this->process->splitLines($output) as $line) { $line = trim($line); if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if (isset($match[1]) && isset($match[2]) && $match[2] === './') { $this->branches['trunk'] = $this->buildIdentifier( '/' . $this->trunkPath, $match[1] ); $this->rootIdentifier = $this->branches['trunk']; break; } } } } unset($output); if ($this->branchesPath !== false) { $output = $this->execute('svn ls --verbose', $this->baseUrl . '/' . $this->branchesPath); if ($output) { foreach ($this->process->splitLines(trim($output)) as $line) { $line = trim($line); if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if (isset($match[1]) && isset($match[2]) && $match[2] !== './') { $this->branches[rtrim($match[2], '/')] = $this->buildIdentifier( '/' . $this->branchesPath . '/' . $match[2], $match[1] ); } } } } } } return $this->branches; } /** * {@inheritDoc} */ public static function supports(IOInterface $io, Config $config, $url, $deep = false) { $url = self::normalizeUrl($url); if (preg_match('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) { return true; } // proceed with deep check for local urls since they are fast to process if (!$deep && !Filesystem::isLocalPath($url)) { return false; } $processExecutor = new ProcessExecutor(); $exit = $processExecutor->execute( "svn info --non-interactive {$url}", $ignoredOutput ); if ($exit === 0) { // This is definitely a Subversion repository. return true; } // Subversion client 1.7 and older if (false !== stripos($processExecutor->getErrorOutput(), 'authorization failed:')) { // This is likely a remote Subversion repository that requires // authentication. We will handle actual authentication later. return true; } // Subversion client 1.8 and newer if (false !== stripos($processExecutor->getErrorOutput(), 'Authentication failed')) { // This is likely a remote Subversion or newer repository that requires // authentication. We will handle actual authentication later. return true; } return false; } /** * An absolute path (leading '/') is converted to a file:// url. * * @param string $url * * @return string */ protected static function normalizeUrl($url) { $fs = new Filesystem(); if ($fs->isAbsolutePath($url)) { return 'file://' . strtr($url, '\\', '/'); } return $url; } /** * Execute an SVN command and try to fix up the process with credentials * if necessary. * * @param string $command The svn command to run. * @param string $url The SVN URL. * @throws \RuntimeException * @return string */ protected function execute($command, $url) { if (null === $this->util) { $this->util = new SvnUtil($this->baseUrl, $this->io, $this->config, $this->process); $this->util->setCacheCredentials($this->cacheCredentials); } try { return $this->util->execute($command, $url); } catch (\RuntimeException $e) { if (0 !== $this->process->execute('svn --version', $ignoredOutput)) { throw new \RuntimeException('Failed to load '.$this->url.', svn was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException( 'Repository '.$this->url.' could not be processed, '.$e->getMessage() ); } } /** * Build the identifier respecting "package-path" config option * * @param string $baseDir The path to trunk/branch/tag * @param int $revision The revision mark to add to identifier * * @return string */ protected function buildIdentifier($baseDir, $revision) { return rtrim($baseDir, '/') . $this->packagePath . '/@' . $revision; } } composer-1.6.3/src/Composer/Repository/Vcs/VcsDriver.php000066400000000000000000000115361323436022200232630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Downloader\TransportException; use Composer\Config; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\Util\Filesystem; /** * A driver implementation for driver with authentication interaction. * * @author François Pluchino */ abstract class VcsDriver implements VcsDriverInterface { /** @var string */ protected $url; /** @var string */ protected $originUrl; /** @var array */ protected $repoConfig; /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var RemoteFilesystem */ protected $remoteFilesystem; /** @var array */ protected $infoCache = array(); /** @var Cache */ protected $cache; /** * Constructor. * * @param array $repoConfig The repository configuration * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param RemoteFilesystem $remoteFilesystem Remote Filesystem, injectable for mocking */ final public function __construct(array $repoConfig, IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null) { if (Filesystem::isLocalPath($repoConfig['url'])) { $repoConfig['url'] = Filesystem::getPlatformPath($repoConfig['url']); } $this->url = $repoConfig['url']; $this->originUrl = $repoConfig['url']; $this->repoConfig = $repoConfig; $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->remoteFilesystem = $remoteFilesystem ?: Factory::createRemoteFilesystem($this->io, $config); } /** * Returns whether or not the given $identifier should be cached or not. * * @param string $identifier * @return bool */ protected function shouldCache($identifier) { return $this->cache && preg_match('{[a-f0-9]{40}}i', $identifier); } /** * {@inheritdoc} */ public function getComposerInformation($identifier) { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } $composer = $this->getBaseComposerInformation($identifier); if ($this->shouldCache($identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } protected function getBaseComposerInformation($identifier) { $composerFileContent = $this->getFileContent('composer.json', $identifier); if (!$composerFileContent) { return null; } $composer = JsonFile::parseJson($composerFileContent, $identifier . ':composer.json'); if (empty($composer['time']) && $changeDate = $this->getChangeDate($identifier)) { $composer['time'] = $changeDate->format(DATE_RFC3339); } return $composer; } /** * {@inheritDoc} */ public function hasComposerFile($identifier) { try { return (bool) $this->getComposerInformation($identifier); } catch (TransportException $e) { } return false; } /** * Get the https or http protocol depending on SSL support. * * Call this only if you know that the server supports both. * * @return string The correct type of protocol */ protected function getScheme() { if (extension_loaded('openssl')) { return 'https'; } return 'http'; } /** * Get the remote content. * * @param string $url The URL of content * * @return mixed The result */ protected function getContents($url) { $options = isset($this->repoConfig['options']) ? $this->repoConfig['options'] : array(); return $this->remoteFilesystem->getContents($this->originUrl, $url, false, $options); } /** * {@inheritDoc} */ public function cleanup() { return; } } composer-1.6.3/src/Composer/Repository/Vcs/VcsDriverInterface.php000066400000000000000000000061761323436022200251100ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\IO\IOInterface; /** * @author Jordi Boggiano */ interface VcsDriverInterface { /** * Initializes the driver (git clone, svn checkout, fetch info etc) */ public function initialize(); /** * Return the composer.json file information * * @param string $identifier Any identifier to a specific branch/tag/commit * @return array containing all infos from the composer.json file */ public function getComposerInformation($identifier); /** * Return the content of $file or null if the file does not exist. * * @param string $file * @param string $identifier * @return string */ public function getFileContent($file, $identifier); /** * Get the changedate for $identifier. * * @param string $identifier * @return \DateTime */ public function getChangeDate($identifier); /** * Return the root identifier (trunk, master, default/tip ..) * * @return string Identifier */ public function getRootIdentifier(); /** * Return list of branches in the repository * * @return array Branch names as keys, identifiers as values */ public function getBranches(); /** * Return list of tags in the repository * * @return array Tag names as keys, identifiers as values */ public function getTags(); /** * @param string $identifier Any identifier to a specific branch/tag/commit * @return array With type, url reference and shasum keys. */ public function getDist($identifier); /** * @param string $identifier Any identifier to a specific branch/tag/commit * @return array With type, url and reference keys. */ public function getSource($identifier); /** * Return the URL of the repository * * @return string */ public function getUrl(); /** * Return true if the repository has a composer file for a given identifier, * false otherwise. * * @param string $identifier Any identifier to a specific branch/tag/commit * @return bool Whether the repository has a composer file for a given identifier. */ public function hasComposerFile($identifier); /** * Performs any cleanup necessary as the driver is not longer needed */ public function cleanup(); /** * Checks if this driver can handle a given url * * @param IOInterface $io IO instance * @param Config $config current $config * @param string $url URL to validate/check * @param bool $deep unless true, only shallow checks (url matching typically) should be done * @return bool */ public static function supports(IOInterface $io, Config $config, $url, $deep = false); } composer-1.6.3/src/Composer/Repository/VcsRepository.php000066400000000000000000000262741323436022200234610ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Downloader\TransportException; use Composer\Repository\Vcs\VcsDriverInterface; use Composer\Package\Version\VersionParser; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Loader\ValidatingArrayLoader; use Composer\Package\Loader\InvalidPackageException; use Composer\Package\Loader\LoaderInterface; use Composer\EventDispatcher\EventDispatcher; use Composer\IO\IOInterface; use Composer\Config; /** * @author Jordi Boggiano */ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInterface { protected $url; protected $packageName; protected $verbose; protected $io; protected $config; protected $versionParser; protected $type; protected $loader; protected $repoConfig; protected $branchErrorOccurred = false; private $drivers; /** @var VcsDriverInterface */ private $driver; public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $dispatcher = null, array $drivers = null) { parent::__construct(); $this->drivers = $drivers ?: array( 'github' => 'Composer\Repository\Vcs\GitHubDriver', 'gitlab' => 'Composer\Repository\Vcs\GitLabDriver', 'git-bitbucket' => 'Composer\Repository\Vcs\GitBitbucketDriver', 'git' => 'Composer\Repository\Vcs\GitDriver', 'hg-bitbucket' => 'Composer\Repository\Vcs\HgBitbucketDriver', 'hg' => 'Composer\Repository\Vcs\HgDriver', 'perforce' => 'Composer\Repository\Vcs\PerforceDriver', 'fossil' => 'Composer\Repository\Vcs\FossilDriver', // svn must be last because identifying a subversion server for sure is practically impossible 'svn' => 'Composer\Repository\Vcs\SvnDriver', ); $this->url = $repoConfig['url']; $this->io = $io; $this->type = isset($repoConfig['type']) ? $repoConfig['type'] : 'vcs'; $this->verbose = $io->isVeryVerbose(); $this->config = $config; $this->repoConfig = $repoConfig; } public function getRepoConfig() { return $this->repoConfig; } public function setLoader(LoaderInterface $loader) { $this->loader = $loader; } public function getDriver() { if ($this->driver) { return $this->driver; } if (isset($this->drivers[$this->type])) { $class = $this->drivers[$this->type]; $this->driver = new $class($this->repoConfig, $this->io, $this->config); $this->driver->initialize(); return $this->driver; } foreach ($this->drivers as $driver) { if ($driver::supports($this->io, $this->config, $this->url)) { $this->driver = new $driver($this->repoConfig, $this->io, $this->config); $this->driver->initialize(); return $this->driver; } } foreach ($this->drivers as $driver) { if ($driver::supports($this->io, $this->config, $this->url, true)) { $this->driver = new $driver($this->repoConfig, $this->io, $this->config); $this->driver->initialize(); return $this->driver; } } } public function hadInvalidBranches() { return $this->branchErrorOccurred; } protected function initialize() { parent::initialize(); $verbose = $this->verbose; $driver = $this->getDriver(); if (!$driver) { throw new \InvalidArgumentException('No driver found to handle VCS repository '.$this->url); } $this->versionParser = new VersionParser; if (!$this->loader) { $this->loader = new ArrayLoader($this->versionParser); } try { if ($driver->hasComposerFile($driver->getRootIdentifier())) { $data = $driver->getComposerInformation($driver->getRootIdentifier()); $this->packageName = !empty($data['name']) ? $data['name'] : null; } } catch (\Exception $e) { if ($verbose) { $this->io->writeError('Skipped parsing '.$driver->getRootIdentifier().', '.$e->getMessage().''); } } foreach ($driver->getTags() as $tag => $identifier) { $msg = 'Reading composer.json of ' . ($this->packageName ?: $this->url) . ' (' . $tag . ')'; if ($verbose) { $this->io->writeError($msg); } else { $this->io->overwriteError($msg, false); } // strip the release- prefix from tags if present $tag = str_replace('release-', '', $tag); if (!$parsedTag = $this->validateTag($tag)) { if ($verbose) { $this->io->writeError('Skipped tag '.$tag.', invalid tag name'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->writeError('Skipped tag '.$tag.', no composer file'); } continue; } // manually versioned package if (isset($data['version'])) { $data['version_normalized'] = $this->versionParser->normalize($data['version']); } else { // auto-versioned package, read value from tag $data['version'] = $tag; $data['version_normalized'] = $parsedTag; } // make sure tag packages have no -dev flag $data['version'] = preg_replace('{[.-]?dev$}i', '', $data['version']); $data['version_normalized'] = preg_replace('{(^dev-|[.-]?dev$)}i', '', $data['version_normalized']); // broken package, version doesn't match tag if ($data['version_normalized'] !== $parsedTag) { if ($verbose) { $this->io->writeError('Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json'); } continue; } if ($verbose) { $this->io->writeError('Importing tag '.$tag.' ('.$data['version_normalized'].')'); } $this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier))); } catch (\Exception $e) { if ($verbose) { $this->io->writeError('Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found' : $e->getMessage()).''); } continue; } } if (!$verbose) { $this->io->overwriteError('', false); } foreach ($driver->getBranches() as $branch => $identifier) { $msg = 'Reading composer.json of ' . ($this->packageName ?: $this->url) . ' (' . $branch . ')'; if ($verbose) { $this->io->writeError($msg); } else { $this->io->overwriteError($msg, false); } if (!$parsedBranch = $this->validateBranch($branch)) { if ($verbose) { $this->io->writeError('Skipped branch '.$branch.', invalid name'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file'); } continue; } // branches are always auto-versioned, read value from branch name $data['version'] = $branch; $data['version_normalized'] = $parsedBranch; // make sure branch packages have a dev flag if ('dev-' === substr($parsedBranch, 0, 4) || '9999999-dev' === $parsedBranch) { $data['version'] = 'dev-' . $data['version']; } else { $prefix = substr($branch, 0, 1) === 'v' ? 'v' : ''; $data['version'] = $prefix . preg_replace('{(\.9{7})+}', '.x', $parsedBranch); } if ($verbose) { $this->io->writeError('Importing branch '.$branch.' ('.$data['version'].')'); } $packageData = $this->preProcess($driver, $data, $identifier); $package = $this->loader->load($packageData); if ($this->loader instanceof ValidatingArrayLoader && $this->loader->getWarnings()) { throw new InvalidPackageException($this->loader->getErrors(), $this->loader->getWarnings(), $packageData); } $this->addPackage($package); } catch (TransportException $e) { if ($verbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file was found'); } continue; } catch (\Exception $e) { if (!$verbose) { $this->io->writeError(''); } $this->branchErrorOccurred = true; $this->io->writeError('Skipped branch '.$branch.', '.$e->getMessage().''); $this->io->writeError(''); continue; } } $driver->cleanup(); if (!$verbose) { $this->io->overwriteError('', false); } if (!$this->getPackages()) { throw new InvalidRepositoryException('No valid composer.json was found in any branch or tag of '.$this->url.', could not load a package from it.'); } } protected function preProcess(VcsDriverInterface $driver, array $data, $identifier) { // keep the name of the main identifier for all packages $data['name'] = $this->packageName ?: $data['name']; if (!isset($data['dist'])) { $data['dist'] = $driver->getDist($identifier); } if (!isset($data['source'])) { $data['source'] = $driver->getSource($identifier); } return $data; } private function validateBranch($branch) { try { return $this->versionParser->normalizeBranch($branch); } catch (\Exception $e) { } return false; } private function validateTag($version) { try { return $this->versionParser->normalize($version); } catch (\Exception $e) { } return false; } } composer-1.6.3/src/Composer/Repository/WritableArrayRepository.php000066400000000000000000000027601323436022200254700ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\AliasPackage; /** * Writable array repository. * * @author Jordi Boggiano */ class WritableArrayRepository extends ArrayRepository implements WritableRepositoryInterface { /** * {@inheritDoc} */ public function write() { } /** * {@inheritDoc} */ public function reload() { } /** * {@inheritDoc} */ public function getCanonicalPackages() { $packages = $this->getPackages(); // get at most one package of each name, preferring non-aliased ones $packagesByName = array(); foreach ($packages as $package) { if (!isset($packagesByName[$package->getName()]) || $packagesByName[$package->getName()] instanceof AliasPackage) { $packagesByName[$package->getName()] = $package; } } $canonicalPackages = array(); // unfold aliased packages foreach ($packagesByName as $package) { while ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } $canonicalPackages[] = $package; } return $canonicalPackages; } } composer-1.6.3/src/Composer/Repository/WritableRepositoryInterface.php000066400000000000000000000023451323436022200263110ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; use Composer\Package\PackageInterface; /** * Writable repository interface. * * @author Konstantin Kudryashov */ interface WritableRepositoryInterface extends RepositoryInterface { /** * Writes repository (f.e. to the disc). */ public function write(); /** * Adds package to the repository. * * @param PackageInterface $package package instance */ public function addPackage(PackageInterface $package); /** * Removes package from the repository. * * @param PackageInterface $package package instance */ public function removePackage(PackageInterface $package); /** * Get unique packages (at most one package of each name), with aliases resolved and removed. * * @return PackageInterface[] */ public function getCanonicalPackages(); /** * Forces a reload of all packages. */ public function reload(); } composer-1.6.3/src/Composer/Script/000077500000000000000000000000001323436022200171675ustar00rootroot00000000000000composer-1.6.3/src/Composer/Script/CommandEvent.php000066400000000000000000000006401323436022200222600ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Script; /** * The Command Event. * * @deprecated use Composer\Script\Event instead */ class CommandEvent extends Event { } composer-1.6.3/src/Composer/Script/Event.php000066400000000000000000000037201323436022200207630ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Script; use Composer\Composer; use Composer\IO\IOInterface; use Composer\EventDispatcher\Event as BaseEvent; /** * The script event class * * @author François Pluchino * @author Nils Adermann */ class Event extends BaseEvent { /** * @var Composer The composer instance */ private $composer; /** * @var IOInterface The IO instance */ private $io; /** * @var bool Dev mode flag */ private $devMode; /** * Constructor. * * @param string $name The event name * @param Composer $composer The composer object * @param IOInterface $io The IOInterface object * @param bool $devMode Whether or not we are in dev mode * @param array $args Arguments passed by the user * @param array $flags Optional flags to pass data not as argument */ public function __construct($name, Composer $composer, IOInterface $io, $devMode = false, array $args = array(), array $flags = array()) { parent::__construct($name, $args, $flags); $this->composer = $composer; $this->io = $io; $this->devMode = $devMode; } /** * Returns the composer instance. * * @return Composer */ public function getComposer() { return $this->composer; } /** * Returns the IO instance. * * @return IOInterface */ public function getIO() { return $this->io; } /** * Return the dev mode flag * * @return bool */ public function isDevMode() { return $this->devMode; } } composer-1.6.3/src/Composer/Script/PackageEvent.php000066400000000000000000000007571323436022200222460ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Script; use Composer\Installer\PackageEvent as BasePackageEvent; /** * The Package Event. * * @deprecated Use Composer\Installer\PackageEvent instead */ class PackageEvent extends BasePackageEvent { } composer-1.6.3/src/Composer/Script/ScriptEvents.php000066400000000000000000000132531323436022200223350ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Script; /** * The Script Events. * * @author François Pluchino * @author Jordi Boggiano */ class ScriptEvents { /** * The PRE_INSTALL_CMD event occurs before the install command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const PRE_INSTALL_CMD = 'pre-install-cmd'; /** * The POST_INSTALL_CMD event occurs after the install command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_INSTALL_CMD = 'post-install-cmd'; /** * The PRE_UPDATE_CMD event occurs before the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const PRE_UPDATE_CMD = 'pre-update-cmd'; /** * The POST_UPDATE_CMD event occurs after the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_UPDATE_CMD = 'post-update-cmd'; /** * The PRE_STATUS_CMD event occurs before the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const PRE_STATUS_CMD = 'pre-status-cmd'; /** * The POST_STATUS_CMD event occurs after the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_STATUS_CMD = 'post-status-cmd'; /** * The PRE_AUTOLOAD_DUMP event occurs before the autoload file is generated. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const PRE_AUTOLOAD_DUMP = 'pre-autoload-dump'; /** * The POST_AUTOLOAD_DUMP event occurs after the autoload file has been generated. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_AUTOLOAD_DUMP = 'post-autoload-dump'; /** * The POST_ROOT_PACKAGE_INSTALL event occurs after the root package has been installed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_ROOT_PACKAGE_INSTALL = 'post-root-package-install'; /** * The POST_CREATE_PROJECT event occurs after the create-project command has been executed. * Note: Event occurs after POST_INSTALL_CMD * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_CREATE_PROJECT_CMD = 'post-create-project-cmd'; /** * The PRE_ARCHIVE_CMD event occurs before the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const PRE_ARCHIVE_CMD = 'pre-archive-cmd'; /** * The POST_ARCHIVE_CMD event occurs after the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ const POST_ARCHIVE_CMD = 'post-archive-cmd'; /** Deprecated constants below */ /** * The PRE_PACKAGE_INSTALL event occurs before a package is installed. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::PRE_PACKAGE_INSTALL instead. * @var string */ const PRE_PACKAGE_INSTALL = 'pre-package-install'; /** * The POST_PACKAGE_INSTALL event occurs after a package is installed. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::POST_PACKAGE_INSTALL instead. * @var string */ const POST_PACKAGE_INSTALL = 'post-package-install'; /** * The PRE_PACKAGE_UPDATE event occurs before a package is updated. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::PRE_PACKAGE_UPDATE instead. * @var string */ const PRE_PACKAGE_UPDATE = 'pre-package-update'; /** * The POST_PACKAGE_UPDATE event occurs after a package is updated. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::POST_PACKAGE_UPDATE instead. * @var string */ const POST_PACKAGE_UPDATE = 'post-package-update'; /** * The PRE_PACKAGE_UNINSTALL event occurs before a package has been uninstalled. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::PRE_PACKAGE_UNINSTALL instead. * @var string */ const PRE_PACKAGE_UNINSTALL = 'pre-package-uninstall'; /** * The POST_PACKAGE_UNINSTALL event occurs after a package has been uninstalled. * * The event listener method receives a Composer\Installer\PackageEvent instance. * * @deprecated Use Composer\Installer\PackageEvents::POST_PACKAGE_UNINSTALL instead. * @var string */ const POST_PACKAGE_UNINSTALL = 'post-package-uninstall'; } composer-1.6.3/src/Composer/SelfUpdate/000077500000000000000000000000001323436022200177575ustar00rootroot00000000000000composer-1.6.3/src/Composer/SelfUpdate/Keys.php000066400000000000000000000015521323436022200214060ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\SelfUpdate; /** * @author Jordi Boggiano */ class Keys { public static function fingerprint($path) { $hash = strtoupper(hash('sha256', preg_replace('{\s}', '', file_get_contents($path)))); return implode(' ', array( substr($hash, 0, 8), substr($hash, 8, 8), substr($hash, 16, 8), substr($hash, 24, 8), '', // Extra space substr($hash, 32, 8), substr($hash, 40, 8), substr($hash, 48, 8), substr($hash, 56, 8), )); } } composer-1.6.3/src/Composer/SelfUpdate/Versions.php000066400000000000000000000041341323436022200223020ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\SelfUpdate; use Composer\Util\RemoteFilesystem; use Composer\Config; use Composer\Json\JsonFile; /** * @author Jordi Boggiano */ class Versions { private $rfs; private $config; private $channel; public function __construct(Config $config, RemoteFilesystem $rfs) { $this->rfs = $rfs; $this->config = $config; } public function getChannel() { if ($this->channel) { return $this->channel; } $channelFile = $this->config->get('home').'/update-channel'; if (file_exists($channelFile)) { $channel = trim(file_get_contents($channelFile)); if (in_array($channel, array('stable', 'preview', 'snapshot'), true)) { return $this->channel = $channel; } } return $this->channel = 'stable'; } public function setChannel($channel) { if (!in_array($channel, array('stable', 'preview', 'snapshot'), true)) { throw new \InvalidArgumentException('Invalid channel '.$channel.', must be one of: stable, preview, snapshot'); } $channelFile = $this->config->get('home').'/update-channel'; $this->channel = $channel; file_put_contents($channelFile, $channel.PHP_EOL); } public function getLatest() { $protocol = extension_loaded('openssl') ? 'https' : 'http'; $versions = JsonFile::parseJson($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/versions', false)); foreach ($versions[$this->getChannel()] as $version) { if ($version['min-php'] <= PHP_VERSION_ID) { return $version; } } throw new \LogicException('There is no version of Composer available for your PHP version ('.PHP_VERSION.')'); } } composer-1.6.3/src/Composer/Util/000077500000000000000000000000001323436022200166405ustar00rootroot00000000000000composer-1.6.3/src/Composer/Util/AuthHelper.php000066400000000000000000000032371323436022200214170ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Config; use Composer\IO\IOInterface; /** * @author Jordi Boggiano */ class AuthHelper { protected $io; protected $config; public function __construct(IOInterface $io, Config $config) { $this->io = $io; $this->config = $config; } public function storeAuth($originUrl, $storeAuth) { $store = false; $configSource = $this->config->getAuthConfigSource(); if ($storeAuth === true) { $store = $configSource; } elseif ($storeAuth === 'prompt') { $answer = $this->io->askAndValidate( 'Do you want to store credentials for '.$originUrl.' in '.$configSource->getName().' ? [Yn] ', function ($value) { $input = strtolower(substr(trim($value), 0, 1)); if (in_array($input, array('y','n'))) { return $input; } throw new \RuntimeException('Please answer (y)es or (n)o'); }, null, 'y' ); if ($answer === 'y') { $store = $configSource; } } if ($store) { $store->addConfigSetting( 'http-basic.'.$originUrl, $this->io->getAuthentication($originUrl) ); } } } composer-1.6.3/src/Composer/Util/Bitbucket.php000066400000000000000000000206101323436022200212640ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Downloader\TransportException; /** * @author Paul Wenke */ class Bitbucket { private $io; private $config; private $process; private $remoteFilesystem; private $token = array(); private $time; const OAUTH2_ACCESS_TOKEN_URL = 'https://bitbucket.org/site/oauth2/access_token'; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param RemoteFilesystem $remoteFilesystem Remote Filesystem, injectable for mocking * @param int $time Timestamp, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null, $time = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor; $this->remoteFilesystem = $remoteFilesystem ?: Factory::createRemoteFilesystem($this->io, $config); $this->time = $time; } /** * @return string */ public function getToken() { if (!isset($this->token['access_token'])) { return ''; } return $this->token['access_token']; } /** * Attempts to authorize a Bitbucket domain via OAuth * * @param string $originUrl The host this Bitbucket instance is located at * @return bool true on success */ public function authorizeOAuth($originUrl) { if ($originUrl !== 'bitbucket.org') { return false; } // if available use token from git config if (0 === $this->process->execute('git config bitbucket.accesstoken', $output)) { $this->io->setAuthentication($originUrl, 'x-token-auth', trim($output)); return true; } return false; } /** * @param string $originUrl * @return bool */ private function requestAccessToken($originUrl) { try { $json = $this->remoteFilesystem->getContents($originUrl, self::OAUTH2_ACCESS_TOKEN_URL, false, array( 'retry-auth-failure' => false, 'http' => array( 'method' => 'POST', 'content' => 'grant_type=client_credentials', ), )); $this->token = json_decode($json, true); } catch (TransportException $e) { if ($e->getCode() === 400) { $this->io->writeError('Invalid OAuth consumer provided.'); $this->io->writeError('This can have two reasons:'); $this->io->writeError('1. You are authenticating with a bitbucket username/password combination'); $this->io->writeError('2. You are using an OAuth consumer, but didn\'t configure a (dummy) callback url'); return false; } elseif (in_array($e->getCode(), array(403, 401))) { $this->io->writeError('Invalid OAuth consumer provided.'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org "'); return false; } throw $e; } return true; } /** * Authorizes a Bitbucket domain interactively via OAuth * * @param string $originUrl The host this Bitbucket instance is located at * @param string $message The reason this authorization is required * @throws \RuntimeException * @throws TransportException|\Exception * @return bool true on success */ public function authorizeOAuthInteractively($originUrl, $message = null) { if ($message) { $this->io->writeError($message); } $url = 'https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html'; $this->io->writeError(sprintf('Follow the instructions on %s', $url)); $this->io->writeError(sprintf('to create a consumer. It will be stored in "%s" for future use by Composer.', $this->config->getAuthConfigSource()->getName())); $this->io->writeError('Ensure you enter a "Callback URL" (http://example.com is fine) or it will not be possible to create an Access Token (this callback url will not be used by composer)'); $consumerKey = trim($this->io->askAndHideAnswer('Consumer Key (hidden): ')); if (!$consumerKey) { $this->io->writeError('No consumer key given, aborting.'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org "'); return false; } $consumerSecret = trim($this->io->askAndHideAnswer('Consumer Secret (hidden): ')); if (!$consumerSecret) { $this->io->writeError('No consumer secret given, aborting.'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org "'); return false; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken($originUrl)) { return false; } // store value in user config $this->storeInAuthConfig($originUrl, $consumerKey, $consumerSecret); // Remove conflicting basic auth credentials (if available) $this->config->getAuthConfigSource()->removeConfigSetting('http-basic.' . $originUrl); $this->io->writeError('Consumer stored successfully.'); return true; } /** * Retrieves an access token from Bitbucket. * * @param string $originUrl * @param string $consumerKey * @param string $consumerSecret * @return string */ public function requestToken($originUrl, $consumerKey, $consumerSecret) { if (!empty($this->token) || $this->getTokenFromConfig($originUrl)) { return $this->token['access_token']; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken($originUrl)) { return ''; } $this->storeInAuthConfig($originUrl, $consumerKey, $consumerSecret); return $this->token['access_token']; } /** * Store the new/updated credentials to the configuration * @param string $originUrl * @param string $consumerKey * @param string $consumerSecret */ private function storeInAuthConfig($originUrl, $consumerKey, $consumerSecret) { $this->config->getConfigSource()->removeConfigSetting('bitbucket-oauth.'.$originUrl); $time = null === $this->time ? time() : $this->time; $consumer = array( "consumer-key" => $consumerKey, "consumer-secret" => $consumerSecret, "access-token" => $this->token['access_token'], "access-token-expiration" => $time + $this->token['expires_in'], ); $this->config->getAuthConfigSource()->addConfigSetting('bitbucket-oauth.'.$originUrl, $consumer); } /** * @param string $originUrl * @return bool */ private function getTokenFromConfig($originUrl) { $authConfig = $this->config->get('bitbucket-oauth'); if ( !isset($authConfig[$originUrl]['access-token']) || !isset($authConfig[$originUrl]['access-token-expiration']) || time() > $authConfig[$originUrl]['access-token-expiration'] ) { return false; } $this->token = array( 'access_token' => $authConfig[$originUrl]['access-token'], ); return true; } } composer-1.6.3/src/Composer/Util/ComposerMirror.php000066400000000000000000000033731323436022200223410ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * Composer mirror utilities * * @author Jordi Boggiano */ class ComposerMirror { public static function processUrl($mirrorUrl, $packageName, $version, $reference, $type) { if ($reference) { $reference = preg_match('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : md5($reference); } $version = strpos($version, '/') === false ? $version : md5($version); return str_replace( array('%package%', '%version%', '%reference%', '%type%'), array($packageName, $version, $reference, $type), $mirrorUrl ); } public static function processGitUrl($mirrorUrl, $packageName, $url, $type) { if (preg_match('#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#', $url, $match)) { $url = 'gh-'.$match[1].'/'.$match[2]; } elseif (preg_match('#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#', $url, $match)) { $url = 'bb-'.$match[1].'/'.$match[2]; } else { $url = preg_replace('{[^a-z0-9_.-]}i', '-', trim($url, '/')); } return str_replace( array('%package%', '%normalizedUrl%', '%type%'), array($packageName, $url, $type), $mirrorUrl ); } public static function processHgUrl($mirrorUrl, $packageName, $url, $type) { return self::processGitUrl($mirrorUrl, $packageName, $url, $type); } } composer-1.6.3/src/Composer/Util/ConfigValidator.php000066400000000000000000000127121323436022200224270ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Loader\ValidatingArrayLoader; use Composer\Package\Loader\InvalidPackageException; use Composer\Json\JsonValidationException; use Composer\IO\IOInterface; use Composer\Json\JsonFile; /** * Validates a composer configuration. * * @author Robert Schönthal * @author Jordi Boggiano */ class ConfigValidator { private $io; public function __construct(IOInterface $io) { $this->io = $io; } /** * Validates the config, and returns the result. * * @param string $file The path to the file * @param int $arrayLoaderValidationFlags Flags for ArrayLoader validation * * @return array a triple containing the errors, publishable errors, and warnings */ public function validate($file, $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL) { $errors = array(); $publishErrors = array(); $warnings = array(); // validate json schema $laxValid = false; try { $json = new JsonFile($file, null, $this->io); $manifest = $json->read(); $json->validateSchema(JsonFile::LAX_SCHEMA); $laxValid = true; $json->validateSchema(); } catch (JsonValidationException $e) { foreach ($e->getErrors() as $message) { if ($laxValid) { $publishErrors[] = $message; } else { $errors[] = $message; } } } catch (\Exception $e) { $errors[] = $e->getMessage(); return array($errors, $publishErrors, $warnings); } // validate actual data if (empty($manifest['license'])) { $warnings[] = 'No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.'; } if (isset($manifest['version'])) { $warnings[] = 'The version field is present, it is recommended to leave it out if the package is published on Packagist.'; } if (!empty($manifest['name']) && preg_match('{[A-Z]}', $manifest['name'])) { $suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $manifest['name']); $suggestName = strtolower($suggestName); $publishErrors[] = sprintf( 'Name "%s" does not match the best practice (e.g. lower-cased/with-dashes). We suggest using "%s" instead. As such you will not be able to submit it to Packagist.', $manifest['name'], $suggestName ); } if (!empty($manifest['type']) && $manifest['type'] == 'composer-installer') { $warnings[] = "The package type 'composer-installer' is deprecated. Please distribute your custom installers as plugins from now on. See https://getcomposer.org/doc/articles/plugins.md for plugin documentation."; } // check for require-dev overrides if (isset($manifest['require']) && isset($manifest['require-dev'])) { $requireOverrides = array_intersect_key($manifest['require'], $manifest['require-dev']); if (!empty($requireOverrides)) { $plural = (count($requireOverrides) > 1) ? 'are' : 'is'; $warnings[] = implode(', ', array_keys($requireOverrides)). " {$plural} required both in require and require-dev, this can lead to unexpected behavior"; } } // check for commit references $require = isset($manifest['require']) ? $manifest['require'] : array(); $requireDev = isset($manifest['require-dev']) ? $manifest['require-dev'] : array(); $packages = array_merge($require, $requireDev); foreach ($packages as $package => $version) { if (preg_match('/#/', $version) === 1) { $warnings[] = sprintf( 'The package "%s" is pointing to a commit-ref, this is bad practice and can cause unforeseen issues.', $package ); } } // check for empty psr-0/psr-4 namespace prefixes if (isset($manifest['autoload']['psr-0'][''])) { $warnings[] = "Defining autoload.psr-0 with an empty namespace prefix is a bad idea for performance"; } if (isset($manifest['autoload']['psr-4'][''])) { $warnings[] = "Defining autoload.psr-4 with an empty namespace prefix is a bad idea for performance"; } try { $loader = new ValidatingArrayLoader(new ArrayLoader(), true, null, $arrayLoaderValidationFlags); if (!isset($manifest['version'])) { $manifest['version'] = '1.0.0'; } if (!isset($manifest['name'])) { $manifest['name'] = 'dummy/dummy'; } $loader->load($manifest); } catch (InvalidPackageException $e) { $errors = array_merge($errors, $e->getErrors()); } $warnings = array_merge($warnings, $loader->getWarnings()); return array($errors, $publishErrors, $warnings); } } composer-1.6.3/src/Composer/Util/ErrorHandler.php000066400000000000000000000043641323436022200217470ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; /** * Convert PHP errors into exceptions * * @author Artem Lopata */ class ErrorHandler { private static $io; /** * Error handler * * @param int $level Level of the error raised * @param string $message Error message * @param string $file Filename that the error was raised in * @param int $line Line number the error was raised at * * @static * @throws \ErrorException */ public static function handle($level, $message, $file, $line) { // error code is not included in error_reporting if (!(error_reporting() & $level)) { return; } if (ini_get('xdebug.scream')) { $message .= "\n\nWarning: You have xdebug.scream enabled, the warning above may be". "\na legitimately suppressed error that you were not supposed to see."; } if ($level !== E_DEPRECATED && $level !== E_USER_DEPRECATED) { throw new \ErrorException($message, 0, $level, $file, $line); } if (self::$io) { self::$io->writeError('Deprecation Notice: '.$message.' in '.$file.':'.$line.''); if (self::$io->isVerbose()) { self::$io->writeError('Stack trace:'); self::$io->writeError(array_filter(array_map(function ($a) { if (isset($a['line'], $a['file'])) { return ' '.$a['file'].':'.$a['line'].''; } return null; }, array_slice(debug_backtrace(), 2)))); } } } /** * Register error handler. * * @param IOInterface|null $io */ public static function register(IOInterface $io = null) { set_error_handler(array(__CLASS__, 'handle')); error_reporting(E_ALL | E_STRICT); self::$io = $io; } } composer-1.6.3/src/Composer/Util/Filesystem.php000066400000000000000000000524451323436022200215070ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Finder\Finder; /** * @author Jordi Boggiano * @author Johannes M. Schmitt */ class Filesystem { private $processExecutor; public function __construct(ProcessExecutor $executor = null) { $this->processExecutor = $executor ?: new ProcessExecutor(); } public function remove($file) { if (is_dir($file)) { return $this->removeDirectory($file); } if (file_exists($file)) { return $this->unlink($file); } return false; } /** * Checks if a directory is empty * * @param string $dir * @return bool */ public function isDirEmpty($dir) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->depth(0) ->in($dir); return count($finder) === 0; } public function emptyDirectory($dir, $ensureDirectoryExists = true) { if (file_exists($dir) && is_link($dir)) { $this->unlink($dir); } if ($ensureDirectoryExists) { $this->ensureDirectoryExists($dir); } if (is_dir($dir)) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->depth(0) ->in($dir); foreach ($finder as $path) { $this->remove((string) $path); } } } /** * Recursively remove a directory * * Uses the process component if proc_open is enabled on the PHP * installation. * * @param string $directory * @throws \RuntimeException * @return bool */ public function removeDirectory($directory) { if ($this->isSymlinkedDirectory($directory)) { return $this->unlinkSymlinkedDirectory($directory); } if ($this->isJunction($directory)) { return $this->removeJunction($directory); } if (!file_exists($directory) || !is_dir($directory)) { return true; } if (preg_match('{^(?:[a-z]:)?[/\\\\]+$}i', $directory)) { throw new \RuntimeException('Aborting an attempted deletion of '.$directory.', this was probably not intended, if it is a real use case please report it.'); } if (!function_exists('proc_open')) { return $this->removeDirectoryPhp($directory); } if (Platform::isWindows()) { $cmd = sprintf('rmdir /S /Q %s', ProcessExecutor::escape(realpath($directory))); } else { $cmd = sprintf('rm -rf %s', ProcessExecutor::escape($directory)); } $result = $this->getProcess()->execute($cmd, $output) === 0; // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if ($result && !file_exists($directory)) { return true; } return $this->removeDirectoryPhp($directory); } /** * Recursively delete directory using PHP iterators. * * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files * before directories, creating a single non-recursive loop * to delete files/directories in the correct order. * * @param string $directory * @return bool */ public function removeDirectoryPhp($directory) { try { $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); } catch (\UnexpectedValueException $e) { // re-try once after clearing the stat cache if it failed as it // sometimes fails without apparent reason, see https://github.com/composer/composer/issues/4009 clearstatcache(); usleep(100000); if (!is_dir($directory)) { return true; } $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); } $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach ($ri as $file) { if ($file->isDir()) { $this->rmdir($file->getPathname()); } else { $this->unlink($file->getPathname()); } } return $this->rmdir($directory); } public function ensureDirectoryExists($directory) { if (!is_dir($directory)) { if (file_exists($directory)) { throw new \RuntimeException( $directory.' exists and is not a directory.' ); } if (!@mkdir($directory, 0777, true)) { throw new \RuntimeException( $directory.' does not exist and could not be created.' ); } } } /** * Attempts to unlink a file and in case of failure retries after 350ms on windows * * @param string $path * @throws \RuntimeException * @return bool */ public function unlink($path) { if (!@$this->unlinkImplementation($path)) { // retry after a bit on windows since it tends to be touchy with mass removals if (!Platform::isWindows() || (usleep(350000) && !@$this->unlinkImplementation($path))) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . @$error['message']; if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; } /** * Attempts to rmdir a file and in case of failure retries after 350ms on windows * * @param string $path * @throws \RuntimeException * @return bool */ public function rmdir($path) { if (!@rmdir($path)) { // retry after a bit on windows since it tends to be touchy with mass removals if (!Platform::isWindows() || (usleep(350000) && !@rmdir($path))) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . @$error['message']; if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; } /** * Copy then delete is a non-atomic version of {@link rename}. * * Some systems can't rename and also don't have proc_open, * which requires this solution. * * @param string $source * @param string $target */ public function copyThenRemove($source, $target) { $this->copy($source, $target); if (!is_dir($source)) { $this->unlink($source); return; } $this->removeDirectoryPhp($source); } /** * Copies a file or directory from $source to $target. * * @param $source * @param $target * @return bool */ public function copy($source, $target) { if (!is_dir($source)) { return copy($source, $target); } $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST); $this->ensureDirectoryExists($target); $result = true; foreach ($ri as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName(); if ($file->isDir()) { $this->ensureDirectoryExists($targetPath); } else { $result = $result && copy($file->getPathname(), $targetPath); } } return $result; } public function rename($source, $target) { if (true === @rename($source, $target)) { return; } if (!function_exists('proc_open')) { return $this->copyThenRemove($source, $target); } if (Platform::isWindows()) { // Try to copy & delete - this is a workaround for random "Access denied" errors. $command = sprintf('xcopy %s %s /E /I /Q /Y', ProcessExecutor::escape($source), ProcessExecutor::escape($target)); $result = $this->processExecutor->execute($command, $output); // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if (0 === $result) { $this->remove($source); return; } } else { // We do not use PHP's "rename" function here since it does not support // the case where $source, and $target are located on different partitions. $command = sprintf('mv %s %s', ProcessExecutor::escape($source), ProcessExecutor::escape($target)); $result = $this->processExecutor->execute($command, $output); // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if (0 === $result) { return; } } return $this->copyThenRemove($source, $target); } /** * Returns the shortest path from $from to $to * * @param string $from * @param string $to * @param bool $directories if true, the source/target are considered to be directories * @throws \InvalidArgumentException * @return string */ public function findShortestPath($from, $to, $directories = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); } $from = lcfirst($this->normalizePath($from)); $to = lcfirst($this->normalizePath($to)); if ($directories) { $from = rtrim($from, '/') . '/dummy_file'; } if (dirname($from) === dirname($to)) { return './'.basename($to); } $commonPath = $to; while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath)) { $commonPath = strtr(dirname($commonPath), '\\', '/'); } if (0 !== strpos($from, $commonPath) || '/' === $commonPath) { return $to; } $commonPath = rtrim($commonPath, '/') . '/'; $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/'); $commonPathCode = str_repeat('../', $sourcePathDepth); return ($commonPathCode . substr($to, strlen($commonPath))) ?: './'; } /** * Returns PHP code that, when executed in $from, will return the path to $to * * @param string $from * @param string $to * @param bool $directories if true, the source/target are considered to be directories * @param bool $staticCode * @throws \InvalidArgumentException * @return string */ public function findShortestPathCode($from, $to, $directories = false, $staticCode = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); } $from = lcfirst($this->normalizePath($from)); $to = lcfirst($this->normalizePath($to)); if ($from === $to) { return $directories ? '__DIR__' : '__FILE__'; } $commonPath = $to; while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) { $commonPath = strtr(dirname($commonPath), '\\', '/'); } if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) { return var_export($to, true); } $commonPath = rtrim($commonPath, '/') . '/'; if (strpos($to, $from.'/') === 0) { return '__DIR__ . '.var_export(substr($to, strlen($from)), true); } $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories; if ($staticCode) { $commonPathCode = "__DIR__ . '".str_repeat('/..', $sourcePathDepth)."'"; } else { $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth); } $relTarget = substr($to, strlen($commonPath)); return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : ''); } /** * Checks if the given path is absolute * * @param string $path * @return bool */ public function isAbsolutePath($path) { return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':'; } /** * Returns size of a file or directory specified by path. If a directory is * given, it's size will be computed recursively. * * @param string $path Path to the file or directory * @throws \RuntimeException * @return int */ public function size($path) { if (!file_exists($path)) { throw new \RuntimeException("$path does not exist."); } if (is_dir($path)) { return $this->directorySize($path); } return filesize($path); } /** * Normalize a path. This replaces backslashes with slashes, removes ending * slash and collapses redundant separators and up-level references. * * @param string $path Path to the file or directory * @return string */ public function normalizePath($path) { $parts = array(); $path = strtr($path, '\\', '/'); $prefix = ''; $absolute = false; // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: if (preg_match('{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix', $path, $match)) { $prefix = $match[1]; $path = substr($path, strlen($prefix)); } if (substr($path, 0, 1) === '/') { $absolute = true; $path = substr($path, 1); } $up = false; foreach (explode('/', $path) as $chunk) { if ('..' === $chunk && ($absolute || $up)) { array_pop($parts); $up = !(empty($parts) || '..' === end($parts)); } elseif ('.' !== $chunk && '' !== $chunk) { $parts[] = $chunk; $up = '..' !== $chunk; } } return $prefix.($absolute ? '/' : '').implode('/', $parts); } /** * Return if the given path is local * * @param string $path * @return bool */ public static function isLocalPath($path) { return (bool) preg_match('{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path); } public static function getPlatformPath($path) { if (Platform::isWindows()) { $path = preg_replace('{^(?:file:///([a-z]):?/)}i', 'file://$1:/', $path); } return preg_replace('{^file://}i', '', $path); } protected function directorySize($directory) { $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); $size = 0; foreach ($ri as $file) { if ($file->isFile()) { $size += $file->getSize(); } } return $size; } protected function getProcess() { return new ProcessExecutor; } /** * delete symbolic link implementation (commonly known as "unlink()") * * symbolic links on windows which link to directories need rmdir instead of unlink * * @param string $path * * @return bool */ private function unlinkImplementation($path) { if (Platform::isWindows() && is_dir($path) && is_link($path)) { return rmdir($path); } return unlink($path); } /** * Creates a relative symlink from $link to $target * * @param string $target The path of the binary file to be symlinked * @param string $link The path where the symlink should be created * @return bool */ public function relativeSymlink($target, $link) { $cwd = getcwd(); $relativePath = $this->findShortestPath($link, $target); chdir(dirname($link)); $result = @symlink($relativePath, $link); chdir($cwd); return (bool) $result; } /** * return true if that directory is a symlink. * * @param string $directory * * @return bool */ public function isSymlinkedDirectory($directory) { if (!is_dir($directory)) { return false; } $resolved = $this->resolveSymlinkedDirectorySymlink($directory); return is_link($resolved); } /** * @param string $directory * * @return bool */ private function unlinkSymlinkedDirectory($directory) { $resolved = $this->resolveSymlinkedDirectorySymlink($directory); return $this->unlink($resolved); } /** * resolve pathname to symbolic link of a directory * * @param string $pathname directory path to resolve * * @return string resolved path to symbolic link or original pathname (unresolved) */ private function resolveSymlinkedDirectorySymlink($pathname) { if (!is_dir($pathname)) { return $pathname; } $resolved = rtrim($pathname, '/'); if (!strlen($resolved)) { return $pathname; } return $resolved; } /** * Creates an NTFS junction. * * @param string $target * @param string $junction */ public function junction($target, $junction) { if (!Platform::isWindows()) { throw new \LogicException(sprintf('Function %s is not available on non-Windows platform', __CLASS__)); } if (!is_dir($target)) { throw new IOException(sprintf('Cannot junction to "%s" as it is not a directory.', $target), 0, null, $target); } $cmd = sprintf('mklink /J %s %s', ProcessExecutor::escape(str_replace('/', DIRECTORY_SEPARATOR, $junction)), ProcessExecutor::escape(realpath($target))); if ($this->getProcess()->execute($cmd, $output) !== 0) { throw new IOException(sprintf('Failed to create junction to "%s" at "%s".', $target, $junction), 0, null, $target); } clearstatcache(true, $junction); } /** * Returns whether the target directory is a Windows NTFS Junction. * * @param string $junction Path to check. * @return bool */ public function isJunction($junction) { if (!Platform::isWindows()) { return false; } if (!is_dir($junction) || is_link($junction)) { return false; } /** * According to MSDN at https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx we can detect a junction now * using the 'mode' value from stat: "The _S_IFDIR bit is set if path specifies a directory; the _S_IFREG bit * is set if path specifies an ordinary file or a device." We have just tested for a directory above, so if * we have a directory that isn't one according to lstat(...) we must have a junction. * * #define _S_IFDIR 0x4000 * #define _S_IFREG 0x8000 * * Stat cache should be cleared before to avoid accidentally reading wrong information from previous installs. */ clearstatcache(true, $junction); clearstatcache(false); $stat = lstat($junction); return !($stat['mode'] & 0xC000); } /** * Removes a Windows NTFS junction. * * @param string $junction * @return bool */ public function removeJunction($junction) { if (!Platform::isWindows()) { return false; } $junction = rtrim(str_replace('/', DIRECTORY_SEPARATOR, $junction), DIRECTORY_SEPARATOR); if (!$this->isJunction($junction)) { throw new IOException(sprintf('%s is not a junction and thus cannot be removed as one', $junction)); } $cmd = sprintf('rmdir /S /Q %s', ProcessExecutor::escape($junction)); clearstatcache(true, $junction); return ($this->getProcess()->execute($cmd, $output) === 0); } } composer-1.6.3/src/Composer/Util/Git.php000066400000000000000000000344641323436022200201070ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Config; use Composer\IO\IOInterface; /** * @author Jordi Boggiano */ class Git { private static $version; /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var Filesystem */ protected $filesystem; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process, Filesystem $fs) { $this->io = $io; $this->config = $config; $this->process = $process; $this->filesystem = $fs; } public function runCommand($commandCallable, $url, $cwd, $initialClone = false) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); if ($initialClone) { $origCwd = $cwd; $cwd = null; } if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) { throw new \InvalidArgumentException('The source URL ' . $url . ' is invalid, ssh URLs should have a port number after ":".' . "\n" . 'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.'); } if (!$initialClone) { // capture username/password from URL if there is one $this->process->execute('git remote -v', $output, $cwd); if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match)) { $this->io->setAuthentication($match[3], urldecode($match[1]), urldecode($match[2])); } } $protocols = $this->config->get('github-protocols'); if (!is_array($protocols)) { throw new \RuntimeException('Config value "github-protocols" must be an array, got ' . gettype($protocols)); } // public github, autoswitch protocols if (preg_match('{^(?:https?|git)://' . self::getGitHubDomainsRegex($this->config) . '/(.*)}', $url, $match)) { $messages = array(); foreach ($protocols as $protocol) { if ('ssh' === $protocol) { $protoUrl = "git@" . $match[1] . ":" . $match[2]; } else { $protoUrl = $protocol . "://" . $match[1] . "/" . $match[2]; } if (0 === $this->process->execute(call_user_func($commandCallable, $protoUrl), $ignoredOutput, $cwd)) { return; } $messages[] = '- ' . $protoUrl . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput()); if ($initialClone) { $this->filesystem->removeDirectory($origCwd); } } // failed to checkout, first check git accessibility $this->throwException('Failed to clone ' . $url . ' via ' . implode(', ', $protocols) . ' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url); } // if we have a private github url and the ssh protocol is disabled then we skip it and directly fallback to https $bypassSshForGitHub = preg_match('{^git@' . self::getGitHubDomainsRegex($this->config) . ':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true); $command = call_user_func($commandCallable, $url); $auth = null; if ($bypassSshForGitHub || 0 !== $this->process->execute($command, $ignoredOutput, $cwd)) { // private github repository without git access, try https with auth if (preg_match('{^git@' . self::getGitHubDomainsRegex($this->config) . ':(.+?)\.git$}i', $url, $match)) { if (!$this->io->hasAuthentication($match[1])) { $gitHubUtil = new GitHub($this->io, $this->config, $this->process); $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos'; if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) { $gitHubUtil->authorizeOAuthInteractively($match[1], $message); } } if ($this->io->hasAuthentication($match[1])) { $auth = $this->io->getAuthentication($match[1]); $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git'; $command = call_user_func($commandCallable, $authUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } } } elseif (preg_match('{^https://(bitbucket\.org)/(.*)(\.git)?$}U', $url, $match)) { //bitbucket oauth $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process); if (!$this->io->hasAuthentication($match[1])) { $message = 'Enter your Bitbucket credentials to access private repos'; if (!$bitbucketUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) { $bitbucketUtil->authorizeOAuthInteractively($match[1], $message); $accessToken = $bitbucketUtil->getToken(); $this->io->setAuthentication($match[1], 'x-token-auth', $accessToken); } } else { //We're authenticating with a locally stored consumer. $auth = $this->io->getAuthentication($match[1]); //We already have an access_token from a previous request. if ($auth['username'] !== 'x-token-auth') { $accessToken = $bitbucketUtil->requestToken($match[1], $auth['username'], $auth['password']); if (! empty($accessToken)) { $this->io->setAuthentication($match[1], 'x-token-auth', $accessToken); } } } if ($this->io->hasAuthentication($match[1])) { $auth = $this->io->getAuthentication($match[1]); $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git'; $command = call_user_func($commandCallable, $authUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } } else { // Falling back to ssh $sshUrl = 'git@bitbucket.org:' . $match[2] . '.git'; $this->io->writeError(' No bitbucket authentication configured. Falling back to ssh.'); $command = call_user_func($commandCallable, $sshUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } } } elseif ($this->isAuthenticationFailure($url, $match)) { // private non-github repo that failed to authenticate if (strpos($match[2], '@')) { list($authParts, $match[2]) = explode('@', $match[2], 2); } $storeAuth = false; if ($this->io->hasAuthentication($match[2])) { $auth = $this->io->getAuthentication($match[2]); } elseif ($this->io->isInteractive()) { $defaultUsername = null; if (isset($authParts) && $authParts) { if (false !== strpos($authParts, ':')) { list($defaultUsername, ) = explode(':', $authParts, 2); } else { $defaultUsername = $authParts; } } $this->io->writeError(' Authentication required (' . parse_url($url, PHP_URL_HOST) . '):'); $auth = array( 'username' => $this->io->ask(' Username: ', $defaultUsername), 'password' => $this->io->askAndHideAnswer(' Password: '), ); $storeAuth = $this->config->get('store-auths'); } if ($auth) { $authUrl = $match[1] . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[2] . $match[3]; $command = call_user_func($commandCallable, $authUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { $this->io->setAuthentication($match[2], $auth['username'], $auth['password']); $authHelper = new AuthHelper($this->io, $this->config); $authHelper->storeAuth($match[2], $storeAuth); return; } } } if ($initialClone) { $this->filesystem->removeDirectory($origCwd); } $this->throwException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(), $url); } } public function syncMirror($url, $dir) { // update the repo if it is a valid git repository if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { try { $commandCallable = function ($url) { return sprintf('git remote set-url origin %s && git remote update --prune origin', ProcessExecutor::escape($url)); }; $this->runCommand($commandCallable, $url, $dir); } catch (\Exception $e) { return false; } return true; } // clean up directory and do a fresh clone into it $this->filesystem->removeDirectory($dir); $commandCallable = function ($url) use ($dir) { return sprintf('git clone --mirror %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir)); }; $this->runCommand($commandCallable, $url, $dir, true); return true; } public function fetchRefOrSyncMirror($url, $dir, $ref) { if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { $escapedRef = ProcessExecutor::escape($ref.'^{commit}'); $exitCode = $this->process->execute(sprintf('git rev-parse --quiet --verify %s', $escapedRef), $output, $dir); if ($exitCode === 0) { return true; } } $this->syncMirror($url, $dir); return false; } private function isAuthenticationFailure($url, &$match) { if (!preg_match('{(https?://)([^/]+)(.*)$}i', $url, $match)) { return false; } $authFailures = array( 'fatal: Authentication failed', 'remote error: Invalid username or password.', 'error: 401 Unauthorized', 'fatal: unable to access', ); foreach ($authFailures as $authFailure) { if (strpos($this->process->getErrorOutput(), $authFailure) !== false) { return true; } } return false; } public static function cleanEnv() { if (PHP_VERSION_ID < 50400 && ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars'), 'GIT_ASKPASS')) { throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer'); } // added in git 1.7.1, prevents prompting the user for username/password if (getenv('GIT_ASKPASS') !== 'echo') { putenv('GIT_ASKPASS=echo'); unset($_SERVER['GIT_ASKPASS']); } // clean up rogue git env vars in case this is running in a git hook if (getenv('GIT_DIR')) { putenv('GIT_DIR'); unset($_SERVER['GIT_DIR']); } if (getenv('GIT_WORK_TREE')) { putenv('GIT_WORK_TREE'); unset($_SERVER['GIT_WORK_TREE']); } // Run processes with predictable LANGUAGE if (getenv('LANGUAGE') !== 'C') { putenv('LANGUAGE=C'); } // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940 putenv("DYLD_LIBRARY_PATH"); unset($_SERVER['DYLD_LIBRARY_PATH']); } public static function getGitHubDomainsRegex(Config $config) { return '(' . implode('|', array_map('preg_quote', $config->get('github-domains'))) . ')'; } public static function sanitizeUrl($message) { return preg_replace_callback('{://(?P[^@]+?):(?P.+?)@}', function ($m) { if (preg_match('{^[a-f0-9]{12,}$}', $m[1])) { return '://***:***@'; } return '://' . $m[1] . ':***@'; }, $message); } private function throwException($message, $url) { // git might delete a directory when it fails and php will not know clearstatcache(); if (0 !== $this->process->execute('git --version', $ignoredOutput)) { throw new \RuntimeException(self::sanitizeUrl('Failed to clone ' . $url . ', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput())); } throw new \RuntimeException(self::sanitizeUrl($message)); } /** * Retrieves the current git version. * * @return string|null The git version number. */ public function getVersion() { if (isset(self::$version)) { return self::$version; } if (0 !== $this->process->execute('git --version', $output)) { return; } if (preg_match('/^git version (\d+(?:\.\d+)+)/m', $output, $matches)) { return self::$version = $matches[1]; } } } composer-1.6.3/src/Composer/Util/GitHub.php000066400000000000000000000110201323436022200205250ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Downloader\TransportException; /** * @author Jordi Boggiano */ class GitHub { protected $io; protected $config; protected $process; protected $remoteFilesystem; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param RemoteFilesystem $remoteFilesystem Remote Filesystem, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor; $this->remoteFilesystem = $remoteFilesystem ?: Factory::createRemoteFilesystem($this->io, $config); } /** * Attempts to authorize a GitHub domain via OAuth * * @param string $originUrl The host this GitHub instance is located at * @return bool true on success */ public function authorizeOAuth($originUrl) { if (!in_array($originUrl, $this->config->get('github-domains'))) { return false; } // if available use token from git config if (0 === $this->process->execute('git config github.accesstoken', $output)) { $this->io->setAuthentication($originUrl, trim($output), 'x-oauth-basic'); return true; } return false; } /** * Authorizes a GitHub domain interactively via OAuth * * @param string $originUrl The host this GitHub instance is located at * @param string $message The reason this authorization is required * @throws \RuntimeException * @throws TransportException|\Exception * @return bool true on success */ public function authorizeOAuthInteractively($originUrl, $message = null) { if ($message) { $this->io->writeError($message); } $note = 'Composer'; if ($this->config->get('github-expose-hostname') === true && 0 === $this->process->execute('hostname', $output)) { $note .= ' on ' . trim($output); } $note .= ' ' . date('Y-m-d Hi'); $url = 'https://'.$originUrl.'/settings/tokens/new?scopes=repo&description=' . str_replace('%20', '+', rawurlencode($note)); $this->io->writeError(sprintf('Head to %s', $url)); $this->io->writeError(sprintf('to retrieve a token. It will be stored in "%s" for future use by Composer.', $this->config->getAuthConfigSource()->getName())); $token = trim($this->io->askAndHideAnswer('Token (hidden): ')); if (!$token) { $this->io->writeError('No token given, aborting.'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth github-oauth.github.com "'); return false; } $this->io->setAuthentication($originUrl, $token, 'x-oauth-basic'); try { $apiUrl = ('github.com' === $originUrl) ? 'api.github.com/' : $originUrl . '/api/v3/'; $this->remoteFilesystem->getContents($originUrl, 'https://'. $apiUrl, false, array( 'retry-auth-failure' => false, )); } catch (TransportException $e) { if (in_array($e->getCode(), array(403, 401))) { $this->io->writeError('Invalid token provided.'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth github-oauth.github.com "'); return false; } throw $e; } // store value in user config $this->config->getConfigSource()->removeConfigSetting('github-oauth.'.$originUrl); $this->config->getAuthConfigSource()->addConfigSetting('github-oauth.'.$originUrl, $token); $this->io->writeError('Token stored successfully.'); return true; } } composer-1.6.3/src/Composer/Util/GitLab.php000066400000000000000000000126541323436022200205230ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; use Composer\Config; use Composer\Factory; use Composer\Downloader\TransportException; use Composer\Json\JsonFile; /** * @author Roshan Gautam */ class GitLab { protected $io; protected $config; protected $process; protected $remoteFilesystem; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param RemoteFilesystem $remoteFilesystem Remote Filesystem, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor(); $this->remoteFilesystem = $remoteFilesystem ?: Factory::createRemoteFilesystem($this->io, $config); } /** * Attempts to authorize a GitLab domain via OAuth. * * @param string $originUrl The host this GitLab instance is located at * * @return bool true on success */ public function authorizeOAuth($originUrl) { if (!in_array($originUrl, $this->config->get('gitlab-domains'), true)) { return false; } // if available use token from git config if (0 === $this->process->execute('git config gitlab.accesstoken', $output)) { $this->io->setAuthentication($originUrl, trim($output), 'oauth2'); return true; } // if available use token from composer config $authTokens = $this->config->get('gitlab-token'); if (isset($authTokens[$originUrl])) { $this->io->setAuthentication($originUrl, $authTokens[$originUrl], 'private-token'); return true; } return false; } /** * Authorizes a GitLab domain interactively via OAuth. * * @param string $scheme Scheme used in the origin URL * @param string $originUrl The host this GitLab instance is located at * @param string $message The reason this authorization is required * * @throws \RuntimeException * @throws TransportException|\Exception * * @return bool true on success */ public function authorizeOAuthInteractively($scheme, $originUrl, $message = null) { if ($message) { $this->io->writeError($message); } $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', $this->config->getAuthConfigSource()->getName())); $this->io->writeError('To revoke access to this token you can visit '.$originUrl.'/profile/applications'); $attemptCounter = 0; while ($attemptCounter++ < 5) { try { $response = $this->createToken($scheme, $originUrl); } catch (TransportException $e) { // 401 is bad credentials, // 403 is max login attempts exceeded if (in_array($e->getCode(), array(403, 401))) { if (401 === $e->getCode()) { $this->io->writeError('Bad credentials.'); } else { $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.'); } $this->io->writeError('You can also manually create a personal token at '.$scheme.'://'.$originUrl.'/profile/personal_access_tokens'); $this->io->writeError('Add it using "composer config --global --auth gitlab-token.'.$originUrl.' "'); continue; } throw $e; } $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2'); // store value in user config in auth file $this->config->getAuthConfigSource()->addConfigSetting('gitlab-oauth.'.$originUrl, $response['access_token']); return true; } throw new \RuntimeException('Invalid GitLab credentials 5 times in a row, aborting.'); } private function createToken($scheme, $originUrl) { $username = $this->io->ask('Username: '); $password = $this->io->askAndHideAnswer('Password: '); $headers = array('Content-Type: application/x-www-form-urlencoded'); $apiUrl = $originUrl; $data = http_build_query(array( 'username' => $username, 'password' => $password, 'grant_type' => 'password', ), null, '&'); $options = array( 'retry-auth-failure' => false, 'http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $data, ), ); $json = $this->remoteFilesystem->getContents($originUrl, $scheme.'://'.$apiUrl.'/oauth/token', false, $options); $this->io->writeError('Token successfully created'); return JsonFile::parseJson($json); } } composer-1.6.3/src/Composer/Util/IniHelper.php000066400000000000000000000036411323436022200212340ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * Provides ini file location functions that work with and without a restart. * When the process has restarted it uses a tmp ini and stores the original * ini locations in an environment variable. * * @author John Stevenson */ class IniHelper { const ENV_ORIGINAL = 'COMPOSER_ORIGINAL_INIS'; /** * Returns an array of php.ini locations with at least one entry * * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files. * The loaded ini location is the first entry and may be empty. * * @return array */ public static function getAll() { $env = getenv(self::ENV_ORIGINAL); if (false !== $env) { return explode(PATH_SEPARATOR, $env); } $paths = array(strval(php_ini_loaded_file())); if ($scanned = php_ini_scanned_files()) { $paths = array_merge($paths, array_map('trim', explode(',', $scanned))); } return $paths; } /** * Describes the location of the loaded php.ini file(s) * * @return string */ public static function getMessage() { $paths = self::getAll(); if (empty($paths[0])) { array_shift($paths); } $ini = array_shift($paths); if (empty($ini)) { return 'A php.ini file does not exist. You will have to create one.'; } if (!empty($paths)) { return 'Your command-line PHP is using multiple ini files. Run `php --ini` to show them.'; } return 'The php.ini used by your command-line PHP is: '.$ini; } } composer-1.6.3/src/Composer/Util/NoProxyPattern.php000066400000000000000000000101061323436022200223230ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * Tests URLs against no_proxy patterns. */ class NoProxyPattern { /** * @var string[] */ protected $rules = array(); /** * @param string $pattern no_proxy pattern */ public function __construct($pattern) { $this->rules = preg_split("/[\s,]+/", $pattern); } /** * Test a URL against the stored pattern. * * @param string $url * * @return true if the URL matches one of the rules. */ public function test($url) { $host = parse_url($url, PHP_URL_HOST); $port = parse_url($url, PHP_URL_PORT); if (empty($port)) { switch (parse_url($url, PHP_URL_SCHEME)) { case 'http': $port = 80; break; case 'https': $port = 443; break; } } foreach ($this->rules as $rule) { if ($rule == '*') { return true; } $match = false; list($ruleHost) = explode(':', $rule); list($base) = explode('/', $ruleHost); if (filter_var($base, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { // ip or cidr match if (!isset($ip)) { $ip = gethostbyname($host); } if (strpos($ruleHost, '/') === false) { $match = $ip === $ruleHost; } else { // gethostbyname() failed to resolve $host to an ip, so we assume // it must be proxied to let the proxy's DNS resolve it if ($ip === $host) { $match = false; } else { // match resolved IP against the rule $match = self::inCIDRBlock($ruleHost, $ip); } } } else { // match end of domain $haystack = '.' . trim($host, '.') . '.'; $needle = '.'. trim($ruleHost, '.') .'.'; $match = stripos(strrev($haystack), strrev($needle)) === 0; } // final port check if ($match && strpos($rule, ':') !== false) { list(, $rulePort) = explode(':', $rule); if (!empty($rulePort) && $port != $rulePort) { $match = false; } } if ($match) { return true; } } return false; } /** * Check an IP address against a CIDR * * http://framework.zend.com/svn/framework/extras/incubator/library/ZendX/Whois/Adapter/Cidr.php * * @param string $cidr IPv4 block in CIDR notation * @param string $ip IPv4 address * * @return bool */ private static function inCIDRBlock($cidr, $ip) { // Get the base and the bits from the CIDR list($base, $bits) = explode('/', $cidr); // Now split it up into it's classes list($a, $b, $c, $d) = explode('.', $base); // Now do some bit shifting/switching to convert to ints $i = ($a << 24) + ($b << 16) + ($c << 8) + $d; $mask = $bits == 0 ? 0 : (~0 << (32 - $bits)); // Here's our lowest int $low = $i & $mask; // Here's our highest int $high = $i | (~$mask & 0xFFFFFFFF); // Now split the ip we're checking against up into classes list($a, $b, $c, $d) = explode('.', $ip); // Now convert the ip we're checking against to an int $check = ($a << 24) + ($b << 16) + ($c << 8) + $d; // If the ip is within the range, including highest/lowest values, // then it's within the CIDR range return $check >= $low && $check <= $high; } } composer-1.6.3/src/Composer/Util/Perforce.php000066400000000000000000000413411323436022200211210ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; use Symfony\Component\Process\Process; /** * @author Matt Whittom */ class Perforce { protected $path; protected $p4Depot; protected $p4Client; protected $p4User; protected $p4Password; protected $p4Port; protected $p4Stream; protected $p4ClientSpec; protected $p4DepotType; protected $p4Branch; protected $process; protected $uniquePerforceClientName; protected $windowsFlag; protected $commandResult; protected $io; protected $filesystem; public function __construct($repoConfig, $port, $path, ProcessExecutor $process, $isWindows, IOInterface $io) { $this->windowsFlag = $isWindows; $this->p4Port = $port; $this->initializePath($path); $this->process = $process; $this->initialize($repoConfig); $this->io = $io; } public static function create($repoConfig, $port, $path, ProcessExecutor $process, IOInterface $io) { return new Perforce($repoConfig, $port, $path, $process, Platform::isWindows(), $io); } public static function checkServerExists($url, ProcessExecutor $processExecutor) { $output = null; return 0 === $processExecutor->execute('p4 -p ' . $url . ' info -s', $output); } public function initialize($repoConfig) { $this->uniquePerforceClientName = $this->generateUniquePerforceClientName(); if (!$repoConfig) { return; } if (isset($repoConfig['unique_perforce_client_name'])) { $this->uniquePerforceClientName = $repoConfig['unique_perforce_client_name']; } if (isset($repoConfig['depot'])) { $this->p4Depot = $repoConfig['depot']; } if (isset($repoConfig['branch'])) { $this->p4Branch = $repoConfig['branch']; } if (isset($repoConfig['p4user'])) { $this->p4User = $repoConfig['p4user']; } else { $this->p4User = $this->getP4variable('P4USER'); } if (isset($repoConfig['p4password'])) { $this->p4Password = $repoConfig['p4password']; } } public function initializeDepotAndBranch($depot, $branch) { if (isset($depot)) { $this->p4Depot = $depot; } if (isset($branch)) { $this->p4Branch = $branch; } } public function generateUniquePerforceClientName() { return gethostname() . "_" . time(); } public function cleanupClientSpec() { $client = $this->getClient(); $task = 'client -d ' . $client; $useP4Client = false; $command = $this->generateP4Command($task, $useP4Client); $this->executeCommand($command); $clientSpec = $this->getP4ClientSpec(); $fileSystem = $this->getFilesystem(); $fileSystem->remove($clientSpec); } protected function executeCommand($command) { $this->commandResult = ''; return $this->process->execute($command, $this->commandResult); } public function getClient() { if (!isset($this->p4Client)) { $cleanStreamName = str_replace(array('//', '/', '@'), array('', '_', ''), $this->getStream()); $this->p4Client = 'composer_perforce_' . $this->uniquePerforceClientName . '_' . $cleanStreamName; } return $this->p4Client; } protected function getPath() { return $this->path; } public function initializePath($path) { $this->path = $path; $fs = $this->getFilesystem(); $fs->ensureDirectoryExists($path); } protected function getPort() { return $this->p4Port; } public function setStream($stream) { $this->p4Stream = $stream; $index = strrpos($stream, '/'); //Stream format is //depot/stream, while non-streaming depot is //depot if ($index > 2) { $this->p4DepotType = 'stream'; } } public function isStream() { return (strcmp($this->p4DepotType, 'stream') === 0); } public function getStream() { if (!isset($this->p4Stream)) { if ($this->isStream()) { $this->p4Stream = '//' . $this->p4Depot . '/' . $this->p4Branch; } else { $this->p4Stream = '//' . $this->p4Depot; } } return $this->p4Stream; } public function getStreamWithoutLabel($stream) { $index = strpos($stream, '@'); if ($index === false) { return $stream; } return substr($stream, 0, $index); } public function getP4ClientSpec() { return $this->path . '/' . $this->getClient() . '.p4.spec'; } public function getUser() { return $this->p4User; } public function setUser($user) { $this->p4User = $user; } public function queryP4User() { $this->getUser(); if (strlen($this->p4User) > 0) { return; } $this->p4User = $this->getP4variable('P4USER'); if (strlen($this->p4User) > 0) { return; } $this->p4User = $this->io->ask('Enter P4 User:'); if ($this->windowsFlag) { $command = 'p4 set P4USER=' . $this->p4User; } else { $command = 'export P4USER=' . $this->p4User; } $this->executeCommand($command); } protected function getP4variable($name) { if ($this->windowsFlag) { $command = 'p4 set'; $this->executeCommand($command); $result = trim($this->commandResult); $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { $fields = explode('=', $line); if (strcmp($name, $fields[0]) == 0) { $index = strpos($fields[1], ' '); if ($index === false) { $value = $fields[1]; } else { $value = substr($fields[1], 0, $index); } $value = trim($value); return $value; } } return null; } $command = 'echo $' . $name; $this->executeCommand($command); $result = trim($this->commandResult); return $result; } public function queryP4Password() { if (isset($this->p4Password)) { return $this->p4Password; } $password = $this->getP4variable('P4PASSWD'); if (strlen($password) <= 0) { $password = $this->io->askAndHideAnswer('Enter password for Perforce user ' . $this->getUser() . ': '); } $this->p4Password = $password; return $password; } public function generateP4Command($command, $useClient = true) { $p4Command = 'p4 '; $p4Command = $p4Command . '-u ' . $this->getUser() . ' '; if ($useClient) { $p4Command = $p4Command . '-c ' . $this->getClient() . ' '; } $p4Command = $p4Command . '-p ' . $this->getPort() . ' ' . $command; return $p4Command; } public function isLoggedIn() { $command = $this->generateP4Command('login -s', false); $exitCode = $this->executeCommand($command); if ($exitCode) { $errorOutput = $this->process->getErrorOutput(); $index = strpos($errorOutput, $this->getUser()); if ($index === false) { $index = strpos($errorOutput, 'p4'); if ($index === false) { return false; } throw new \Exception('p4 command not found in path: ' . $errorOutput); } throw new \Exception('Invalid user name: ' . $this->getUser()); } return true; } public function connectClient() { $p4CreateClientCommand = $this->generateP4Command( 'client -i < ' . str_replace(" ", "\\ ", $this->getP4ClientSpec()) ); $this->executeCommand($p4CreateClientCommand); } public function syncCodeBase($sourceReference) { $prevDir = getcwd(); chdir($this->path); $p4SyncCommand = $this->generateP4Command('sync -f '); if (null !== $sourceReference) { $p4SyncCommand = $p4SyncCommand . '@' . $sourceReference; } $this->executeCommand($p4SyncCommand); chdir($prevDir); } public function writeClientSpecToFile($spec) { fwrite($spec, 'Client: ' . $this->getClient() . PHP_EOL . PHP_EOL); fwrite($spec, 'Update: ' . date('Y/m/d H:i:s') . PHP_EOL . PHP_EOL); fwrite($spec, 'Access: ' . date('Y/m/d H:i:s') . PHP_EOL); fwrite($spec, 'Owner: ' . $this->getUser() . PHP_EOL . PHP_EOL); fwrite($spec, 'Description:' . PHP_EOL); fwrite($spec, ' Created by ' . $this->getUser() . ' from composer.' . PHP_EOL . PHP_EOL); fwrite($spec, 'Root: ' . $this->getPath() . PHP_EOL . PHP_EOL); fwrite($spec, 'Options: noallwrite noclobber nocompress unlocked modtime rmdir' . PHP_EOL . PHP_EOL); fwrite($spec, 'SubmitOptions: revertunchanged' . PHP_EOL . PHP_EOL); fwrite($spec, 'LineEnd: local' . PHP_EOL . PHP_EOL); if ($this->isStream()) { fwrite($spec, 'Stream:' . PHP_EOL); fwrite($spec, ' ' . $this->getStreamWithoutLabel($this->p4Stream) . PHP_EOL); } else { fwrite( $spec, 'View: ' . $this->getStream() . '/... //' . $this->getClient() . '/... ' . PHP_EOL ); } } public function writeP4ClientSpec() { $clientSpec = $this->getP4ClientSpec(); $spec = fopen($clientSpec, 'w'); try { $this->writeClientSpecToFile($spec); } catch (\Exception $e) { fclose($spec); throw $e; } fclose($spec); } protected function read($pipe, $name) { if (feof($pipe)) { return; } $line = fgets($pipe); while ($line !== false) { $line = fgets($pipe); } return; } public function windowsLogin($password) { $command = $this->generateP4Command(' login -a'); $process = new Process($command, null, null, $password); return $process->run(); } public function p4Login() { $this->queryP4User(); if (!$this->isLoggedIn()) { $password = $this->queryP4Password(); if ($this->windowsFlag) { $this->windowsLogin($password); } else { $command = 'echo ' . $password . ' | ' . $this->generateP4Command(' login -a', false); $exitCode = $this->executeCommand($command); $result = trim($this->commandResult); if ($exitCode) { throw new \Exception("Error logging in:" . $this->process->getErrorOutput()); } } } } public function getComposerInformation($identifier) { $composerFileContent = $this->getFileContent('composer.json', $identifier); if (!$composerFileContent) { return; } return json_decode($composerFileContent, true); } public function getFileContent($file, $identifier) { $path = $this->getFilePath($file, $identifier); $command = $this->generateP4Command(' print ' . $path); $this->executeCommand($command); $result = $this->commandResult; if (!trim($result)) { return null; } return $result; } public function getFilePath($file, $identifier) { $index = strpos($identifier, '@'); if ($index === false) { $path = $identifier. '/' . $file; return $path; } $path = substr($identifier, 0, $index) . '/' . $file . substr($identifier, $index); $command = $this->generateP4Command(' files ' . $path, false); $this->executeCommand($command); $result = $this->commandResult; $index2 = strpos($result, 'no such file(s).'); if ($index2 === false) { $index3 = strpos($result, 'change'); if ($index3 !== false) { $phrase = trim(substr($result, $index3)); $fields = explode(' ', $phrase); return substr($identifier, 0, $index) . '/' . $file . '@' . $fields[1]; } } return null; } public function getBranches() { $possibleBranches = array(); if (!$this->isStream()) { $possibleBranches[$this->p4Branch] = $this->getStream(); } else { $command = $this->generateP4Command('streams //' . $this->p4Depot . '/...'); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { $resBits = explode(' ', $line); if (count($resBits) > 4) { $branch = preg_replace('/[^A-Za-z0-9 ]/', '', $resBits[4]); $possibleBranches[$branch] = $resBits[1]; } } } $command = $this->generateP4Command('changes '. $this->getStream() . '/...', false); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); $lastCommit = $resArray[0]; $lastCommitArr = explode(' ', $lastCommit); $lastCommitNum = $lastCommitArr[1]; $branches = array('master' => $possibleBranches[$this->p4Branch] . '@'. $lastCommitNum); return $branches; } public function getTags() { $command = $this->generateP4Command('labels'); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); $tags = array(); foreach ($resArray as $line) { $index = strpos($line, 'Label'); if (!($index === false)) { $fields = explode(' ', $line); $tags[$fields[1]] = $this->getStream() . '@' . $fields[1]; } } return $tags; } public function checkStream() { $command = $this->generateP4Command('depots', false); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { $index = strpos($line, 'Depot'); if (!($index === false)) { $fields = explode(' ', $line); if (strcmp($this->p4Depot, $fields[1]) === 0) { $this->p4DepotType = $fields[3]; return $this->isStream(); } } } return false; } /** * @param $reference * @return mixed|null */ protected function getChangeList($reference) { $index = strpos($reference, '@'); if ($index === false) { return null; } $label = substr($reference, $index); $command = $this->generateP4Command(' changes -m1 ' . $label); $this->executeCommand($command); $changes = $this->commandResult; if (strpos($changes, 'Change') !== 0) { return null; } $fields = explode(' ', $changes); return $fields[1]; } /** * @param $fromReference * @param $toReference * @return mixed|null */ public function getCommitLogs($fromReference, $toReference) { $fromChangeList = $this->getChangeList($fromReference); if ($fromChangeList === null) { return null; } $toChangeList = $this->getChangeList($toReference); if ($toChangeList === null) { return null; } $index = strpos($fromReference, '@'); $main = substr($fromReference, 0, $index) . '/...'; $command = $this->generateP4Command('filelog ' . $main . '@' . $fromChangeList. ',' . $toChangeList); $this->executeCommand($command); return $this->commandResult; } public function getFilesystem() { if (empty($this->filesystem)) { $this->filesystem = new Filesystem($this->process); } return $this->filesystem; } public function setFilesystem(Filesystem $fs) { $this->filesystem = $fs; } } composer-1.6.3/src/Composer/Util/Platform.php000066400000000000000000000050501323436022200211350ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * Platform helper for uniform platform-specific tests. * * @author Niels Keurentjes */ class Platform { /** * Parses tildes and environment variables in paths. * * @param string $path * @return string */ public static function expandPath($path) { if (preg_match('#^~[\\/]#', $path)) { return self::getUserDirectory() . substr($path, 1); } return preg_replace_callback('#^(\$|(?P%))(?P\w++)(?(percent)%)(?P.*)#', function ($matches) { // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons if (Platform::isWindows() && $matches['var'] == 'HOME') { return (getenv('HOME') ?: getenv('USERPROFILE')) . $matches['path']; } return getenv($matches['var']) . $matches['path']; }, $path); } /** * @throws \RuntimeException If the user home could not reliably be determined * @return string The formal user home as detected from environment parameters */ public static function getUserDirectory() { if (false !== ($home = getenv('HOME'))) { return $home; } if (self::isWindows() && false !== ($home = getenv('USERPROFILE'))) { return $home; } if (function_exists('posix_getuid') && function_exists('posix_getpwuid')) { $info = posix_getpwuid(posix_getuid()); return $info['dir']; } throw new \RuntimeException('Could not determine user directory'); } /** * @return bool Whether the host machine is running a Windows OS */ public static function isWindows() { return defined('PHP_WINDOWS_VERSION_BUILD'); } /** * @param string $str * @return int return a guaranteed binary length of the string, regardless of silly mbstring configs */ public static function strlen($str) { static $useMbString = null; if (null === $useMbString) { $useMbString = function_exists('mb_strlen') && ini_get('mbstring.func_overload'); } if ($useMbString) { return mb_strlen($str, '8bit'); } return strlen($str); } } composer-1.6.3/src/Composer/Util/ProcessExecutor.php000066400000000000000000000127711323436022200225160ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; use Symfony\Component\Process\Process; use Symfony\Component\Process\ProcessUtils; /** * @author Robert Schönthal */ class ProcessExecutor { protected static $timeout = 300; protected $captureOutput; protected $errorOutput; protected $io; public function __construct(IOInterface $io = null) { $this->io = $io; } /** * runs a process on the commandline * * @param string $command the command to execute * @param mixed $output the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler * @param string $cwd the working directory * @return int statuscode */ public function execute($command, &$output = null, $cwd = null) { if ($this->io && $this->io->isDebug()) { $safeCommand = preg_replace_callback('{://(?P[^:/\s]+):(?P[^@\s/]+)@}i', function ($m) { if (preg_match('{^[a-f0-9]{12,}$}', $m['user'])) { return '://***:***@'; } return '://'.$m['user'].':***@'; }, $command); $this->io->writeError('Executing command ('.($cwd ?: 'CWD').'): '.$safeCommand); } // make sure that null translate to the proper directory in case the dir is a symlink // and we call a git command, because msysgit does not handle symlinks properly if (null === $cwd && Platform::isWindows() && false !== strpos($command, 'git') && getcwd()) { $cwd = realpath(getcwd()); } $this->captureOutput = count(func_get_args()) > 1; $this->errorOutput = null; $process = new Process($command, $cwd, null, null, static::getTimeout()); $callback = is_callable($output) ? $output : array($this, 'outputHandler'); $process->run($callback); if ($this->captureOutput && !is_callable($output)) { $output = $process->getOutput(); } $this->errorOutput = $process->getErrorOutput(); return $process->getExitCode(); } public function splitLines($output) { $output = trim($output); return ((string) $output === '') ? array() : preg_split('{\r?\n}', $output); } /** * Get any error output from the last command * * @return string */ public function getErrorOutput() { return $this->errorOutput; } public function outputHandler($type, $buffer) { if ($this->captureOutput) { return; } if (null === $this->io) { echo $buffer; return; } if (Process::ERR === $type) { $this->io->writeError($buffer, false); } else { $this->io->write($buffer, false); } } public static function getTimeout() { return static::$timeout; } public static function setTimeout($timeout) { static::$timeout = $timeout; } /** * Escapes a string to be used as a shell argument. * * @param string $argument The argument that will be escaped * * @return string The escaped argument */ public static function escape($argument) { if (method_exists('Symfony\Component\Process\ProcessUtils', 'escapeArgument')) { return ProcessUtils::escapeArgument($argument); } return self::escapeArgument($argument); } /** * Copy of ProcessUtils::escapeArgument() that is removed in Symfony 4. * * @param string $argument * * @return string */ private static function escapeArgument($argument) { //Fix for PHP bug #43784 escapeshellarg removes % from given string //Fix for PHP bug #49446 escapeshellarg doesn't work on Windows //@see https://bugs.php.net/bug.php?id=43784 //@see https://bugs.php.net/bug.php?id=49446 if ('\\' === DIRECTORY_SEPARATOR) { if ('' === $argument) { return escapeshellarg($argument); } $escapedArgument = ''; $quote = false; foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { if ('"' === $part) { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy($part, '%')) { // Avoid environment variable expansion $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%'; } else { // escape trailing backslash if ('\\' === substr($part, -1)) { $part .= '\\'; } $quote = true; $escapedArgument .= $part; } } if ($quote) { $escapedArgument = '"'.$escapedArgument.'"'; } return $escapedArgument; } return "'".str_replace("'", "'\\''", $argument)."'"; } private static function isSurroundedBy($arg, $char) { return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1]; } } composer-1.6.3/src/Composer/Util/RemoteFilesystem.php000066400000000000000000001222571323436022200226620ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; use Composer\CaBundle\CaBundle; use Psr\Log\LoggerInterface; /** * @author François Pluchino * @author Jordi Boggiano * @author Nils Adermann */ class RemoteFilesystem { private $io; private $config; private $scheme; private $bytesMax; private $originUrl; private $fileUrl; private $fileName; private $retry; private $progress; private $lastProgress; private $options = array(); private $peerCertificateMap = array(); private $disableTls = false; private $retryAuthFailure; private $lastHeaders; private $storeAuth; private $degradedMode = false; private $redirects; private $maxRedirects = 20; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The config * @param array $options The options * @param bool $disableTls */ public function __construct(IOInterface $io, Config $config = null, array $options = array(), $disableTls = false) { $this->io = $io; // Setup TLS options // The cafile option can be set via config.json if ($disableTls === false) { $this->options = $this->getTlsDefaults($options); } else { $this->disableTls = true; } // handle the other externally set options normally. $this->options = array_replace_recursive($this->options, $options); $this->config = $config; } /** * Copy the remote file in local. * * @param string $originUrl The origin URL * @param string $fileUrl The file URL * @param string $fileName the local filename * @param bool $progress Display the progression * @param array $options Additional context options * * @return bool true */ public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array()) { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); } /** * Get the content. * * @param string $originUrl The origin URL * @param string $fileUrl The file URL * @param bool $progress Display the progression * @param array $options Additional context options * * @return bool|string The content */ public function getContents($originUrl, $fileUrl, $progress = true, $options = array()) { return $this->get($originUrl, $fileUrl, $options, null, $progress); } /** * Retrieve the options set in the constructor * * @return array Options */ public function getOptions() { return $this->options; } /** * Merges new options * * @return array $options */ public function setOptions(array $options) { $this->options = array_replace_recursive($this->options, $options); } public function isTlsDisabled() { return $this->disableTls === true; } /** * Returns the headers of the last request * * @return array */ public function getLastHeaders() { return $this->lastHeaders; } /** * @param array $headers array of returned headers like from getLastHeaders() * @param string $name header name (case insensitive) * @return string|null */ public function findHeaderValue(array $headers, $name) { $value = null; foreach ($headers as $header) { if (preg_match('{^'.$name.':\s*(.+?)\s*$}i', $header, $match)) { $value = $match[1]; } elseif (preg_match('{^HTTP/}i', $header)) { // In case of redirects, http_response_headers contains the headers of all responses // so we reset the flag when a new response is being parsed as we are only interested in the last response $value = null; } } return $value; } /** * @param array $headers array of returned headers like from getLastHeaders() * @return int|null */ public function findStatusCode(array $headers) { $value = null; foreach ($headers as $header) { if (preg_match('{^HTTP/\S+ (\d+)}i', $header, $match)) { // In case of redirects, http_response_headers contains the headers of all responses // so we can not return directly and need to keep iterating $value = (int) $match[1]; } } return $value; } /** * Get file content or copy action. * * @param string $originUrl The origin URL * @param string $fileUrl The file URL * @param array $additionalOptions context options * @param string $fileName the local filename * @param bool $progress Display the progression * * @throws TransportException|\Exception * @throws TransportException When the file could not be downloaded * * @return bool|string */ protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true) { if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) { $originUrl = 'github.com'; } // Gitlab can be installed in a non-root context (i.e. gitlab.com/foo). When downloading archives the originUrl // is the host without the path, so we look for the registered gitlab-domains matching the host here if ( $this->config && is_array($this->config->get('gitlab-domains')) && false === strpos($originUrl, '/') && !in_array($originUrl, $this->config->get('gitlab-domains')) ) { foreach ($this->config->get('gitlab-domains') as $gitlabDomain) { if (0 === strpos($gitlabDomain, $originUrl)) { $originUrl = $gitlabDomain; break; } } unset($gitlabDomain); } $this->scheme = parse_url($fileUrl, PHP_URL_SCHEME); $this->bytesMax = 0; $this->originUrl = $originUrl; $this->fileUrl = $fileUrl; $this->fileName = $fileName; $this->progress = $progress; $this->lastProgress = null; $this->retryAuthFailure = true; $this->lastHeaders = array(); $this->redirects = 1; // The first request counts. // capture username/password from URL if there is one if (preg_match('{^https?://([^:/]+):([^@/]+)@([^/]+)}i', $fileUrl, $match)) { $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2])); } $tempAdditionalOptions = $additionalOptions; if (isset($tempAdditionalOptions['retry-auth-failure'])) { $this->retryAuthFailure = (bool) $tempAdditionalOptions['retry-auth-failure']; unset($tempAdditionalOptions['retry-auth-failure']); } $isRedirect = false; if (isset($tempAdditionalOptions['redirects'])) { $this->redirects = $tempAdditionalOptions['redirects']; $isRedirect = true; unset($tempAdditionalOptions['redirects']); } $options = $this->getOptionsForUrl($originUrl, $tempAdditionalOptions); unset($tempAdditionalOptions); $origFileUrl = $fileUrl; if (isset($options['github-token'])) { // only add the access_token if it is actually a github URL (in case we were redirected to S3) if (preg_match('{^https?://([a-z0-9-]+\.)*github\.com/}', $fileUrl)) { $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token']; } unset($options['github-token']); } if (isset($options['gitlab-token'])) { $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token']; unset($options['gitlab-token']); } if (isset($options['http'])) { $options['http']['ignore_errors'] = true; } if ($this->degradedMode && substr($fileUrl, 0, 21) === 'http://packagist.org/') { // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol $fileUrl = 'http://' . gethostbyname('packagist.org') . substr($fileUrl, 20); $degradedPackagist = true; } $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet'))); $actualContextOptions = stream_context_get_options($ctx); $usingProxy = !empty($actualContextOptions['http']['proxy']) ? ' using proxy ' . $actualContextOptions['http']['proxy'] : ''; $this->io->writeError((substr($origFileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $origFileUrl . $usingProxy, true, IOInterface::DEBUG); unset($origFileUrl, $actualContextOptions); // Check for secure HTTP, but allow insecure Packagist calls to $hashed providers as file integrity is verified with sha256 if ((substr($fileUrl, 0, 23) !== 'http://packagist.org/p/' || (false === strpos($fileUrl, '$') && false === strpos($fileUrl, '%24'))) && empty($degradedPackagist) && $this->config) { $this->config->prohibitUrlByConfig($fileUrl, $this->io); } if ($this->progress && !$isRedirect) { $this->io->writeError("Downloading (connecting...)", false); } $errorMessage = ''; $errorCode = 0; $result = false; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg); }); try { $result = file_get_contents($fileUrl, false, $ctx); $contentLength = !empty($http_response_header[0]) ? $this->findHeaderValue($http_response_header, 'content-length') : null; if ($contentLength && Platform::strlen($result) < $contentLength) { // alas, this is not possible via the stream callback because STREAM_NOTIFY_COMPLETED is documented, but not implemented anywhere in PHP $e = new TransportException('Content-Length mismatch, received '.Platform::strlen($result).' bytes out of the expected '.$contentLength); $e->setHeaders($http_response_header); $e->setStatusCode($this->findStatusCode($http_response_header)); $e->setResponse($result); $this->io->writeError('Content-Length mismatch, received '.Platform::strlen($result).' out of '.$contentLength.' bytes: (' . base64_encode($result).')', true, IOInterface::DEBUG); throw $e; } if (PHP_VERSION_ID < 50600 && !empty($options['ssl']['peer_fingerprint'])) { // Emulate fingerprint validation on PHP < 5.6 $params = stream_context_get_params($ctx); $expectedPeerFingerprint = $options['ssl']['peer_fingerprint']; $peerFingerprint = TlsHelper::getCertificateFingerprint($params['options']['ssl']['peer_certificate']); // Constant time compare??! if ($expectedPeerFingerprint !== $peerFingerprint) { throw new TransportException('Peer fingerprint did not match'); } } } catch (\Exception $e) { if ($e instanceof TransportException && !empty($http_response_header[0])) { $e->setHeaders($http_response_header); $e->setStatusCode($this->findStatusCode($http_response_header)); } if ($e instanceof TransportException && $result !== false) { $e->setResponse($result); } $result = false; } if ($errorMessage && !ini_get('allow_url_fopen')) { $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')'; } restore_error_handler(); if (isset($e) && !$this->retry) { if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) { $this->degradedMode = true; $this->io->writeError(''); $this->io->writeError(array( ''.$e->getMessage().'', 'Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info', )); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } throw $e; } $statusCode = null; $contentType = null; if (!empty($http_response_header[0])) { $statusCode = $this->findStatusCode($http_response_header); $contentType = $this->findHeaderValue($http_response_header, 'content-type'); } // check for bitbucket login page asking to authenticate if ($originUrl === 'bitbucket.org' && !$this->isPublicBitBucketDownload($fileUrl) && substr($fileUrl, -4) === '.zip' && $contentType && preg_match('{^text/html\b}i', $contentType) ) { $result = false; if ($this->retryAuthFailure) { $this->promptAuthAndRetry(401); } } // check for gitlab 404 when downloading archives if ($statusCode === 404 && $this->config && in_array($originUrl, $this->config->get('gitlab-domains'), true) && false !== strpos($fileUrl, 'archive.zip') ) { $result = false; if ($this->retryAuthFailure) { $this->promptAuthAndRetry(401); } } // handle 3xx redirects, 304 Not Modified is excluded $hasFollowedRedirect = false; if ($statusCode >= 300 && $statusCode <= 399 && $statusCode !== 304 && $this->redirects < $this->maxRedirects) { $hasFollowedRedirect = true; $result = $this->handleRedirect($http_response_header, $additionalOptions, $result); } // fail 4xx and 5xx responses and capture the response if ($statusCode && $statusCode >= 400 && $statusCode <= 599) { if (!$this->retry) { if ($this->progress && !$this->retry && !$isRedirect) { $this->io->overwriteError("Downloading (failed)", false); } $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $statusCode); $e->setHeaders($http_response_header); $e->setResponse($result); $e->setStatusCode($statusCode); throw $e; } $result = false; } if ($this->progress && !$this->retry && !$isRedirect) { $this->io->overwriteError("Downloading (".($result === false ? 'failed' : '100%').")", false); } // decode gzip if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http' && !$hasFollowedRedirect) { $contentEncoding = $this->findHeaderValue($http_response_header, 'content-encoding'); $decode = $contentEncoding && 'gzip' === strtolower($contentEncoding); if ($decode) { try { if (PHP_VERSION_ID >= 50400) { $result = zlib_decode($result); } else { // work around issue with gzuncompress & co that do not work with all gzip checksums $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result)); } if (!$result) { throw new TransportException('Failed to decode zlib stream'); } } catch (\Exception $e) { if ($this->degradedMode) { throw $e; } $this->degradedMode = true; $this->io->writeError(array( '', 'Failed to decode response: '.$e->getMessage().'', 'Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info', )); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } } } // handle copy command if download was successful if (false !== $result && null !== $fileName && !$isRedirect) { if ('' === $result) { throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response'); } $errorMessage = ''; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg); }); $result = (bool) file_put_contents($fileName, $result); restore_error_handler(); if (false === $result) { throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage); } } // Handle SSL cert match issues if (false === $result && false !== strpos($errorMessage, 'Peer certificate') && PHP_VERSION_ID < 50600) { // Certificate name error, PHP doesn't support subjectAltName on PHP < 5.6 // The procedure to handle sAN for older PHP's is: // // 1. Open socket to remote server and fetch certificate (disabling peer // validation because PHP errors without giving up the certificate.) // // 2. Verifying the domain in the URL against the names in the sAN field. // If there is a match record the authority [host/port], certificate // common name, and certificate fingerprint. // // 3. Retry the original request but changing the CN_match parameter to // the common name extracted from the certificate in step 2. // // 4. To prevent any attempt at being hoodwinked by switching the // certificate between steps 2 and 3 the fingerprint of the certificate // presented in step 3 is compared against the one recorded in step 2. if (CaBundle::isOpensslParseSafe()) { $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options); if ($certDetails) { $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails; $this->retry = true; } } else { $this->io->writeError(''); $this->io->writeError(sprintf( 'Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.', PHP_VERSION )); } } if ($this->retry) { $this->retry = false; $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); if ($this->storeAuth && $this->config) { $authHelper = new AuthHelper($this->io, $this->config); $authHelper->storeAuth($this->originUrl, $this->storeAuth); $this->storeAuth = false; } return $result; } if (false === $result) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode); if (!empty($http_response_header[0])) { $e->setHeaders($http_response_header); } if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) { $this->degradedMode = true; $this->io->writeError(''); $this->io->writeError(array( ''.$e->getMessage().'', 'Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info', )); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } throw $e; } if (!empty($http_response_header[0])) { $this->lastHeaders = $http_response_header; } return $result; } /** * Get notification action. * * @param int $notificationCode The notification code * @param int $severity The severity level * @param string $message The message * @param int $messageCode The message code * @param int $bytesTransferred The loaded size * @param int $bytesMax The total size * @throws TransportException */ protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: if (400 === $messageCode) { // This might happen if your host is secured by ssl client certificate authentication // but you do not send an appropriate certificate throw new TransportException("The '" . $this->fileUrl . "' URL could not be accessed: " . $message, $messageCode); } // intentional fallthrough to the next case as the notificationCode // isn't always consistent and we should inspect the messageCode for 401s case STREAM_NOTIFY_AUTH_REQUIRED: if (401 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode); } break; case STREAM_NOTIFY_AUTH_RESULT: if (403 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode, $message); } break; case STREAM_NOTIFY_FILE_SIZE_IS: $this->bytesMax = $bytesMax; break; case STREAM_NOTIFY_PROGRESS: if ($this->bytesMax > 0 && $this->progress) { $progression = min(100, round($bytesTransferred / $this->bytesMax * 100)); if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) { $this->lastProgress = $progression; $this->io->overwriteError("Downloading ($progression%)", false); } } break; default: break; } } protected function promptAuthAndRetry($httpStatus, $reason = null) { if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) { $message = "\n".'Could not fetch '.$this->fileUrl.', please create a GitHub OAuth token '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit'); $gitHubUtil = new GitHub($this->io, $this->config, null); if (!$gitHubUtil->authorizeOAuth($this->originUrl) && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message)) ) { throw new TransportException('Could not authenticate against '.$this->originUrl, 401); } } elseif ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) { $message = "\n".'Could not fetch '.$this->fileUrl.', enter your ' . $this->originUrl . ' credentials ' .($httpStatus === 401 ? 'to access private repos' : 'to go over the API rate limit'); $gitLabUtil = new GitLab($this->io, $this->config, null); if ($this->io->hasAuthentication($this->originUrl) && ($auth = $this->io->getAuthentication($this->originUrl)) && $auth['password'] === 'private-token') { throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus); } if (!$gitLabUtil->authorizeOAuth($this->originUrl) && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, $message)) ) { throw new TransportException('Could not authenticate against '.$this->originUrl, 401); } } elseif ($this->config && $this->originUrl === 'bitbucket.org') { $askForOAuthToken = true; if ($this->io->hasAuthentication($this->originUrl)) { $auth = $this->io->getAuthentication($this->originUrl); if ($auth['username'] !== 'x-token-auth') { $bitbucketUtil = new Bitbucket($this->io, $this->config); $accessToken = $bitbucketUtil->requestToken($this->originUrl, $auth['username'], $auth['password']); if (!empty($accessToken)) { $this->io->setAuthentication($this->originUrl, 'x-token-auth', $accessToken); $askForOAuthToken = false; } } else { throw new TransportException('Could not authenticate against ' . $this->originUrl, 401); } } if ($askForOAuthToken) { $message = "\n".'Could not fetch ' . $this->fileUrl . ', please create a bitbucket OAuth token to ' . (($httpStatus === 401 || $httpStatus === 403) ? 'access private repos' : 'go over the API rate limit'); $bitBucketUtil = new Bitbucket($this->io, $this->config); if (! $bitBucketUtil->authorizeOAuth($this->originUrl) && (! $this->io->isInteractive() || !$bitBucketUtil->authorizeOAuthInteractively($this->originUrl, $message)) ) { throw new TransportException('Could not authenticate against ' . $this->originUrl, 401); } } } else { // 404s are only handled for github if ($httpStatus === 404) { return; } // fail if the console is not interactive if (!$this->io->isInteractive()) { if ($httpStatus === 401) { $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate"; } if ($httpStatus === 403) { $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason; } throw new TransportException($message, $httpStatus); } // fail if we already have auth if ($this->io->hasAuthentication($this->originUrl)) { throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus); } $this->io->overwriteError(''); $this->io->writeError(' Authentication required ('.parse_url($this->fileUrl, PHP_URL_HOST).'):'); $username = $this->io->ask(' Username: '); $password = $this->io->askAndHideAnswer(' Password: '); $this->io->setAuthentication($this->originUrl, $username, $password); $this->storeAuth = $this->config->get('store-auths'); } $this->retry = true; throw new TransportException('RETRY'); } protected function getOptionsForUrl($originUrl, $additionalOptions) { $tlsOptions = array(); // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN if ($this->disableTls === false && PHP_VERSION_ID < 50600 && !stream_is_local($this->fileUrl)) { $host = parse_url($this->fileUrl, PHP_URL_HOST); if (PHP_VERSION_ID < 50304) { // PHP < 5.3.4 does not support follow_location, for those people // do some really nasty hard coded transformations. These will // still breakdown if the site redirects to a domain we don't // expect. if ($host === 'github.com' || $host === 'api.github.com') { $host = '*.github.com'; } } $tlsOptions['ssl']['CN_match'] = $host; $tlsOptions['ssl']['SNI_server_name'] = $host; $urlAuthority = $this->getUrlAuthority($this->fileUrl); if (isset($this->peerCertificateMap[$urlAuthority])) { // Handle subjectAltName on lesser PHP's. $certMap = $this->peerCertificateMap[$urlAuthority]; $this->io->writeError('', true, IOInterface::DEBUG); $this->io->writeError(sprintf( 'Using %s as CN for subjectAltName enabled host %s', $certMap['cn'], $urlAuthority ), true, IOInterface::DEBUG); $tlsOptions['ssl']['CN_match'] = $certMap['cn']; $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp']; } } $headers = array(); if (extension_loaded('zlib')) { $headers[] = 'Accept-Encoding: gzip'; } $options = array_replace_recursive($this->options, $tlsOptions, $additionalOptions); if (!$this->degradedMode) { // degraded mode disables HTTP/1.1 which causes issues with some bad // proxies/software due to the use of chunked encoding $options['http']['protocol_version'] = 1.1; $headers[] = 'Connection: close'; } if ($this->io->hasAuthentication($originUrl)) { $auth = $this->io->getAuthentication($originUrl); if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) { $options['github-token'] = $auth['username']; } elseif ($this->config && in_array($originUrl, $this->config->get('gitlab-domains'), true)) { if ($auth['password'] === 'oauth2') { $headers[] = 'Authorization: Bearer '.$auth['username']; } elseif ($auth['password'] === 'private-token') { $headers[] = 'PRIVATE-TOKEN: '.$auth['username']; } } elseif ('bitbucket.org' === $originUrl && $this->fileUrl !== Bitbucket::OAUTH2_ACCESS_TOKEN_URL && 'x-token-auth' === $auth['username'] ) { if (!$this->isPublicBitBucketDownload($this->fileUrl)) { $headers[] = 'Authorization: Bearer ' . $auth['password']; } } else { $authStr = base64_encode($auth['username'] . ':' . $auth['password']); $headers[] = 'Authorization: Basic '.$authStr; } } $options['http']['follow_location'] = 0; if (isset($options['http']['header']) && !is_array($options['http']['header'])) { $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n")); } foreach ($headers as $header) { $options['http']['header'][] = $header; } return $options; } private function handleRedirect(array $http_response_header, array $additionalOptions, $result) { if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) { if (parse_url($locationHeader, PHP_URL_SCHEME)) { // Absolute URL; e.g. https://example.com/composer $targetUrl = $locationHeader; } elseif (parse_url($locationHeader, PHP_URL_HOST)) { // Scheme relative; e.g. //example.com/foo $targetUrl = $this->scheme.':'.$locationHeader; } elseif ('/' === $locationHeader[0]) { // Absolute path; e.g. /foo $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); // Replace path using hostname as an anchor. $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); } else { // Relative path; e.g. foo // This actually differs from PHP which seems to add duplicate slashes. $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl); } } if (!empty($targetUrl)) { $this->redirects++; $this->io->writeError('', true, IOInterface::DEBUG); $this->io->writeError(sprintf('Following redirect (%u) %s', $this->redirects, $targetUrl), true, IOInterface::DEBUG); $additionalOptions['redirects'] = $this->redirects; return $this->get(parse_url($targetUrl, PHP_URL_HOST), $targetUrl, $additionalOptions, $this->fileName, $this->progress); } if (!$this->retry) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')'); $e->setHeaders($http_response_header); $e->setResponse($result); throw $e; } return false; } /** * @param array $options * * @return array */ private function getTlsDefaults(array $options) { $ciphers = implode(':', array( 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'DHE-RSA-AES128-GCM-SHA256', 'DHE-DSS-AES128-GCM-SHA256', 'kEDH+AESGCM', 'ECDHE-RSA-AES128-SHA256', 'ECDHE-ECDSA-AES128-SHA256', 'ECDHE-RSA-AES128-SHA', 'ECDHE-ECDSA-AES128-SHA', 'ECDHE-RSA-AES256-SHA384', 'ECDHE-ECDSA-AES256-SHA384', 'ECDHE-RSA-AES256-SHA', 'ECDHE-ECDSA-AES256-SHA', 'DHE-RSA-AES128-SHA256', 'DHE-RSA-AES128-SHA', 'DHE-DSS-AES128-SHA256', 'DHE-RSA-AES256-SHA256', 'DHE-DSS-AES256-SHA', 'DHE-RSA-AES256-SHA', 'AES128-GCM-SHA256', 'AES256-GCM-SHA384', 'AES128-SHA256', 'AES256-SHA256', 'AES128-SHA', 'AES256-SHA', 'AES', 'CAMELLIA', 'DES-CBC3-SHA', '!aNULL', '!eNULL', '!EXPORT', '!DES', '!RC4', '!MD5', '!PSK', '!aECDH', '!EDH-DSS-DES-CBC3-SHA', '!EDH-RSA-DES-CBC3-SHA', '!KRB5-DES-CBC3-SHA', )); /** * CN_match and SNI_server_name are only known once a URL is passed. * They will be set in the getOptionsForUrl() method which receives a URL. * * cafile or capath can be overridden by passing in those options to constructor. */ $defaults = array( 'ssl' => array( 'ciphers' => $ciphers, 'verify_peer' => true, 'verify_depth' => 7, 'SNI_enabled' => true, 'capture_peer_cert' => true, ), ); if (isset($options['ssl'])) { $defaults['ssl'] = array_replace_recursive($defaults['ssl'], $options['ssl']); } $caBundleLogger = $this->io instanceof LoggerInterface ? $this->io : null; /** * Attempt to find a local cafile or throw an exception if none pre-set * The user may go download one if this occurs. */ if (!isset($defaults['ssl']['cafile']) && !isset($defaults['ssl']['capath'])) { $result = CaBundle::getSystemCaRootBundlePath($caBundleLogger); if (is_dir($result)) { $defaults['ssl']['capath'] = $result; } else { $defaults['ssl']['cafile'] = $result; } } if (isset($defaults['ssl']['cafile']) && (!is_readable($defaults['ssl']['cafile']) || !CaBundle::validateCaFile($defaults['ssl']['cafile'], $caBundleLogger))) { throw new TransportException('The configured cafile was not valid or could not be read.'); } if (isset($defaults['ssl']['capath']) && (!is_dir($defaults['ssl']['capath']) || !is_readable($defaults['ssl']['capath']))) { throw new TransportException('The configured capath was not valid or could not be read.'); } /** * Disable TLS compression to prevent CRIME attacks where supported. */ if (PHP_VERSION_ID >= 50413) { $defaults['ssl']['disable_compression'] = true; } return $defaults; } /** * Fetch certificate common name and fingerprint for validation of SAN. * * @todo Remove when PHP 5.6 is minimum supported version. */ private function getCertificateCnAndFp($url, $options) { if (PHP_VERSION_ID >= 50600) { throw new \BadMethodCallException(sprintf( '%s must not be used on PHP >= 5.6', __METHOD__ )); } $context = StreamContextFactory::getContext($url, $options, array('options' => array( 'ssl' => array( 'capture_peer_cert' => true, 'verify_peer' => false, // Yes this is fucking insane! But PHP is lame. ), ), )); // Ideally this would just use stream_socket_client() to avoid sending a // HTTP request but that does not capture the certificate. if (false === $handle = @fopen($url, 'rb', false, $context)) { return; } // Close non authenticated connection without reading any content. fclose($handle); $handle = null; $params = stream_context_get_params($context); if (!empty($params['options']['ssl']['peer_certificate'])) { $peerCertificate = $params['options']['ssl']['peer_certificate']; if (TlsHelper::checkCertificateHost($peerCertificate, parse_url($url, PHP_URL_HOST), $commonName)) { return array( 'cn' => $commonName, 'fp' => TlsHelper::getCertificateFingerprint($peerCertificate), ); } } } private function getUrlAuthority($url) { $defaultPorts = array( 'ftp' => 21, 'http' => 80, 'https' => 443, 'ssh2.sftp' => 22, 'ssh2.scp' => 22, ); $scheme = parse_url($url, PHP_URL_SCHEME); if (!isset($defaultPorts[$scheme])) { throw new \InvalidArgumentException(sprintf( 'Could not get default port for unknown scheme: %s', $scheme )); } $defaultPort = $defaultPorts[$scheme]; $port = parse_url($url, PHP_URL_PORT) ?: $defaultPort; return parse_url($url, PHP_URL_HOST).':'.$port; } /** * @link https://github.com/composer/composer/issues/5584 * * @param string $urlToBitBucketFile URL to a file at bitbucket.org. * * @return bool Whether the given URL is a public BitBucket download which requires no authentication. */ private function isPublicBitBucketDownload($urlToBitBucketFile) { $domain = parse_url($urlToBitBucketFile, PHP_URL_HOST); if (strpos($domain, 'bitbucket.org') === false) { // Bitbucket downloads are hosted on amazonaws. // We do not need to authenticate there at all return true; } $path = parse_url($urlToBitBucketFile, PHP_URL_PATH); // Path for a public download follows this pattern /{user}/{repo}/downloads/{whatever} // {@link https://blog.bitbucket.org/2009/04/12/new-feature-downloads/} $pathParts = explode('/', $path); return count($pathParts) >= 4 && $pathParts[3] == 'downloads'; } } composer-1.6.3/src/Composer/Util/Silencer.php000066400000000000000000000041661323436022200211240ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * Temporarily suppress PHP error reporting, usually warnings and below. * * @author Niels Keurentjes */ class Silencer { /** * @var int[] Unpop stack */ private static $stack = array(); /** * Suppresses given mask or errors. * * @param int|null $mask Error levels to suppress, default value NULL indicates all warnings and below. * @return int The old error reporting level. */ public static function suppress($mask = null) { if (!isset($mask)) { $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT; } $old = error_reporting(); self::$stack[] = $old; error_reporting($old & ~$mask); return $old; } /** * Restores a single state. */ public static function restore() { if (!empty(self::$stack)) { error_reporting(array_pop(self::$stack)); } } /** * Calls a specified function while silencing warnings and below. * * Future improvement: when PHP requirements are raised add Callable type hint (5.4) and variadic parameters (5.6) * * @param callable $callable Function to execute. * @throws \Exception Any exceptions from the callback are rethrown. * @return mixed Return value of the callback. */ public static function call($callable /*, ...$parameters */) { try { self::suppress(); $result = call_user_func_array($callable, array_slice(func_get_args(), 1)); self::restore(); return $result; } catch (\Exception $e) { // Use a finally block for this when requirements are raised to PHP 5.5 self::restore(); throw $e; } } } composer-1.6.3/src/Composer/Util/SpdxLicense.php000066400000000000000000000010721323436022200215720ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Spdx\SpdxLicenses; trigger_error('The ' . __NAMESPACE__ . '\SpdxLicense class is deprecated, use Composer\Spdx\SpdxLicenses instead.', E_USER_DEPRECATED); /** * @deprecated use Composer\Spdx\SpdxLicenses instead */ class SpdxLicense extends SpdxLicenses { } composer-1.6.3/src/Composer/Util/StreamContextFactory.php000066400000000000000000000162041323436022200235040ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Composer; /** * Allows the creation of a basic context supporting http proxy * * @author Jordan Alliot * @author Markus Tacker */ final class StreamContextFactory { /** * Creates a context supporting HTTP proxies * * @param string $url URL the context is to be used for * @param array $defaultOptions Options to merge with the default * @param array $defaultParams Parameters to specify on the context * @throws \RuntimeException if https proxy required and OpenSSL uninstalled * @return resource Default context */ public static function getContext($url, array $defaultOptions = array(), array $defaultParams = array()) { $options = array('http' => array( // specify defaults again to try and work better with curlwrappers enabled 'follow_location' => 1, 'max_redirects' => 20, )); // Handle HTTP_PROXY/http_proxy on CLI only for security reasons if (PHP_SAPI === 'cli' && (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy']))) { $proxy = parse_url(!empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY']); } // Prefer CGI_HTTP_PROXY if available if (!empty($_SERVER['CGI_HTTP_PROXY'])) { $proxy = parse_url($_SERVER['CGI_HTTP_PROXY']); } // Override with HTTPS proxy if present and URL is https if (preg_match('{^https://}i', $url) && (!empty($_SERVER['HTTPS_PROXY']) || !empty($_SERVER['https_proxy']))) { $proxy = parse_url(!empty($_SERVER['https_proxy']) ? $_SERVER['https_proxy'] : $_SERVER['HTTPS_PROXY']); } // Remove proxy if URL matches no_proxy directive if (!empty($_SERVER['NO_PROXY']) || !empty($_SERVER['no_proxy']) && parse_url($url, PHP_URL_HOST)) { $pattern = new NoProxyPattern(!empty($_SERVER['no_proxy']) ? $_SERVER['no_proxy'] : $_SERVER['NO_PROXY']); if ($pattern->test($url)) { unset($proxy); } } if (!empty($proxy)) { $proxyURL = isset($proxy['scheme']) ? $proxy['scheme'] . '://' : ''; $proxyURL .= isset($proxy['host']) ? $proxy['host'] : ''; if (isset($proxy['port'])) { $proxyURL .= ":" . $proxy['port']; } elseif ('http://' == substr($proxyURL, 0, 7)) { $proxyURL .= ":80"; } elseif ('https://' == substr($proxyURL, 0, 8)) { $proxyURL .= ":443"; } // http(s):// is not supported in proxy $proxyURL = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $proxyURL); if (0 === strpos($proxyURL, 'ssl:') && !extension_loaded('openssl')) { throw new \RuntimeException('You must enable the openssl extension to use a proxy over https'); } $options['http']['proxy'] = $proxyURL; // enabled request_fulluri unless it is explicitly disabled switch (parse_url($url, PHP_URL_SCHEME)) { case 'http': // default request_fulluri to true $reqFullUriEnv = getenv('HTTP_PROXY_REQUEST_FULLURI'); if ($reqFullUriEnv === false || $reqFullUriEnv === '' || (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv)) { $options['http']['request_fulluri'] = true; } break; case 'https': // default request_fulluri to true $reqFullUriEnv = getenv('HTTPS_PROXY_REQUEST_FULLURI'); if ($reqFullUriEnv === false || $reqFullUriEnv === '' || (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv)) { $options['http']['request_fulluri'] = true; } break; } // add SNI opts for https URLs if ('https' === parse_url($url, PHP_URL_SCHEME)) { $options['ssl']['SNI_enabled'] = true; if (PHP_VERSION_ID < 50600) { $options['ssl']['SNI_server_name'] = parse_url($url, PHP_URL_HOST); } } // handle proxy auth if present if (isset($proxy['user'])) { $auth = urldecode($proxy['user']); if (isset($proxy['pass'])) { $auth .= ':' . urldecode($proxy['pass']); } $auth = base64_encode($auth); // Preserve headers if already set in default options if (isset($defaultOptions['http']['header'])) { if (is_string($defaultOptions['http']['header'])) { $defaultOptions['http']['header'] = array($defaultOptions['http']['header']); } $defaultOptions['http']['header'][] = "Proxy-Authorization: Basic {$auth}"; } else { $options['http']['header'] = array("Proxy-Authorization: Basic {$auth}"); } } } $options = array_replace_recursive($options, $defaultOptions); if (isset($options['http']['header'])) { $options['http']['header'] = self::fixHttpHeaderField($options['http']['header']); } if (defined('HHVM_VERSION')) { $phpVersion = 'HHVM ' . HHVM_VERSION; } else { $phpVersion = 'PHP ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION; } if (!isset($options['http']['header']) || false === stripos(implode('', $options['http']['header']), 'user-agent')) { $options['http']['header'][] = sprintf( 'User-Agent: Composer/%s (%s; %s; %s%s)', Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION, function_exists('php_uname') ? php_uname('s') : 'Unknown', function_exists('php_uname') ? php_uname('r') : 'Unknown', $phpVersion, getenv('CI') ? '; CI' : '' ); } return stream_context_create($options, $defaultParams); } /** * A bug in PHP prevents the headers from correctly being sent when a content-type header is present and * NOT at the end of the array * * This method fixes the array by moving the content-type header to the end * * @link https://bugs.php.net/bug.php?id=61548 * @param $header * @return array */ private static function fixHttpHeaderField($header) { if (!is_array($header)) { $header = explode("\r\n", $header); } uasort($header, function ($el) { return preg_match('{^content-type}i', $el) ? 1 : -1; }); return $header; } } composer-1.6.3/src/Composer/Util/Svn.php000066400000000000000000000224731323436022200201270ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Config; use Composer\IO\IOInterface; /** * @author Till Klampaeckel * @author Jordi Boggiano */ class Svn { const MAX_QTY_AUTH_TRIES = 5; /** * @var array */ protected $credentials; /** * @var bool */ protected $hasAuth; /** * @var \Composer\IO\IOInterface */ protected $io; /** * @var string */ protected $url; /** * @var bool */ protected $cacheCredentials = true; /** * @var ProcessExecutor */ protected $process; /** * @var int */ protected $qtyAuthTries = 0; /** * @var \Composer\Config */ protected $config; /** * @param string $url * @param \Composer\IO\IOInterface $io * @param Config $config * @param ProcessExecutor $process */ public function __construct($url, IOInterface $io, Config $config, ProcessExecutor $process = null) { $this->url = $url; $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor; } public static function cleanEnv() { // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940 putenv("DYLD_LIBRARY_PATH"); unset($_SERVER['DYLD_LIBRARY_PATH']); } /** * Execute an SVN remote command and try to fix up the process with credentials * if necessary. * * @param string $command SVN command to run * @param string $url SVN url * @param string $cwd Working directory * @param string $path Target for a checkout * @param bool $verbose Output all output to the user * * @throws \RuntimeException * @return string */ public function execute($command, $url, $cwd = null, $path = null, $verbose = false) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); $svnCommand = $this->getCommand($command, $url, $path); return $this->executeWithAuthRetry($svnCommand, $cwd, $path, $verbose); } /** * Execute an SVN local command and try to fix up the process with credentials * if necessary. * * @param string $command SVN command to run * @param string $path Path argument passed thru to the command * @param string $cwd Working directory * @param bool $verbose Output all output to the user * * @throws \RuntimeException * @return string */ public function executeLocal($command, $path, $cwd = null, $verbose = false) { $svnCommand = sprintf('%s %s%s %s', $command, '--non-interactive ', $this->getCredentialString(), ProcessExecutor::escape($path) ); return $this->executeWithAuthRetry($svnCommand, $cwd, $path, $verbose); } private function executeWithAuthRetry($command, $cwd, $path, $verbose) { $output = null; $io = $this->io; $handler = function ($type, $buffer) use (&$output, $io, $verbose) { if ($type !== 'out') { return; } if ('Redirecting to URL ' === substr($buffer, 0, 19)) { return; } $output .= $buffer; if ($verbose) { $io->writeError($buffer, false); } }; $status = $this->process->execute($command, $handler, $cwd); if (0 === $status) { return $output; } $errorOutput = $this->process->getErrorOutput(); $fullOutput = implode("\n", array($output, $errorOutput)); // the error is not auth-related if (false === stripos($fullOutput, 'Could not authenticate to server:') && false === stripos($fullOutput, 'authorization failed') && false === stripos($fullOutput, 'svn: E170001:') && false === stripos($fullOutput, 'svn: E215004:')) { throw new \RuntimeException($fullOutput); } if (!$this->hasAuth()) { $this->doAuthDance(); } // try to authenticate if maximum quantity of tries not reached if ($this->qtyAuthTries++ < self::MAX_QTY_AUTH_TRIES) { // restart the process return $this->executeWithAuthRetry($command, $cwd, $path, $verbose); } throw new \RuntimeException( 'wrong credentials provided ('.$fullOutput.')' ); } /** * @param bool $cacheCredentials */ public function setCacheCredentials($cacheCredentials) { $this->cacheCredentials = $cacheCredentials; } /** * Repositories requests credentials, let's put them in. * * @throws \RuntimeException * @return \Composer\Util\Svn */ protected function doAuthDance() { // cannot ask for credentials in non interactive mode if (!$this->io->isInteractive()) { throw new \RuntimeException( 'can not ask for authentication in non interactive mode' ); } $this->io->writeError("The Subversion server ({$this->url}) requested credentials:"); $this->hasAuth = true; $this->credentials['username'] = $this->io->ask("Username: "); $this->credentials['password'] = $this->io->askAndHideAnswer("Password: "); $this->cacheCredentials = $this->io->askConfirmation("Should Subversion cache these credentials? (yes/no) ", true); return $this; } /** * A method to create the svn commands run. * * @param string $cmd Usually 'svn ls' or something like that. * @param string $url Repo URL. * @param string $path Target for a checkout * * @return string */ protected function getCommand($cmd, $url, $path = null) { $cmd = sprintf('%s %s%s %s', $cmd, '--non-interactive ', $this->getCredentialString(), ProcessExecutor::escape($url) ); if ($path) { $cmd .= ' ' . ProcessExecutor::escape($path); } return $cmd; } /** * Return the credential string for the svn command. * * Adds --no-auth-cache when credentials are present. * * @return string */ protected function getCredentialString() { if (!$this->hasAuth()) { return ''; } return sprintf( ' %s--username %s --password %s ', $this->getAuthCache(), ProcessExecutor::escape($this->getUsername()), ProcessExecutor::escape($this->getPassword()) ); } /** * Get the password for the svn command. Can be empty. * * @throws \LogicException * @return string */ protected function getPassword() { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); } return isset($this->credentials['password']) ? $this->credentials['password'] : ''; } /** * Get the username for the svn command. * * @throws \LogicException * @return string */ protected function getUsername() { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); } return $this->credentials['username']; } /** * Detect Svn Auth. * * @return bool */ protected function hasAuth() { if (null !== $this->hasAuth) { return $this->hasAuth; } if (false === $this->createAuthFromConfig()) { $this->createAuthFromUrl(); } return $this->hasAuth; } /** * Return the no-auth-cache switch. * * @return string */ protected function getAuthCache() { return $this->cacheCredentials ? '' : '--no-auth-cache '; } /** * Create the auth params from the configuration file. * * @return bool */ private function createAuthFromConfig() { if (!$this->config->has('http-basic')) { return $this->hasAuth = false; } $authConfig = $this->config->get('http-basic'); $host = parse_url($this->url, PHP_URL_HOST); if (isset($authConfig[$host])) { $this->credentials['username'] = $authConfig[$host]['username']; $this->credentials['password'] = $authConfig[$host]['password']; return $this->hasAuth = true; } return $this->hasAuth = false; } /** * Create the auth params from the url * * @return bool */ private function createAuthFromUrl() { $uri = parse_url($this->url); if (empty($uri['user'])) { return $this->hasAuth = false; } $this->credentials['username'] = $uri['user']; if (!empty($uri['pass'])) { $this->credentials['password'] = $uri['pass']; } return $this->hasAuth = true; } } composer-1.6.3/src/Composer/Util/TlsHelper.php000066400000000000000000000150101323436022200212500ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\CaBundle\CaBundle; /** * @author Chris Smith */ final class TlsHelper { private static $useOpensslParse; /** * Match hostname against a certificate. * * @param mixed $certificate X.509 certificate * @param string $hostname Hostname in the URL * @param string $cn Set to the common name of the certificate iff match found * * @return bool */ public static function checkCertificateHost($certificate, $hostname, &$cn = null) { $names = self::getCertificateNames($certificate); if (empty($names)) { return false; } $combinedNames = array_merge($names['san'], array($names['cn'])); $hostname = strtolower($hostname); foreach ($combinedNames as $certName) { $matcher = self::certNameMatcher($certName); if ($matcher && $matcher($hostname)) { $cn = $names['cn']; return true; } } return false; } /** * Extract DNS names out of an X.509 certificate. * * @param mixed $certificate X.509 certificate * * @return array|null */ public static function getCertificateNames($certificate) { if (is_array($certificate)) { $info = $certificate; } elseif (CaBundle::isOpensslParseSafe()) { $info = openssl_x509_parse($certificate, false); } if (!isset($info['subject']['commonName'])) { return null; } $commonName = strtolower($info['subject']['commonName']); $subjectAltNames = array(); if (isset($info['extensions']['subjectAltName'])) { $subjectAltNames = preg_split('{\s*,\s*}', $info['extensions']['subjectAltName']); $subjectAltNames = array_filter(array_map(function ($name) { if (0 === strpos($name, 'DNS:')) { return strtolower(ltrim(substr($name, 4))); } return null; }, $subjectAltNames)); $subjectAltNames = array_values($subjectAltNames); } return array( 'cn' => $commonName, 'san' => $subjectAltNames, ); } /** * Get the certificate pin. * * By Kevin McArthur of StormTide Digital Studios Inc. * @KevinSMcArthur / https://github.com/StormTide * * See http://tools.ietf.org/html/draft-ietf-websec-key-pinning-02 * * This method was adapted from Sslurp. * https://github.com/EvanDotPro/Sslurp * * (c) Evan Coury * * For the full copyright and license information, please see below: * * Copyright (c) 2013, Evan Coury * 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. */ public static function getCertificateFingerprint($certificate) { $pubkeydetails = openssl_pkey_get_details(openssl_get_publickey($certificate)); $pubkeypem = $pubkeydetails['key']; //Convert PEM to DER before SHA1'ing $start = '-----BEGIN PUBLIC KEY-----'; $end = '-----END PUBLIC KEY-----'; $pemtrim = substr($pubkeypem, (strpos($pubkeypem, $start) + strlen($start)), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1)); $der = base64_decode($pemtrim); return sha1($der); } /** * Test if it is safe to use the PHP function openssl_x509_parse(). * * This checks if OpenSSL extensions is vulnerable to remote code execution * via the exploit documented as CVE-2013-6420. * * @return bool */ public static function isOpensslParseSafe() { return CaBundle::isOpensslParseSafe(); } /** * Convert certificate name into matching function. * * @param string $certName CN/SAN * * @return callable|null */ private static function certNameMatcher($certName) { $wildcards = substr_count($certName, '*'); if (0 === $wildcards) { // Literal match. return function ($hostname) use ($certName) { return $hostname === $certName; }; } if (1 === $wildcards) { $components = explode('.', $certName); if (3 > count($components)) { // Must have 3+ components return; } $firstComponent = $components[0]; // Wildcard must be the last character. if ('*' !== $firstComponent[strlen($firstComponent) - 1]) { return; } $wildcardRegex = preg_quote($certName); $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); $wildcardRegex = "{^{$wildcardRegex}$}"; return function ($hostname) use ($wildcardRegex) { return 1 === preg_match($wildcardRegex, $hostname); }; } } } composer-1.6.3/src/Composer/Util/Url.php000066400000000000000000000055651323436022200201260ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\Config; use Composer\IO\IOInterface; /** * @author Jordi Boggiano */ class Url { public static function updateDistReference(Config $config, $url, $ref) { $host = parse_url($url, PHP_URL_HOST); if ($host === 'api.github.com' || $host === 'github.com' || $host === 'www.github.com') { if (preg_match('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i', $url, $match)) { // update legacy github archives to API calls with the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } elseif (preg_match('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i', $url, $match)) { // update current github web archives to API calls with the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } elseif (preg_match('{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i', $url, $match)) { // update api archives to the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } } elseif ($host === 'bitbucket.org' || $host === 'www.bitbucket.org') { if (preg_match('{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i', $url, $match)) { // update Bitbucket archives to the proper reference $url = 'https://bitbucket.org/' . $match[1] . '/'. $match[2] . '/get/' . $ref . '.' . $match[4]; } } elseif ($host === 'gitlab.com' || $host === 'www.gitlab.com') { if (preg_match('{^https?://(?:www\.)?gitlab\.com/api/v[34]/projects/([^/]+)/repository/archive\.(zip|tar\.gz|tar\.bz2|tar)\?sha=.+$}i', $url, $match)) { // update Gitlab archives to the proper reference $url = 'https://gitlab.com/api/v4/projects/' . $match[1] . '/repository/archive.' . $match[2] . '?sha=' . $ref; } } elseif (in_array($host, $config->get('github-domains'), true)) { $url = preg_replace('{(/repos/[^/]+/[^/]+/(zip|tar)ball)(?:/.+)?$}i', '$1/'.$ref, $url); } elseif (in_array($host, $config->get('gitlab-domains'), true)) { $url = preg_replace('{(/api/v[34]/projects/[^/]+/repository/archive\.(?:zip|tar\.gz|tar\.bz2|tar)\?sha=).+$}i', '${1}'.$ref, $url); } return $url; } } composer-1.6.3/src/Composer/XdebugHandler.php000066400000000000000000000206431323436022200211550ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Util\IniHelper; use Symfony\Component\Console\Output\OutputInterface; /** * @author John Stevenson */ class XdebugHandler { const ENV_ALLOW = 'COMPOSER_ALLOW_XDEBUG'; const ENV_VERSION = 'COMPOSER_XDEBUG_VERSION'; const RESTART_ID = 'internal'; private $output; private $loaded; private $envScanDir; private $version; private $tmpIni; /** * Constructor */ public function __construct(OutputInterface $output) { $this->output = $output; $this->loaded = extension_loaded('xdebug'); $this->envScanDir = getenv('PHP_INI_SCAN_DIR'); if ($this->loaded) { $ext = new \ReflectionExtension('xdebug'); $this->version = strval($ext->getVersion()); } } /** * Checks if xdebug is loaded and composer needs to be restarted * * If so, then a tmp ini is created with the xdebug ini entry commented out. * If additional inis have been loaded, these are combined into the tmp ini * and PHP_INI_SCAN_DIR is set to an empty value. Current ini locations are * are stored in COMPOSER_ORIGINAL_INIS, for use in the restarted process. * * This behaviour can be disabled by setting the COMPOSER_ALLOW_XDEBUG * environment variable to 1. This variable is used internally so that the * restarted process is created only once and PHP_INI_SCAN_DIR can be * restored to its original value. */ public function check() { $args = explode('|', strval(getenv(self::ENV_ALLOW)), 2); if ($this->needsRestart($args[0])) { if ($this->prepareRestart()) { $command = $this->getCommand(); $this->restart($command); } return; } // Restore environment variables if we are restarting if (self::RESTART_ID === $args[0]) { putenv(self::ENV_ALLOW); if (false !== $this->envScanDir) { // $args[1] contains the original value if (isset($args[1])) { putenv('PHP_INI_SCAN_DIR='.$args[1]); } else { putenv('PHP_INI_SCAN_DIR'); } } // Clear version if the restart failed to disable xdebug if ($this->loaded) { putenv(self::ENV_VERSION); } } } /** * Executes the restarted command then deletes the tmp ini * * @param string $command */ protected function restart($command) { passthru($command, $exitCode); if (!empty($this->tmpIni)) { @unlink($this->tmpIni); } exit($exitCode); } /** * Returns true if a restart is needed * * @param string $allow Environment value * * @return bool */ private function needsRestart($allow) { if (PHP_SAPI !== 'cli' || !defined('PHP_BINARY')) { return false; } return empty($allow) && $this->loaded; } /** * Returns true if everything was written for the restart * * If any of the following fails (however unlikely) we must return false to * stop potential recursion: * - tmp ini file creation * - environment variable creation * * @return bool */ private function prepareRestart() { $this->tmpIni = ''; $iniPaths = IniHelper::getAll(); $additional = count($iniPaths) > 1; if ($this->writeTmpIni($iniPaths)) { return $this->setEnvironment($additional, $iniPaths); } return false; } /** * Returns true if the tmp ini file was written * * The filename is passed as the -c option when the process restarts. * * @param array $iniPaths Locations reported by the current process * * @return bool */ private function writeTmpIni(array $iniPaths) { if (!$this->tmpIni = tempnam(sys_get_temp_dir(), '')) { return false; } // $iniPaths has at least one item and it may be empty if (empty($iniPaths[0])) { array_shift($iniPaths); } $content = ''; $regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi'; foreach ($iniPaths as $file) { $data = preg_replace($regex, ';$1', file_get_contents($file)); $content .= $data.PHP_EOL; } $content .= 'allow_url_fopen='.ini_get('allow_url_fopen').PHP_EOL; $content .= 'disable_functions="'.ini_get('disable_functions').'"'.PHP_EOL; $content .= 'memory_limit='.ini_get('memory_limit').PHP_EOL; if (defined('PHP_WINDOWS_VERSION_BUILD')) { // Work-around for PHP windows bug, see issue #6052 $content .= 'opcache.enable_cli=0'.PHP_EOL; } return @file_put_contents($this->tmpIni, $content); } /** * Returns the restart command line * * @return string */ private function getCommand() { $phpArgs = array(PHP_BINARY, '-c', $this->tmpIni); $params = array_merge($phpArgs, $this->getScriptArgs($_SERVER['argv'])); return implode(' ', array_map(array($this, 'escape'), $params)); } /** * Returns true if the restart environment variables were set * * @param bool $additional Whether there were additional inis * @param array $iniPaths Locations reported by the current process * * @return bool */ private function setEnvironment($additional, array $iniPaths) { // Set scan dir to an empty value if additional ini files were used if ($additional && !putenv('PHP_INI_SCAN_DIR=')) { return false; } // Make original inis available to restarted process if (!putenv(IniHelper::ENV_ORIGINAL.'='.implode(PATH_SEPARATOR, $iniPaths))) { return false; } // Make xdebug version available to restarted process if (!putenv(self::ENV_VERSION.'='.$this->version)) { return false; } // Flag restarted process and save env scan dir state $args = array(self::RESTART_ID); if (false !== $this->envScanDir) { // Save current PHP_INI_SCAN_DIR $args[] = $this->envScanDir; } return putenv(self::ENV_ALLOW.'='.implode('|', $args)); } /** * Returns the restart script arguments, adding --ansi if required * * If we are a terminal with color support we must ensure that the --ansi * option is set, because the restarted output is piped. * * @param array $args The argv array * * @return array */ private function getScriptArgs(array $args) { if (in_array('--no-ansi', $args) || in_array('--ansi', $args)) { return $args; } if ($this->output->isDecorated()) { $offset = count($args) > 1 ? 2 : 1; array_splice($args, $offset, 0, '--ansi'); } return $args; } /** * Escapes a string to be used as a shell argument. * * From https://github.com/johnstevenson/winbox-args * MIT Licensed (c) John Stevenson * * @param string $arg The argument to be escaped * @param bool $meta Additionally escape cmd.exe meta characters * * @return string The escaped argument */ private function escape($arg, $meta = true) { if (!defined('PHP_WINDOWS_VERSION_BUILD')) { return escapeshellarg($arg); } $quote = strpbrk($arg, " \t") !== false || $arg === ''; $arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes); if ($meta) { $meta = $dquotes || preg_match('/%[^%]+%/', $arg); if (!$meta && !$quote) { $quote = strpbrk($arg, '^&|<>()') !== false; } } if ($quote) { $arg = preg_replace('/(\\\\*)$/', '$1$1', $arg); $arg = '"'.$arg.'"'; } if ($meta) { $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg); } return $arg; } } composer-1.6.3/src/bootstrap.php000066400000000000000000000013111323436022200166560ustar00rootroot00000000000000 * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ function includeIfExists($file) { return file_exists($file) ? include $file : false; } if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) { echo 'You must set up the project dependencies using `composer install`'.PHP_EOL. 'See https://getcomposer.org/download/ for instructions on installing Composer'.PHP_EOL; exit(1); } return $loader;