#!/usr/bin/env php ;^ wp-cli.phar#vendor/wp-cli/wp-cli/php/compat.phpq@]qE (vendor/wp-cli/wp-cli/php/config-spec.php @] q"vendor/wp-cli/wp-cli/php/utils.php(@](LCq'vendor/wp-cli/wp-cli/php/dispatcher.phpR@]R$vendor/wp-cli/wp-cli/php/boot-fs.php@]A6vendor/wp-cli/wp-cli/php/WP_CLI/WpHttpCacheManager.php @] E۫k*vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php@]u<vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/RunnerInstance.php@]{Hvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/DeclareAbstractBaseCommand.phpA@]A@<@Evendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/DefineProtectedCommands.php@]ٶXwGvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/IncludeFallbackAutoloader.php@]\Bvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LoadUtilityFunctions.php)@])TYMݴHvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/IncludeFrameworkAutoloader.php@]t?ߴ<vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/AutoloaderStep.php @] <vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LoadDispatcher.php5@]5U4:vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LaunchRunner.php(@](z\Fvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/RegisterDeferredCommands.php@].Ǵ>vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/InitializeLogger.php@](mJAvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LoadRequiredCommand.php@] #>vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/DeclareMainClass.php@]TjGvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/RegisterFrameworkCommands.php8@]8PxODvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/InitializeColorization.phpL@]L'=Fvendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/IncludePackageAutoloader.php@]w<vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/BootstrapState.php@]n$=vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/ConfigureRunner.php5@]5߶-;vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/BootstrapStep.php@]A7/ (vendor/wp-cli/wp-cli/php/WP_CLI/NoOp.php@]D1-vendor/wp-cli/wp-cli/php/WP_CLI/FileCache.php(!@](!Nj^1vendor/wp-cli/wp-cli/php/WP_CLI/Fetchers/Base.php@]y9-vendor/wp-cli/wp-cli/php/WP_CLI/DocParser.php7@]7fdl-vendor/wp-cli/wp-cli/php/WP_CLI/Formatter.php%@]%X&.vendor/wp-cli/wp-cli/php/WP_CLI/ProcessRun.php@](~Avendor/wp-cli/wp-cli/php/WP_CLI/PackageManagerEventSubscriber.php@]ݑྴJvendor/wp-cli/wp-cli/php/WP_CLI/Compat/Min_PHP_5_6/FeedbackMethodTrait.php@]4pJvendor/wp-cli/wp-cli/php/WP_CLI/Compat/Min_PHP_5_4/FeedbackMethodTrait.php@]ܠӴ>vendor/wp-cli/wp-cli/php/WP_CLI/Compat/FeedbackMethodTrait.php@]閴3vendor/wp-cli/wp-cli/php/WP_CLI/Loggers/Regular.php @] 1vendor/wp-cli/wp-cli/php/WP_CLI/Loggers/Quiet.php@]k0vendor/wp-cli/wp-cli/php/WP_CLI/Loggers/Base.php@]햴5vendor/wp-cli/wp-cli/php/WP_CLI/Loggers/Execution.php@@]@BB0vendor/wp-cli/wp-cli/php/WP_CLI/UpgraderSkin.php=@]=A /vendor/wp-cli/wp-cli/php/WP_CLI/Completions.php@]S.vendor/wp-cli/wp-cli/php/WP_CLI/Autoloader.phpK@]Kv>vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandAddition.php#@]#躛?vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandNamespace.php@]z?vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CompositeCommand.php@]Zv,=vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandFactory.php/"@]/".:vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/RootCommand.php^@]^xD{9vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/Subcommand.php:2@]:25f2vendor/wp-cli/wp-cli/php/WP_CLI/SynopsisParser.php@]xM1vendor/wp-cli/wp-cli/php/WP_CLI/ExitException.phpD@]Ds/ߴ5vendor/wp-cli/wp-cli/php/WP_CLI/SynopsisValidator.php1@]1]0vendor/wp-cli/wp-cli/php/WP_CLI/Configurator.php+&@]+&d٧F.vendor/wp-cli/wp-cli/php/WP_CLI/ComposerIO.phpK@]K+vendor/wp-cli/wp-cli/php/WP_CLI/Process.php} @]} !Ǵ-vendor/wp-cli/wp-cli/php/WP_CLI/Inflector.php+@@]+@7-vendor/wp-cli/wp-cli/php/WP_CLI/Extractor.phpW'@]W'I73vendor/wp-cli/wp-cli/php/WP_CLI/Iterators/Query.php @] YoA7vendor/wp-cli/wp-cli/php/WP_CLI/Iterators/Transform.php@]Ŀ3vendor/wp-cli/wp-cli/php/WP_CLI/Iterators/Table.php} @]} [A7vendor/wp-cli/wp-cli/php/WP_CLI/Iterators/Exception.phpR@]RY71vendor/wp-cli/wp-cli/php/WP_CLI/Iterators/CSV.phpm@]mYo6&vendor/wp-cli/wp-cli/php/bootstrap.php@]#vendor/wp-cli/wp-cli/php/wp-cli.php @] xc*vendor/wp-cli/wp-cli/php/commands/help.php@]lD)vendor/wp-cli/wp-cli/php/commands/cli.php@]jn6vendor/wp-cli/wp-cli/php/commands/src/Help_Command.phpg@]g";vendor/wp-cli/wp-cli/php/commands/src/CLI_Alias_Command.phpd2@]d24;vendor/wp-cli/wp-cli/php/commands/src/CLI_Cache_Command.php@]n?5vendor/wp-cli/wp-cli/php/commands/src/CLI_Command.phpJ@]J41vendor/wp-cli/wp-cli/php/class-wp-cli-command.php@]*,vendor/wp-cli/wp-cli/php/wp-settings-cli.phpQB@]QB")vendor/wp-cli/wp-cli/php/class-wp-cli.phpɞ@]ɞ@ᠴ%vendor/wp-cli/wp-cli/php/utils-wp.php5@]5A\php/boot-phar.php9@]9Ys0vendor/mustache/mustache/bin/build_bootstrap.php;@];3vendor/mustache/mustache/src/Mustache/Tokenizer.php)@]) =vendor/mustache/mustache/src/Mustache/Logger/StreamLogger.php@]J?vendor/mustache/mustache/src/Mustache/Logger/AbstractLogger.phpv @]v nY60vendor/mustache/mustache/src/Mustache/Logger.php$ @]$ @Y96vendor/mustache/mustache/src/Mustache/LambdaHelper.php@]pմ0vendor/mustache/mustache/src/Mustache/Parser.php*@]*nG4vendor/mustache/mustache/src/Mustache/Autoloader.php@]=cִ@vendor/mustache/mustache/src/Mustache/Loader/CascadingLoader.php@]>vendor/mustache/mustache/src/Mustache/Loader/MutableLoader.php@]g=vendor/mustache/mustache/src/Mustache/Loader/InlineLoader.php@]\ =vendor/mustache/mustache/src/Mustache/Loader/StringLoader.php@]<%Avendor/mustache/mustache/src/Mustache/Loader/FilesystemLoader.php@]L$yKvendor/mustache/mustache/src/Mustache/Loader/ProductionFilesystemLoader.phpf @]f <vendor/mustache/mustache/src/Mustache/Loader/ArrayLoader.php@]!?vendor/mustache/mustache/src/Mustache/Cache/FilesystemCache.phph@]h(}49vendor/mustache/mustache/src/Mustache/Cache/NoopCache.phpA@]Aٴ=vendor/mustache/mustache/src/Mustache/Cache/AbstractCache.php@]V߀۴1vendor/mustache/mustache/src/Mustache/Context.php@]D2vendor/mustache/mustache/src/Mustache/Template.php@]80vendor/mustache/mustache/src/Mustache/Engine.phpc@]cR2vendor/mustache/mustache/src/Mustache/Compiler.php|X@]|XVs:vendor/mustache/mustache/src/Mustache/HelperCollection.php@]Ӵ/vendor/mustache/mustache/src/Mustache/Cache.php@]% H 3vendor/mustache/mustache/src/Mustache/Exception.phpR@]R]u0vendor/mustache/mustache/src/Mustache/Loader.phpB@]BQy0vendor/mustache/mustache/src/Mustache/Source.php@]b׶mAvendor/mustache/mustache/src/Mustache/Source/FilesystemSource.phpj@]j@Bvendor/mustache/mustache/src/Mustache/Exception/LogicException.php@]}AJvendor/mustache/mustache/src/Mustache/Exception/UnknownHelperException.php@]HjCvendor/mustache/mustache/src/Mustache/Exception/SyntaxException.php@]NJvendor/mustache/mustache/src/Mustache/Exception/UnknownFilterException.php@]f޴Lvendor/mustache/mustache/src/Mustache/Exception/InvalidArgumentException.php@]QDvendor/mustache/mustache/src/Mustache/Exception/RuntimeException.php@]1]ӴLvendor/mustache/mustache/src/Mustache/Exception/UnknownTemplateException.php@]-[2vendor/rmccue/requests/bin/create_pear_package.php#@]# !쯴7vendor/rmccue/requests/library/Requests/IDNAEncoder.php=,@]=,J4vendor/rmccue/requests/library/Requests/Response.php @] 9=0vendor/rmccue/requests/library/Requests/IPv6.php?@]?6vendor/rmccue/requests/library/Requests/Auth/Basic.php@]z6vendor/rmccue/requests/library/Requests/Cookie/Jar.php@]! Wg?vendor/rmccue/requests/library/Requests/Transport/fsockopen.php0@]0:vendor/rmccue/requests/library/Requests/Transport/cURL.php;@];8Lߴ1vendor/rmccue/requests/library/Requests/Hooks.phpw@]wTִ/vendor/rmccue/requests/library/Requests/IRI.php3o@]3oD 1vendor/rmccue/requests/library/Requests/Proxy.php-@]-<vendor/rmccue/requests/library/Requests/Response/Headers.phpM@]M~ʹ6vendor/rmccue/requests/library/Requests/Proxy/HTTP.php @] 3vendor/rmccue/requests/library/Requests/Session.php@]x´/vendor/rmccue/requests/library/Requests/SSL.php@]vendor/rmccue/requests/library/Requests/Exception/HTTP/414.php@]y>vendor/rmccue/requests/library/Requests/Exception/HTTP/412.php@]RUJ>vendor/rmccue/requests/library/Requests/Exception/HTTP/401.php@] >vendor/rmccue/requests/library/Requests/Exception/HTTP/416.php@]1>vendor/rmccue/requests/library/Requests/Exception/HTTP/402.php@]U>vendor/rmccue/requests/library/Requests/Exception/HTTP/503.php@]*>vendor/rmccue/requests/library/Requests/Exception/HTTP/403.php}@]}^%>vendor/rmccue/requests/library/Requests/Exception/HTTP/505.php@]">vendor/rmccue/requests/library/Requests/Exception/HTTP/501.php@]c/>vendor/rmccue/requests/library/Requests/Exception/HTTP/411.php@]uI>vendor/rmccue/requests/library/Requests/Exception/HTTP/404.php}@]}k>vendor/rmccue/requests/library/Requests/Exception/HTTP/305.php~@]~4-O>vendor/rmccue/requests/library/Requests/Exception/HTTP/418.php@]?/l>vendor/rmccue/requests/library/Requests/Exception/HTTP/428.php@]ْ/>vendor/rmccue/requests/library/Requests/Exception/HTTP/406.php@]*>vendor/rmccue/requests/library/Requests/Exception/HTTP/413.php@]6^%>vendor/rmccue/requests/library/Requests/Exception/HTTP/306.php@]Mo>vendor/rmccue/requests/library/Requests/Exception/HTTP/429.php%@]%]fn>vendor/rmccue/requests/library/Requests/Exception/HTTP/409.phpz@]z>vendor/rmccue/requests/library/Requests/Exception/HTTP/400.php@]v>vendor/rmccue/requests/library/Requests/Exception/HTTP/417.php@];>vendor/rmccue/requests/library/Requests/Exception/HTTP/502.php@]b>vendor/rmccue/requests/library/Requests/Exception/HTTP/304.php@]H9>vendor/rmccue/requests/library/Requests/Exception/HTTP/405.php@]]>vendor/rmccue/requests/library/Requests/Exception/HTTP/408.php@]&M>vendor/rmccue/requests/library/Requests/Exception/HTTP/504.php@]m͍>vendor/rmccue/requests/library/Requests/Exception/HTTP/415.php@]9>vendor/rmccue/requests/library/Requests/Exception/HTTP/407.php@]biִBvendor/rmccue/requests/library/Requests/Exception/HTTP/Unknown.phpc@]c"v>vendor/rmccue/requests/library/Requests/Exception/HTTP/500.php@]}l\>vendor/rmccue/requests/library/Requests/Exception/HTTP/431.php@]3JѴ>vendor/rmccue/requests/library/Requests/Exception/HTTP/511.php@] D>vendor/rmccue/requests/library/Requests/Exception/HTTP/410.phpn@]n|ZDvendor/rmccue/requests/library/Requests/Exception/Transport/cURL.php@]`:vendor/rmccue/requests/library/Requests/Exception/HTTP.php@]S冴?vendor/rmccue/requests/library/Requests/Exception/Transport.phpJ@]J9[+vendor/rmccue/requests/library/Requests.php^t@]^tD ?"vendor/composer/autoload_files.phpw @]w )Ӵ#vendor/composer/autoload_static.phpW@]Wr3vendor/composer/composer/src/Composer/IO/BaseIO.php@]u{w6vendor/composer/composer/src/Composer/IO/ConsoleIO.php?'@]?'bO8vendor/composer/composer/src/Composer/IO/IOInterface.php4@]45vendor/composer/composer/src/Composer/IO/BufferIO.php3 @]3 W3vendor/composer/composer/src/Composer/IO/NullIO.php @] =vendor/composer/composer/src/Composer/SelfUpdate/Versions.php\@]\l9vendor/composer/composer/src/Composer/SelfUpdate/Keys.phpj@]jAEvendor/composer/composer/src/Composer/Console/HtmlOutputFormatter.php @] Rܴ=vendor/composer/composer/src/Composer/Console/Application.phpO@]ORvendor/composer/composer/src/Composer/EventDispatcher/ScriptExecutionException.php@]\!'ƴRvendor/composer/composer/src/Composer/EventDispatcher/EventSubscriberInterface.php@]#gIvendor/composer/composer/src/Composer/EventDispatcher/EventDispatcher.phpgV@]gV?vendor/composer/composer/src/Composer/EventDispatcher/Event.phpf@]fKxմFvendor/composer/composer/src/Composer/Config/ConfigSourceInterface.php@]Q-Avendor/composer/composer/src/Composer/Config/JsonConfigSource.php @] jL\Mvendor/composer/composer/src/Composer/Question/StrictConfirmationQuestion.phpk @]k |FDvendor/composer/composer/src/Composer/Autoload/AutoloadGenerator.php܈@]܈}Dvendor/composer/composer/src/Composer/Autoload/ClassMapGenerator.php"@]",r>vendor/composer/composer/src/Composer/Autoload/ClassLoader.php4@]4z7vendor/composer/composer/src/Composer/XdebugHandler.phpM@]M.3vendor/composer/composer/src/Composer/Installer.php@]DS"Ǵ=vendor/composer/composer/src/Composer/Script/PackageEvent.php@]6vendor/composer/composer/src/Composer/Script/Event.php @] H=vendor/composer/composer/src/Composer/Script/CommandEvent.php@]Ǵ=vendor/composer/composer/src/Composer/Script/ScriptEvents.php@]NׯFvendor/composer/composer/src/Composer/Json/JsonValidationException.php@]Jȴ>vendor/composer/composer/src/Composer/Json/JsonManipulator.phpK@]K^7vendor/composer/composer/src/Composer/Json/JsonFile.php%@]%#Ǵ<vendor/composer/composer/src/Composer/Json/JsonFormatter.php@]|⸴:vendor/composer/composer/src/Composer/Util/SpdxLicense.php:@]:R<vendor/composer/composer/src/Composer/Util/PackageSorter.php @] x-5vendor/composer/composer/src/Composer/Util/GitLab.php4@]4&9vendor/composer/composer/src/Composer/Util/Filesystem.php9W@]9Wܿд7vendor/composer/composer/src/Composer/Util/Silencer.phpv@]vG;vendor/composer/composer/src/Composer/Util/ErrorHandler.phpC @]C >vendor/composer/composer/src/Composer/Util/ProcessExecutor.php @] Yp=vendor/composer/composer/src/Composer/Util/ComposerMirror.php@]Q7vendor/composer/composer/src/Composer/Util/Platform.php( @]( R8vendor/composer/composer/src/Composer/Util/Bitbucket.php!@]!9Cvendor/composer/composer/src/Composer/Util/StreamContextFactory.php@]2vendor/composer/composer/src/Composer/Util/Zip.php @] 7vendor/composer/composer/src/Composer/Util/Perforce.phpeD@]eD3nC2vendor/composer/composer/src/Composer/Util/Git.phpC@]CtxD{8vendor/composer/composer/src/Composer/Util/IniHelper.php`@]`X2vendor/composer/composer/src/Composer/Util/Svn.php9'@]9'竚ʴ9vendor/composer/composer/src/Composer/Util/AuthHelper.php@]F5vendor/composer/composer/src/Composer/Util/GitHub.php@].2vendor/composer/composer/src/Composer/Util/Url.phpX @]X c>vendor/composer/composer/src/Composer/Util/ConfigValidator.phpy@]y_F?vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php@]1vendor/composer/composer/src/Composer/Util/Hg.phpC @]C s8vendor/composer/composer/src/Composer/Util/TlsHelper.php@]=vendor/composer/composer/src/Composer/Util/NoProxyPattern.phpK@]KCLvendor/composer/composer/src/Composer/DependencyResolver/PolicyInterface.php@]Hvendor/composer/composer/src/Composer/DependencyResolver/Transaction.php-@]-Ȭ~Mvendor/composer/composer/src/Composer/DependencyResolver/RuleSetGenerator.phpv7@]v7Kvendor/composer/composer/src/Composer/DependencyResolver/RuleWatchGraph.php@]/Avendor/composer/composer/src/Composer/DependencyResolver/Rule.php$@]$n~ѴAvendor/composer/composer/src/Composer/DependencyResolver/Pool.php7@]7;Hvendor/composer/composer/src/Composer/DependencyResolver/GenericRule.phpz@]zrpJvendor/composer/composer/src/Composer/DependencyResolver/RuleWatchNode.php @] Dvendor/composer/composer/src/Composer/DependencyResolver/Problem.php;%@];% #Fvendor/composer/composer/src/Composer/DependencyResolver/Decisions.php@]/Cvendor/composer/composer/src/Composer/DependencyResolver/Solver.phpk@]kyvOvendor/composer/composer/src/Composer/DependencyResolver/SolverBugException.php@]8|4Jvendor/composer/composer/src/Composer/DependencyResolver/DefaultPolicy.phpy$@]y$FhCDvendor/composer/composer/src/Composer/DependencyResolver/RuleSet.php<@]<ZDvendor/composer/composer/src/Composer/DependencyResolver/Request.php@]~6Kvendor/composer/composer/src/Composer/DependencyResolver/RuleWatchChain.phpz@]zd]_CTvendor/composer/composer/src/Composer/DependencyResolver/SolverProblemsException.php @] ',Lvendor/composer/composer/src/Composer/DependencyResolver/RuleSetIterator.php @] JcWvendor/composer/composer/src/Composer/DependencyResolver/Operation/InstallOperation.phpK@]KQVvendor/composer/composer/src/Composer/DependencyResolver/Operation/UpdateOperation.php.@]. %pgdvendor/composer/composer/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php@]x@Yvendor/composer/composer/src/Composer/DependencyResolver/Operation/UninstallOperation.phpS@]SBTYvendor/composer/composer/src/Composer/DependencyResolver/Operation/OperationInterface.php#@]#uVvendor/composer/composer/src/Composer/DependencyResolver/Operation/SolverOperation.php@]݊bvendor/composer/composer/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php@]DJvendor/composer/composer/src/Composer/DependencyResolver/Rule2Literals.php @] MɴBvendor/composer/composer/src/Composer/Package/RootAliasPackage.php=@]=6Pvendor/composer/composer/src/Composer/Package/Archiver/ComposerExcludeFilter.phpZ@]ZHInwJvendor/composer/composer/src/Composer/Package/Archiver/HgExcludeFilter.php @] ұSLvendor/composer/composer/src/Composer/Package/Archiver/ArchiverInterface.php@]lةPvendor/composer/composer/src/Composer/Package/Archiver/ArchivableFilesFilter.php@]Դ=Lvendor/composer/composer/src/Composer/Package/Archiver/BaseExcludeFilter.php@]xFvendor/composer/composer/src/Composer/Package/Archiver/ZipArchiver.php@]Kvendor/composer/composer/src/Composer/Package/Archiver/GitExcludeFilter.php9@]9$Ivendor/composer/composer/src/Composer/Package/Archiver/ArchiveManager.php<@]<Pvendor/composer/composer/src/Composer/Package/Archiver/ArchivableFilesFinder.phpK @]K I|/Gvendor/composer/composer/src/Composer/Package/Archiver/PharArchiver.phpF @]F L Xvendor/composer/composer/src/Composer/Package/LinkConstraint/LinkConstraintInterface.php@]䑞Rvendor/composer/composer/src/Composer/Package/LinkConstraint/VersionConstraint.php@]4OSvendor/composer/composer/src/Composer/Package/LinkConstraint/SpecificConstraint.php@]<Pvendor/composer/composer/src/Composer/Package/LinkConstraint/EmptyConstraint.php@]3Pvendor/composer/composer/src/Composer/Package/LinkConstraint/MultiConstraint.php@][5Hvendor/composer/composer/src/Composer/Package/Version/VersionGuesser.php.@].CGvendor/composer/composer/src/Composer/Package/Version/VersionParser.php @] Ivendor/composer/composer/src/Composer/Package/Version/VersionSelector.php@]FBo'Bvendor/composer/composer/src/Composer/Package/PackageInterface.phpl%@]l%~9vendor/composer/composer/src/Composer/Package/Package.php1@]1p(Dvendor/composer/composer/src/Composer/Package/Dumper/ArrayDumper.phpX@]X`Z%Pvendor/composer/composer/src/Composer/Package/Loader/InvalidPackageException.php@]IQشCvendor/composer/composer/src/Composer/Package/Loader/JsonLoader.php\@]\pjDvendor/composer/composer/src/Composer/Package/Loader/ArrayLoader.php,@],UƴHvendor/composer/composer/src/Composer/Package/Loader/LoaderInterface.phpB@]B*JJvendor/composer/composer/src/Composer/Package/Loader/RootPackageLoader.phpq'@]q'86ߴNvendor/composer/composer/src/Composer/Package/Loader/ValidatingArrayLoader.phpV@]V#"Cvendor/composer/composer/src/Composer/Package/Comparer/Comparer.php4@]4r=Avendor/composer/composer/src/Composer/Package/CompletePackage.php:@]: "w=vendor/composer/composer/src/Composer/Package/RootPackage.phpD @]D -/=vendor/composer/composer/src/Composer/Package/BasePackage.php@]vO>vendor/composer/composer/src/Composer/Package/AliasPackage.phpQ$@]Q$ZJ8vendor/composer/composer/src/Composer/Package/Locker.phpi9@]i9Fvendor/composer/composer/src/Composer/Package/RootPackageInterface.php @] ' fJvendor/composer/composer/src/Composer/Package/CompletePackageInterface.php@]r6vendor/composer/composer/src/Composer/Package/Link.php @] 0V2vendor/composer/composer/src/Composer/Compiler.phpi(@]i(9W´2vendor/composer/composer/src/Composer/Composer.php@]R/vendor/composer/composer/src/Composer/Cache.phpM@]M\UCvendor/composer/composer/src/Composer/Command/ClearCacheCommand.phpg@]g(Jvendor/composer/composer/src/Composer/Command/CheckPlatformReqsCommand.php@]>lcAvendor/composer/composer/src/Composer/Command/OutdatedCommand.phpI@]IA?vendor/composer/composer/src/Composer/Command/ConfigCommand.phpVo@]VoE=vendor/composer/composer/src/Composer/Command/InitCommand.phpz@]z]=vendor/composer/composer/src/Composer/Command/ShowCommand.php]@]]+:Ҵ@vendor/composer/composer/src/Composer/Command/DependsCommand.phpt@]tzf@vendor/composer/composer/src/Composer/Command/RequireCommand.php1@]1IN=vendor/composer/composer/src/Composer/Command/HomeCommand.phpu@]uDi>vendor/composer/composer/src/Composer/Command/AboutCommand.php@]'|Avendor/composer/composer/src/Composer/Command/ValidateCommand.php6@]6!$1dGvendor/composer/composer/src/Composer/Command/BaseDependencyCommand.php-'@]-'8PtEvendor/composer/composer/src/Composer/Command/DumpAutoloadCommand.phph@]h@vendor/composer/composer/src/Composer/Command/ArchiveCommand.php@]> =vendor/composer/composer/src/Composer/Command/ExecCommand.php @] p<Avendor/composer/composer/src/Composer/Command/LicensesCommand.php@]2Bvendor/composer/composer/src/Composer/Command/ProhibitsCommand.php@]ٴ@vendor/composer/composer/src/Composer/Command/InstallCommand.php%@]%\4?vendor/composer/composer/src/Composer/Command/GlobalCommand.php @] f1=vendor/composer/composer/src/Composer/Command/BaseCommand.php@]Bi?vendor/composer/composer/src/Composer/Command/StatusCommand.php @] !Bvendor/composer/composer/src/Composer/Command/RunScriptCommand.php@]o2|qFvendor/composer/composer/src/Composer/Command/CreateProjectCommand.phpE@]Ef:?vendor/composer/composer/src/Composer/Command/UpdateCommand.php+@]+͞f?vendor/composer/composer/src/Composer/Command/SearchCommand.php @] K5ӴCvendor/composer/composer/src/Composer/Command/SelfUpdateCommand.phpB@]BE_ѴAvendor/composer/composer/src/Composer/Command/SuggestsCommand.php@]J}#?vendor/composer/composer/src/Composer/Command/RemoveCommand.php@]UDvendor/composer/composer/src/Composer/Command/ScriptAliasCommand.php@]fOAvendor/composer/composer/src/Composer/Command/DiagnoseCommand.phpkn@]kn/a]8vendor/composer/composer/src/Composer/Plugin/Capable.php@]'}Cvendor/composer/composer/src/Composer/Plugin/PreCommandRunEvent.phpM@]MÒ@ @vendor/composer/composer/src/Composer/Plugin/PluginInterface.php*@]*u*ִEvendor/composer/composer/src/Composer/Plugin/PreFileDownloadEvent.php7@]7JD=vendor/composer/composer/src/Composer/Plugin/PluginEvents.php@]@=vendor/composer/composer/src/Composer/Plugin/CommandEvent.php@]# Kvendor/composer/composer/src/Composer/Plugin/Capability/CommandProvider.php_@]_μFvendor/composer/composer/src/Composer/Plugin/Capability/Capability.php@]Y93>vendor/composer/composer/src/Composer/Plugin/PluginManager.php>@]>K1vendor/composer/composer/src/Composer/Factory.phpp_@]p_~Jvendor/composer/composer/src/Composer/Downloader/ChangeReportInterface.php@])ŸEvendor/composer/composer/src/Composer/Downloader/FossilDownloader.php@]k"oGvendor/composer/composer/src/Composer/Downloader/TransportException.php@]y#eRvendor/composer/composer/src/Composer/Downloader/VcsCapableDownloaderInterface.php@] Bvendor/composer/composer/src/Composer/Downloader/RarDownloader.php& @]& ´Bvendor/composer/composer/src/Composer/Downloader/GitDownloader.phpP@]PMB6Bvendor/composer/composer/src/Composer/Downloader/SvnDownloader.php@]]C Cvendor/composer/composer/src/Composer/Downloader/GzipDownloader.php* @]* rwBvendor/composer/composer/src/Composer/Downloader/TarDownloader.php@] fLvendor/composer/composer/src/Composer/Downloader/DvcsDownloaderInterface.php@]v(Fvendor/composer/composer/src/Composer/Downloader/ArchiveDownloader.php$@]$ͦDvendor/composer/composer/src/Composer/Downloader/DownloadManager.phpX)@]X)JHvendor/composer/composer/src/Composer/Downloader/DownloaderInterface.php@]Rz^Bvendor/composer/composer/src/Composer/Downloader/ZipDownloader.php!@]!tSIvendor/composer/composer/src/Composer/Downloader/PearPackageExtractor.php-@]-WCvendor/composer/composer/src/Composer/Downloader/PharDownloader.php@]x6Cvendor/composer/composer/src/Composer/Downloader/FileDownloader.php,@],ə!cBvendor/composer/composer/src/Composer/Downloader/VcsDownloader.php)@])X6Avendor/composer/composer/src/Composer/Downloader/HgDownloader.php @] bMܴHvendor/composer/composer/src/Composer/Downloader/FilesystemException.php@]Gvendor/composer/composer/src/Composer/Downloader/PerforceDownloader.php @] Avendor/composer/composer/src/Composer/Downloader/XzDownloader.php@]-DJCvendor/composer/composer/src/Composer/Downloader/PathDownloader.phpG#@]G#I$0vendor/composer/composer/src/Composer/Config.php5@@]5@3Bvendor/composer/composer/src/Composer/Installer/InstallerEvent.php @] Cvendor/composer/composer/src/Composer/Installer/PluginInstaller.php @] cAvendor/composer/composer/src/Composer/Installer/PackageEvents.php@]ZV@vendor/composer/composer/src/Composer/Installer/PackageEvent.phpT@]T[ڴFvendor/composer/composer/src/Composer/Installer/InstallerInterface.php @] {`Cvendor/composer/composer/src/Composer/Installer/BinaryInstaller.phpf@]f{Kvendor/composer/composer/src/Composer/Installer/BinaryPresenceInterface.php@]Gvendor/composer/composer/src/Composer/Installer/InstallationManager.php*@]*nwDDvendor/composer/composer/src/Composer/Installer/LibraryInstaller.php@]+_Dvendor/composer/composer/src/Composer/Installer/ProjectInstaller.php/ @]/ #DHvendor/composer/composer/src/Composer/Installer/MetapackageInstaller.php @] W%Gvendor/composer/composer/src/Composer/Installer/PearBinaryInstaller.phpT@]T|Avendor/composer/composer/src/Composer/Installer/PearInstaller.php6 @]6 x Avendor/composer/composer/src/Composer/Installer/NoopInstaller.phpn@]n1aCvendor/composer/composer/src/Composer/Installer/InstallerEvents.php@].!Mvendor/composer/composer/src/Composer/Installer/SuggestedPackagesReporter.php@]ډBvendor/composer/composer/src/Composer/Exception/NoSslException.php@]gBvendor/composer/composer/src/Composer/Repository/VcsRepository.php<@]<ORvendor/composer/composer/src/Composer/Repository/InstalledFilesystemRepository.php@]YGvendor/composer/composer/src/Composer/Repository/ArtifactRepository.phph @]h Jvendor/composer/composer/src/Composer/Repository/VersionCacheInterface.phpz@]zm%ݴDvendor/composer/composer/src/Composer/Repository/ArrayRepository.phpV@]VaNHvendor/composer/composer/src/Composer/Repository/CompositeRepository.phpW@]W2Kvendor/composer/composer/src/Composer/Repository/Vcs/GitBitbucketDriver.phpM @]M h9mKvendor/composer/composer/src/Composer/Repository/Vcs/VcsDriverInterface.php~ @]~ Hvendor/composer/composer/src/Composer/Repository/Vcs/BitbucketDriver.php5@]5YĴBvendor/composer/composer/src/Composer/Repository/Vcs/GitDriver.php@]YJvendor/composer/composer/src/Composer/Repository/Vcs/HgBitbucketDriver.phpG @]G *ڿNBvendor/composer/composer/src/Composer/Repository/Vcs/SvnDriver.php/@]/AEvendor/composer/composer/src/Composer/Repository/Vcs/GitLabDriver.php<@]< Evendor/composer/composer/src/Composer/Repository/Vcs/GitHubDriver.php=@]=DBvendor/composer/composer/src/Composer/Repository/Vcs/VcsDriver.php^@]^tlEvendor/composer/composer/src/Composer/Repository/Vcs/FossilDriver.php'@]'"cGvendor/composer/composer/src/Composer/Repository/Vcs/PerforceDriver.phpZ@]ZZAvendor/composer/composer/src/Composer/Repository/Vcs/HgDriver.phpY@]Y.Gvendor/composer/composer/src/Composer/Repository/ComposerRepository.phpK}@]K}ۜIvendor/composer/composer/src/Composer/Repository/FilesystemRepository.php @] a fPvendor/composer/composer/src/Composer/Repository/RepositorySecurityException.php@]<9Gvendor/composer/composer/src/Composer/Repository/PlatformRepository.php2@]2S Pvendor/composer/composer/src/Composer/Repository/WritableRepositoryInterface.php@]ugbCvendor/composer/composer/src/Composer/Repository/BaseRepository.php#@]#6Cvendor/composer/composer/src/Composer/Repository/PearRepository.php'"@]'"뛅ǴTvendor/composer/composer/src/Composer/Repository/ConfigurableRepositoryInterface.php@]6{Mvendor/composer/composer/src/Composer/Repository/InstalledArrayRepository.phpH@]H +;IFvendor/composer/composer/src/Composer/Repository/PackageRepository.php\@]\兴Fvendor/composer/composer/src/Composer/Repository/RepositoryManager.php@]^Cvendor/composer/composer/src/Composer/Repository/PathRepository.php@]3Qvendor/composer/composer/src/Composer/Repository/Pear/PackageDependencyParser.php*@]*o}Mvendor/composer/composer/src/Composer/Repository/Pear/ChannelRest10Reader.php@]>o9Nvendor/composer/composer/src/Composer/Repository/Pear/DependencyConstraint.php@]s2Hvendor/composer/composer/src/Composer/Repository/Pear/DependencyInfo.php@]-mEvendor/composer/composer/src/Composer/Repository/Pear/ChannelInfo.php@]sKvendor/composer/composer/src/Composer/Repository/Pear/BaseChannelReader.php @] H˴Mvendor/composer/composer/src/Composer/Repository/Pear/ChannelRest11Reader.php@]eδEvendor/composer/composer/src/Composer/Repository/Pear/PackageInfo.phpJ@]JrEvendor/composer/composer/src/Composer/Repository/Pear/ReleaseInfo.php@]3&Gvendor/composer/composer/src/Composer/Repository/Pear/ChannelReader.php @] xFvendor/composer/composer/src/Composer/Repository/RepositoryFactory.php$@]$ ȴLvendor/composer/composer/src/Composer/Repository/WritableArrayRepository.php@]dHvendor/composer/composer/src/Composer/Repository/RepositoryInterface.php@]􏉴Ovendor/composer/composer/src/Composer/Repository/InvalidRepositoryException.php@]$Qvendor/composer/composer/src/Composer/Repository/InstalledRepositoryInterface.phpC@]C#*vendor/composer/composer/src/bootstrap.php@]cAl!vendor/composer/autoload_real.phpn @]n >m!vendor/composer/autoload_psr4.php@]&vendor/composer/ClassLoader.php4@]4z2vendor/composer/spdx-licenses/src/SpdxLicenses.php#@]#*vendor/composer/ca-bundle/src/CaBundle.php6@]6nC/ 4vendor/composer/xdebug-handler/src/XdebugHandler.php@@]@K0vendor/composer/xdebug-handler/src/PhpConfig.php5@]5j$-vendor/composer/xdebug-handler/src/Status.php@]f.vendor/composer/xdebug-handler/src/Process.php@]q;,vendor/composer/semver/src/VersionParser.phpL@]L+&h%vendor/composer/semver/src/Semver.php @] =nQA4vendor/composer/semver/src/Constraint/Constraint.phpV@]Vzn=vendor/composer/semver/src/Constraint/ConstraintInterface.php^@]^)X<vendor/composer/semver/src/Constraint/AbstractConstraint.phpn@]n;9vendor/composer/semver/src/Constraint/EmptyConstraint.php8@]8)ʹ9vendor/composer/semver/src/Constraint/MultiConstraint.php& @]& ()vendor/composer/semver/src/Comparator.php @] g3 %vendor/composer/autoload_classmap.php@]GP&'vendor/composer/autoload_namespaces.php@]d-3vendor/symfony/finder/Expression/ValueInterface.php@]yz</vendor/symfony/finder/Expression/Expression.php @] R4*vendor/symfony/finder/Expression/Regex.phpW@]W)vendor/symfony/finder/Expression/Glob.php!@]!NŜ̴3vendor/symfony/finder/Comparator/DateComparator.php@]Gô/vendor/symfony/finder/Comparator/Comparator.php@]p5vendor/symfony/finder/Comparator/NumberComparator.php @]  vendor/symfony/finder/Finder.phpa@]ai^%vendor/symfony/finder/SplFileInfo.phpW@]W!tVb%vendor/symfony/finder/Shell/Shell.phpM@]M9'vendor/symfony/finder/Shell/Command.phpQ@]Q1vendor/symfony/finder/Adapter/AbstractAdapter.php@]8k2vendor/symfony/finder/Adapter/AdapterInterface.php@]”0vendor/symfony/finder/Adapter/BsdFindAdapter.php @] J+5vendor/symfony/finder/Adapter/AbstractFindAdapter.php?*@]?*0vendor/symfony/finder/Adapter/GnuFindAdapter.php @] ͂,vendor/symfony/finder/Adapter/PhpAdapter.phpq @]q ҔT9vendor/symfony/finder/Iterator/FilenameFilterIterator.php@] p<vendor/symfony/finder/Iterator/FilecontentFilterIterator.php@]r~;vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php@]4vendor/symfony/finder/Iterator/FilePathsIterator.phpS @]S +QAvendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php @] ,9vendor/symfony/finder/Iterator/FileTypeFilterIterator.php>@]>pY3vendor/symfony/finder/Iterator/SortableIterator.php @] v0ZN=vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php@]yM5vendor/symfony/finder/Iterator/PathFilterIterator.php@]}7vendor/symfony/finder/Iterator/CustomFilterIterator.php@] 1vendor/symfony/finder/Iterator/FilterIterator.php@]8=/=vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php @] 5:vendor/symfony/finder/Iterator/DateRangeFilterIterator.php@]@:vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php@]:~д6vendor/symfony/finder/Exception/ExceptionInterface.php@]79vendor/symfony/finder/Exception/AccessDeniedException.php@]cW޴Avendor/symfony/finder/Exception/OperationNotPermitedException.phpr@]r[&=;vendor/symfony/finder/Exception/AdapterFailureException.php@]@vendor/symfony/finder/Exception/ShellCommandFailureException.php[@][vendor/symfony/finder/Glob.php @] 2'vendor/symfony/polyfill-ctype/Ctype.php}@]}\谴+vendor/symfony/polyfill-ctype/bootstrap.phpS@]S7-vendor/symfony/polyfill-mbstring/Mbstring.phpk@]k1D@vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.phpI@]IFvendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php9@]9>|zK@vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.phpI@]I(~.vendor/symfony/polyfill-mbstring/bootstrap.php@].vendor/symfony/process/PhpExecutableFinder.phpk @]k W+vendor/symfony/process/ExecutableFinder.php @] s(%vendor/symfony/process/PhpProcess.phpp @]p E)vendor/symfony/process/ProcessBuilder.phpv@]vW"vendor/symfony/process/Process.php7@]7V)晴-vendor/symfony/process/Pipes/WindowsPipes.php@]B.vendor/symfony/process/Pipes/AbstractPipes.php@]9*vendor/symfony/process/Pipes/UnixPipes.phpT@]T]]/vendor/symfony/process/Pipes/PipesInterface.phpt@]t?_'vendor/symfony/process/ProcessUtils.php@] x3vendor/symfony/process/Exception/LogicException.php@]W=vendor/symfony/process/Exception/ProcessTimedOutException.php{@]{47vendor/symfony/process/Exception/ExceptionInterface.php@]<=vendor/symfony/process/Exception/InvalidArgumentException.php@]˅;vendor/symfony/process/Exception/ProcessFailedException.php@]P55vendor/symfony/process/Exception/RuntimeException.php@]>H9vendor/wp-cli/super-admin-command/super-admin-command.php@]=vendor/wp-cli/super-admin-command/src/Super_Admin_Command.php8@]8*|*vendor/wp-cli/export-command/functions.phpp@]p/vendor/wp-cli/export-command/export-command.php@]2d<vendor/wp-cli/export-command/src/WP_Export_WXR_Formatter.php&@]&HAvendor/wp-cli/export-command/src/WP_Export_Split_Files_Writer.php3 @]3 ƻ=vendor/wp-cli/export-command/src/WP_Export_Term_Exception.phpC@]CǴ3vendor/wp-cli/export-command/src/Export_Command.php2@]2Դ4vendor/wp-cli/export-command/src/WP_Export_Query.php4@]4T:vendor/wp-cli/export-command/src/WP_Export_File_Writer.php@]qj˴7vendor/wp-cli/export-command/src/WP_Export_Returner.phpB@]BM9vendor/wp-cli/export-command/src/WP_Post_IDs_Iterator.phpH@]H4vendor/wp-cli/export-command/src/WP_Map_Iterator.php@@]@ѱ<vendor/wp-cli/export-command/src/WP_Export_XML_Over_HTTP.phpk@]ke J:vendor/wp-cli/export-command/src/WP_Export_Base_Writer.php@]Ǵb:vendor/wp-cli/export-command/src/WP_Iterator_Exception.php9@]9w8vendor/wp-cli/export-command/src/WP_Export_Exception.php>@]>M5vendor/wp-cli/export-command/src/WP_Export_Oxymel.php@]bfL+vendor/wp-cli/core-command/core-command.php@]:/vendor/wp-cli/core-command/src/Core_Command.phpD@]DbIvendor/wp-cli/core-command/src/WP_CLI/Core/NonDestructiveCoreUpgrader.php@]!z~;vendor/wp-cli/core-command/src/WP_CLI/Core/CoreUpgrader.php@]nN-vendor/wp-cli/shell-command/shell-command.php @] ٷ1vendor/wp-cli/shell-command/src/Shell_Command.php=@]=_-5vendor/wp-cli/shell-command/src/WP_CLI/Shell/REPL.php @] Db-vendor/wp-cli/embed-command/embed-command.phpx@]x#δ4vendor/wp-cli/embed-command/src/Provider_Command.php@]}t4*vendor/wp-cli/embed-command/src/oEmbed.php@]p>4vendor/wp-cli/embed-command/src/Embeds_Namespace.php@]q1vendor/wp-cli/embed-command/src/Cache_Command.php@]mP3vendor/wp-cli/embed-command/src/Handler_Command.php@]`W1vendor/wp-cli/embed-command/src/Fetch_Command.php$@]$+vendor/wp-cli/wp-cli/utils/contrib-list.php@]TE:@vendor/wp-cli/wp-cli/utils/get-package-require-from-composer.php@] 3vendor/wp-cli/widget-command/src/Widget_Command.phpF@]FqWk4vendor/wp-cli/widget-command/src/Sidebar_Command.php@]d/vendor/wp-cli/widget-command/widget-command.phpD@]D 1vendor/wp-cli/rewrite-command/rewrite-command.php@]K5vendor/wp-cli/rewrite-command/src/Rewrite_Command.php0@]0;?vendor/wp-cli/wp-config-transformer/src/WPConfigTransformer.php)@])%״'vendor/wp-cli/server-command/router.phpN@]N73vendor/wp-cli/server-command/src/Server_Command.php, @], 6\/vendor/wp-cli/server-command/server-command.php@]+Cvendor/wp-cli/maintenance-mode-command/maintenance-mode-command.phpL@]L9v4Evendor/wp-cli/maintenance-mode-command/src/MaintenanceModeCommand.php7 @]7 02=@)vendor/wp-cli/mustangostang-spyc/Spyc.php@]x.vendor/wp-cli/mustangostang-spyc/php4/5to4.php@]uS])7vendor/wp-cli/mustangostang-spyc/includes/functions.php@]:-vendor/wp-cli/mustangostang-spyc/src/Spyc.php˅@]˅~-vendor/wp-cli/cache-command/cache-command.phpC@]C&'e1vendor/wp-cli/cache-command/src/Cache_Command.php1@]15Ŵ5vendor/wp-cli/cache-command/src/Transient_Command.phpD@]DJo3vendor/wp-cli/checksum-command/checksum-command.php@][zs<vendor/wp-cli/checksum-command/src/Checksum_Core_Command.php`@]`Y>vendor/wp-cli/checksum-command/src/Checksum_Plugin_Command.php>#@]>#{(qk<vendor/wp-cli/checksum-command/src/Checksum_Base_Command.phpM@]M?sGvendor/wp-cli/checksum-command/src/WP_CLI/Fetchers/UnfilteredPlugin.php:@]:<g?vendor/wp-cli/checksum-command/src/Plugin_Command_Namespace.php@]:f=vendor/wp-cli/checksum-command/src/Core_Command_Namespace.php@]{+vendor/wp-cli/i18n-command/i18n-command.php@]I/vendor/wp-cli/i18n-command/src/PotGenerator.phpQ@]Q1vendor/wp-cli/i18n-command/src/MakePotCommand.phpq@]q0/vendor/wp-cli/i18n-command/src/JedGenerator.phpm@]mʓ3vendor/wp-cli/i18n-command/src/CommandNamespace.php@]lh5vendor/wp-cli/i18n-command/src/JsFunctionsScanner.php@]8"*8vendor/wp-cli/i18n-command/src/IterableCodeExtractor.phpf @]f )3vendor/wp-cli/i18n-command/src/MapCodeExtractor.phpe@]evƴ2vendor/wp-cli/i18n-command/src/MakeJsonCommand.php@]3vendor/wp-cli/i18n-command/src/PhpCodeExtractor.php@]ya6vendor/wp-cli/i18n-command/src/PhpFunctionsScanner.php@]I2vendor/wp-cli/i18n-command/src/JsCodeExtractor.php@]]+vendor/wp-cli/role-command/role-command.php;@];av/vendor/wp-cli/role-command/src/Role_Command.phpr)@]r)/Դ7vendor/wp-cli/role-command/src/Capabilities_Command.php3@]3/vendor/wp-cli/import-command/import-command.php@]ʴ3vendor/wp-cli/import-command/src/Import_Command.php8@]8Ңs3vendor/wp-cli/scaffold-command/scaffold-command.php@]洃7vendor/wp-cli/scaffold-command/src/Scaffold_Command.php @] )-vendor/wp-cli/media-command/media-command.php@]6X1vendor/wp-cli/media-command/src/Media_Command.php@]?vendor/wp-cli/entity-command/src/WP_CLI/CommandWithDBObject.php@]#Rvendor/wp-cli/entity-command/src/WP_CLI/Entity/RecursiveDataStructureTraverser.php@]Lm8vendor/wp-cli/entity-command/src/WP_CLI/Entity/Utils.php@]y㦴Jvendor/wp-cli/entity-command/src/WP_CLI/Entity/NonExistentKeyException.php@]̱h:vendor/wp-cli/entity-command/src/Menu_Location_Command.php@]d1vendor/wp-cli/entity-command/src/Menu_Command.php @] ʹ9vendor/wp-cli/entity-command/src/Comment_Meta_Command.php@]Cq4vendor/wp-cli/entity-command/src/Comment_Command.phpB@]B\K6vendor/wp-cli/entity-command/src/Term_Meta_Command.php@]Bs5vendor/wp-cli/entity-command/src/Taxonomy_Command.php@];f6vendor/wp-cli/entity-command/src/User_Meta_Command.php$@]$RI|K3vendor/wp-cli/language-command/language-command.php1@]17g=vendor/wp-cli/language-command/src/Theme_Language_Command.php]1@]]1k9vendor/wp-cli/language-command/src/Language_Namespace.php@])|>vendor/wp-cli/language-command/src/Plugin_Language_Command.php3@]3BM<vendor/wp-cli/language-command/src/Core_Language_Command.php&@]&) ʴDvendor/wp-cli/language-command/src/WP_CLI/CommandWithTranslation.php @] iBvendor/wp-cli/language-command/src/WP_CLI/LanguagePackUpgrader.php @] rGCvendor/wp-cli/language-command/src/Site_Switch_Language_Command.php@]1$vendor/wp-cli/php-cli-tools/test.phpi@]i3M6vendor/wp-cli/php-cli-tools/lib/cli/notify/Spinner.php@]8u3vendor/wp-cli/php-cli-tools/lib/cli/notify/Dots.phpd@]dwz7vendor/wp-cli/php-cli-tools/lib/cli/arguments/Lexer.php^ @]^ G:vendor/wp-cli/php-cli-tools/lib/cli/arguments/Argument.php @] =Bvendor/wp-cli/php-cli-tools/lib/cli/arguments/InvalidArguments.php@]R<vendor/wp-cli/php-cli-tools/lib/cli/arguments/HelpScreen.php @] +B%-vendor/wp-cli/php-cli-tools/lib/cli/Shell.php @] mŻ,vendor/wp-cli/php-cli-tools/lib/cli/Tree.php@]@1vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php/@]/o4vendor/wp-cli/php-cli-tools/lib/cli/progress/Bar.php @] n(O-vendor/wp-cli/php-cli-tools/lib/cli/Table.php@]t*/vendor/wp-cli/php-cli-tools/lib/cli/Streams.php"@]"+f +vendor/wp-cli/php-cli-tools/lib/cli/cli.php@@]@~z״/vendor/wp-cli/php-cli-tools/lib/cli/Memoize.php@].vendor/wp-cli/php-cli-tools/lib/cli/Colors.phpk!@]k!y6)2vendor/wp-cli/php-cli-tools/lib/cli/tree/Ascii.phpx@]x95vendor/wp-cli/php-cli-tools/lib/cli/tree/Renderer.phpO@]Oc"Ӵ5vendor/wp-cli/php-cli-tools/lib/cli/tree/Markdown.php@]T魴5vendor/wp-cli/php-cli-tools/lib/cli/unicode/regex.phpb@]bɶ9ʹ.vendor/wp-cli/php-cli-tools/lib/cli/Notify.php@],3vendor/wp-cli/php-cli-tools/lib/cli/table/Ascii.php @] @%=5vendor/wp-cli/php-cli-tools/lib/cli/table/Tabular.php@]l6vendor/wp-cli/php-cli-tools/lib/cli/table/Renderer.phpG@]GYߒ0vendor/wp-cli/php-cli-tools/lib/cli/Progress.php @] a,vendor/wp-cli/php-cli-tools/http-console.php@]>5vendor/wp-cli/extension-command/extension-command.php@]@J86vendor/wp-cli/extension-command/src/Plugin_Command.php@]״=vendor/wp-cli/extension-command/src/WP_CLI/Fetchers/Theme.php @] 3>vendor/wp-cli/extension-command/src/WP_CLI/Fetchers/Plugin.php"@]" F Hvendor/wp-cli/extension-command/src/WP_CLI/DestructivePluginUpgrader.php@]$QrGvendor/wp-cli/extension-command/src/WP_CLI/DestructiveThemeUpgrader.php@]hE!Avendor/wp-cli/extension-command/src/WP_CLI/CommandWithUpgrade.phpY@]Y [5vendor/wp-cli/extension-command/src/Theme_Command.phpk@]kL9vendor/wp-cli/extension-command/src/Theme_Mod_Command.php@]MO{+vendor/wp-cli/eval-command/eval-command.php=@]=Ak/vendor/wp-cli/eval-command/src/Eval_Command.phpR@]Rx_i3vendor/wp-cli/eval-command/src/EvalFile_Command.php8@]8:!+vendor/wp-cli/cron-command/cron-command.php@].5vendor/wp-cli/cron-command/src/Cron_Event_Command.php3@]3{C/vendor/wp-cli/cron-command/src/Cron_Command.php @] o8vendor/wp-cli/cron-command/src/Cron_Schedule_Command.phpi @]i @'vendor/wp-cli/db-command/db-command.php@]k+vendor/wp-cli/db-command/src/DB_Command.php@]6/vendor/wp-cli/config-command/config-command.php@]7Q3vendor/wp-cli/config-command/src/Config_Command.phpfc@]fcR8(vendor/nb/oxymel/OxymelTest.php@]BLVvendor/nb/oxymel/Oxymel.php)@])(rմ%vendor/psr/log/Psr/Log/NullLogger.php@]I*vendor/psr/log/Psr/Log/LoggerInterface.php @] d?)vendor/psr/log/Psr/Log/AbstractLogger.php @] Gl&vendor/psr/log/Psr/Log/LoggerTrait.phpW @]W Wj+vendor/psr/log/Psr/Log/LoggerAwareTrait.php@]z%3vendor/psr/log/Psr/Log/InvalidArgumentException.php`@]` X1/vendor/psr/log/Psr/Log/LoggerAwareInterface.php)@])j #vendor/psr/log/Psr/Log/LogLevel.phpP@]P)vendor/seld/phar-utils/src/Timestamps.php@]ׁ60vendor/seld/jsonlint/src/Seld/JsonLint/Lexer.phpe@]e)$4vendor/seld/jsonlint/src/Seld/JsonLint/Undefined.php@]g;vendor/seld/jsonlint/src/Seld/JsonLint/ParsingException.php0@]0K粴@vendor/seld/jsonlint/src/Seld/JsonLint/DuplicateKeyException.php8@]8 5vendor/seld/jsonlint/src/Seld/JsonLint/JsonParser.phpP@]PCۂ/vendor/symfony/console/Logger/ConsoleLogger.php @] n,vendor/symfony/console/Style/OutputStyle.php@]jK-vendor/symfony/console/Style/SymfonyStyle.phpvendor/symfony/console/Formatter/OutputFormatterStyleStack.php @] 94vendor/symfony/console/Formatter/OutputFormatter.php@]KBvendor/symfony/console/Formatter/OutputFormatterStyleInterface.php7@]7.@Y=vendor/symfony/console/Formatter/OutputFormatterInterface.php@]#7u6vendor/symfony/console/Helper/DebugFormatterHelper.phpW@]W 2vendor/symfony/console/Helper/DescriptorHelper.php1 @]1 ^x1vendor/symfony/console/Helper/HelperInterface.phpp@]pn2vendor/symfony/console/Helper/InputAwareHelper.php@]+vendor/symfony/console/Helper/HelperSet.phpi @]i %0vendor/symfony/console/Helper/ProgressHelper.phpP1@]P1_;!-vendor/symfony/console/Helper/TableHelper.php@]su}/vendor/symfony/console/Helper/ProcessHelper.php@] д0vendor/symfony/console/Helper/TableSeparator.php@]=_0vendor/symfony/console/Helper/QuestionHelper.php6@]6Q@'vendor/symfony/console/Helper/Table.phpI@]I{1vendor/symfony/console/Helper/FormatterHelper.php @] jߕ.vendor/symfony/console/Helper/DialogHelper.phpD@]Dzr7vendor/symfony/console/Helper/SymfonyQuestionHelper.php@]=-vendor/symfony/console/Helper/ProgressBar.phpE@]E{z(vendor/symfony/console/Helper/Helper.php @]  3vendor/symfony/console/Helper/ProgressIndicator.php!@]!Q},vendor/symfony/console/Helper/TableStyle.php{@]{6ϳ]+vendor/symfony/console/Helper/TableCell.phpz@]zq8vendor/symfony/console/Output/ConsoleOutputInterface.php@]/vendor/symfony/console/Output/ConsoleOutput.php]@]],,vendor/symfony/console/Output/NullOutput.phpn@]ntD.vendor/symfony/console/Output/StreamOutput.php(@](݋(vendor/symfony/console/Output/Output.php{@]{70vendor/symfony/console/Output/BufferedOutput.phpH@]H9Դ1vendor/symfony/console/Output/OutputInterface.php @] 7ڴ4vendor/symfony/console/Event/ConsoleCommandEvent.php%@]%{˾6vendor/symfony/console/Event/ConsoleTerminateEvent.php@]{e-vendor/symfony/console/Event/ConsoleEvent.php@] 6vendor/symfony/console/Event/ConsoleExceptionEvent.php=@]=Ŵ4vendor/symfony/console/Input/InputAwareInterface.php:@]: '0vendor/symfony/console/Input/InputDefinition.php2@]2Vq&vendor/symfony/console/Input/Input.php^@]^~w].vendor/symfony/console/Input/InputArgument.phpT @]T +4+vendor/symfony/console/Input/ArrayInput.php@]pMq,vendor/symfony/console/Input/StringInput.php @] e,vendor/symfony/console/Input/InputOption.php@]Y*vendor/symfony/console/Input/ArgvInput.php)@])Yw/vendor/symfony/console/Input/InputInterface.php@].vendor/symfony/console/Command/ListCommand.phpo @]o Y.vendor/symfony/console/Command/HelpCommand.php @] Dž*vendor/symfony/console/Command/Command.phpN@]NӸY3vendor/symfony/console/Exception/LogicException.php@]SML;vendor/symfony/console/Exception/InvalidOptionException.php@];7vendor/symfony/console/Exception/ExceptionInterface.php@]U=vendor/symfony/console/Exception/CommandNotFoundException.php@]=vendor/symfony/console/Exception/InvalidArgumentException.php@]u i5vendor/symfony/console/Exception/RuntimeException.php@]*b(vendor/symfony/filesystem/Filesystem.phpe@]e@]>o5Jvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Constraint.phpX@]X\vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeCheck/TypeCheckInterface.php@]c>ϴXvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeCheck/LooseTypeCheck.php@] Yvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeCheck/StrictTypeCheck.php+@]+QܴNvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/EnumConstraint.phpq@]q` Svendor/justinrainbow/json-schema/src/JsonSchema/Constraints/ConstraintInterface.php@]teTvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/CollectionConstraint.php@]NNvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeConstraint.php&@]&ٌ]Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/ObjectConstraint.php@]FgcPvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/NumberConstraint.php @] 9|Gvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Factory.phpF@]F:0/Nvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/BaseConstraint.php%@]%2=vendor/justinrainbow/json-schema/src/JsonSchema/Validator.php @] 8Fvendor/justinrainbow/json-schema/src/JsonSchema/Entity/JsonPointer.php> @]> WKvendor/justinrainbow/json-schema/src/JsonSchema/Iterator/ObjectIterator.php @] HWvendor/justinrainbow/json-schema/src/JsonSchema/Exception/ResourceNotFoundException.phpT@]T:Rvendor/justinrainbow/json-schema/src/JsonSchema/Exception/UriResolverException.phpJ@]J-Pvendor/justinrainbow/json-schema/src/JsonSchema/Exception/ExceptionInterface.phpI@]I%|Wvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSourceUriException.php\@]\iRTvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSchemaException.phpN@]Nݠ^vendor/justinrainbow/json-schema/src/JsonSchema/Exception/UnresolvableJsonPointerException.php@].miTvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidConfigException.phpQ@]QJQvendor/justinrainbow/json-schema/src/JsonSchema/Exception/ValidationException.php@]EB*Vvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidArgumentException.phpy@]yWΖ]vendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.phpW@]W%*)ִNvendor/justinrainbow/json-schema/src/JsonSchema/Exception/RuntimeException.phpa@]a`Svendor/justinrainbow/json-schema/src/JsonSchema/Exception/JsonDecodingException.php@]٣4vendor/gettext/languages/bin/export-plural-rules.php*$@]*${ Nb+vendor/gettext/languages/src/autoloader.phpU@]UV )vendor/gettext/languages/src/Category.php@]1vendor/gettext/languages/src/FormulaConverter.php@]gW-vendor/gettext/languages/src/Exporter/Php.phpx@]x7?X2vendor/gettext/languages/src/Exporter/Exporter.php0@]0pӴ,vendor/gettext/languages/src/Exporter/Po.php4@]4+4vendor/gettext/languages/src/Exporter/Prettyjson.php@].vendor/gettext/languages/src/Exporter/Html.phpH @]H {Ÿ.vendor/gettext/languages/src/Exporter/Json.phpb@]bW@4.vendor/gettext/languages/src/Exporter/Docs.php@]S \-vendor/gettext/languages/src/Exporter/Xml.php@]1)vendor/gettext/languages/src/CldrData.php5@]5[eA)vendor/gettext/languages/src/Language.php=@]=n]e)vendor/gettext/gettext/src/autoloader.php@]Ap$vendor/gettext/gettext/src/Merge.phpD@]Dm6P2vendor/gettext/gettext/src/TranslatorInterface.php% @]% /vendor/gettext/gettext/src/Generators/Xliff.php6@]6þQ,vendor/gettext/gettext/src/Generators/Po.php @] (S<vendor/gettext/gettext/src/Generators/GeneratorInterface.php@] g.vendor/gettext/gettext/src/Generators/Json.phpO@]Of'N7vendor/gettext/gettext/src/Generators/CsvDictionary.php@]CT 8vendor/gettext/gettext/src/Generators/YamlDictionary.php@]L5-vendor/gettext/gettext/src/Generators/Csv.php@]{.vendor/gettext/gettext/src/Generators/Yaml.php@]2vendor/gettext/gettext/src/Generators/PhpArray.php@]H;8vendor/gettext/gettext/src/Generators/JsonDictionary.php=@]={-vendor/gettext/gettext/src/Generators/Jed.phpp@]p,k.3vendor/gettext/gettext/src/Generators/Generator.php@]3,vendor/gettext/gettext/src/Generators/Mo.php@]0д+vendor/gettext/gettext/src/Translations.php@@]@;.vendor/gettext/gettext/src/Extractors/Twig.php<@]<K/vendor/gettext/gettext/src/Extractors/Xliff.php @] W},vendor/gettext/gettext/src/Extractors/Po.php@] ԴAvendor/gettext/gettext/src/Extractors/ExtractorMultiInterface.php@]].vendor/gettext/gettext/src/Extractors/Json.php.@].w=u7vendor/gettext/gettext/src/Extractors/CsvDictionary.phpR@]RWG8vendor/gettext/gettext/src/Extractors/YamlDictionary.phpQ@]Qts/vendor/gettext/gettext/src/Extractors/Blade.phpj@]j{7-vendor/gettext/gettext/src/Extractors/Csv.php@]m8´.vendor/gettext/gettext/src/Extractors/Yaml.php]@]]jя"2vendor/gettext/gettext/src/Extractors/PhpArray.phpG@]G/DѴ<vendor/gettext/gettext/src/Extractors/ExtractorInterface.php @] p}Yд/vendor/gettext/gettext/src/Extractors/VueJs.php5@]5QD8vendor/gettext/gettext/src/Extractors/JsonDictionary.php(@](-*1vendor/gettext/gettext/src/Extractors/PhpCode.php?@]?…'-vendor/gettext/gettext/src/Extractors/Jed.php@]{c,vendor/gettext/gettext/src/Extractors/Mo.phpm@]mep3vendor/gettext/gettext/src/Extractors/Extractor.php@] {n0vendor/gettext/gettext/src/Extractors/JsCode.php(@](8vU)vendor/gettext/gettext/src/Translator.php@]J>*vendor/gettext/gettext/src/Translation.php+@]+90vendor/gettext/gettext/src/GettextTranslator.php@]޼|3vendor/gettext/gettext/src/translator_functions.php0@]0ȴ-vendor/gettext/gettext/src/BaseTranslator.php@]3vĴ?vendor/gettext/gettext/src/Utils/MultidimensionalArrayTrait.php @] i$a4vendor/gettext/gettext/src/Utils/DictionaryTrait.php@]'1vendor/gettext/gettext/src/Utils/StringReader.php@]P-vendor/gettext/gettext/src/Utils/CsvTrait.php@]S*3vendor/gettext/gettext/src/Utils/ParsedFunction.phpq@]qBWc5vendor/gettext/gettext/src/Utils/FunctionsScanner.phpH@]HD|7vendor/gettext/gettext/src/Utils/JsFunctionsScanner.php$@]$(d:vendor/gettext/gettext/src/Utils/HeadersExtractorTrait.php~@]~д:vendor/gettext/gettext/src/Utils/HeadersGeneratorTrait.php7@]76ÉG8vendor/gettext/gettext/src/Utils/PhpFunctionsScanner.php@]©m,2vendor/gettext/gettext/src/Utils/ParsedComment.php\ @]\ ܺC*vendor/mck89/peast/lib/Peast/Traverser.php@]J8vendor/mck89/peast/lib/Peast/Syntax/CommentsRegistry.php )@] )|/vendor/mck89/peast/lib/Peast/Syntax/Scanner.php@]~[N+vendor/mck89/peast/lib/Peast/Syntax/LSM.php@]7O-vendor/mck89/peast/lib/Peast/Syntax/Token.php @] ;/V6vendor/mck89/peast/lib/Peast/Syntax/SourceLocation.php@]جA6vendor/mck89/peast/lib/Peast/Syntax/ES2019/Scanner.php@] ϴ5vendor/mck89/peast/lib/Peast/Syntax/ES2019/Parser.php@] l5vendor/mck89/peast/lib/Peast/Syntax/EventsEmitter.php@]{u=vendor/mck89/peast/lib/Peast/Syntax/Node/UpdateExpression.php; @]; 3m9vendor/mck89/peast/lib/Peast/Syntax/Node/ForStatement.phpC @]C 1>vendor/mck89/peast/lib/Peast/Syntax/Node/ModuleDeclaration.php@]nt4vendor/mck89/peast/lib/Peast/Syntax/Node/Literal.php@]5ʴ;vendor/mck89/peast/lib/Peast/Syntax/Node/ThisExpression.php@]%a=vendor/mck89/peast/lib/Peast/Syntax/Node/BinaryExpression.phpW@]W[:vendor/mck89/peast/lib/Peast/Syntax/Node/SpreadElement.php@]%?vendor/mck89/peast/lib/Peast/Syntax/Node/SequenceExpression.php@]Cvendor/mck89/peast/lib/Peast/Syntax/Node/ImportDefaultSpecifier.php@]J;vendor/mck89/peast/lib/Peast/Syntax/Node/NumericLiteral.php@]&O6vendor/mck89/peast/lib/Peast/Syntax/Node/ClassBody.phpH@]HhZ8vendor/mck89/peast/lib/Peast/Syntax/Node/RestElement.php@]č<vendor/mck89/peast/lib/Peast/Syntax/Node/ReturnStatement.php@]:C4vendor/mck89/peast/lib/Peast/Syntax/Node/Pattern.php@]6vendor/mck89/peast/lib/Peast/Syntax/Node/Statement.php@]=vendor/mck89/peast/lib/Peast/Syntax/Node/MemberExpression.php @] |K Evendor/mck89/peast/lib/Peast/Syntax/Node/ImportNamespaceSpecifier.php@]Mc>vendor/mck89/peast/lib/Peast/Syntax/Node/ContinueStatement.php@]ZYEvendor/mck89/peast/lib/Peast/Syntax/Node/TaggedTemplateExpression.php\@]\:vendor/mck89/peast/lib/Peast/Syntax/Node/WithStatement.phpd@]d|J:vendor/mck89/peast/lib/Peast/Syntax/Node/StringLiteral.php @] 5v;vendor/mck89/peast/lib/Peast/Syntax/Node/ForInStatement.php @] P㛴<vendor/mck89/peast/lib/Peast/Syntax/Node/ModuleSpecifier.phpO@]O9EM<vendor/mck89/peast/lib/Peast/Syntax/Node/SwitchStatement.php@];vendor/mck89/peast/lib/Peast/Syntax/Node/CallExpression.phpe@]e!8vendor/mck89/peast/lib/Peast/Syntax/Node/CatchClause.php@]<vendor/mck89/peast/lib/Peast/Syntax/Node/ArrayExpression.php@]t88vendor/mck89/peast/lib/Peast/Syntax/Node/IfStatement.php @] {Dvendor/mck89/peast/lib/Peast/Syntax/Node/ParenthesizedExpression.php@](Ӵ8vendor/mck89/peast/lib/Peast/Syntax/Node/Declaration.php@]84>vendor/mck89/peast/lib/Peast/Syntax/Node/DebuggerStatement.php@]di=vendor/mck89/peast/lib/Peast/Syntax/Node/MethodDefinition.php@]uѴ;vendor/mck89/peast/lib/Peast/Syntax/Node/BooleanLiteral.phpI@]Im|Avendor/mck89/peast/lib/Peast/Syntax/Node/ExportAllDeclaration.phpa@]a~& =vendor/mck89/peast/lib/Peast/Syntax/Node/ObjectExpression.php@]'!E7vendor/mck89/peast/lib/Peast/Syntax/Node/SwitchCase.phpX@]XE <vendor/mck89/peast/lib/Peast/Syntax/Node/UnaryExpression.phpR @]R ~uҴ2vendor/mck89/peast/lib/Peast/Syntax/Node/Super.php@]RC(;vendor/mck89/peast/lib/Peast/Syntax/Node/EmptyStatement.php@]n;vendor/mck89/peast/lib/Peast/Syntax/Node/ForOfStatement.php@],5vendor/mck89/peast/lib/Peast/Syntax/Node/Property.php@] <vendor/mck89/peast/lib/Peast/Syntax/Node/ExportSpecifier.php@]L<vendor/mck89/peast/lib/Peast/Syntax/Node/TemplateElement.php @] 7Ѵ;vendor/mck89/peast/lib/Peast/Syntax/Node/BreakStatement.phpy@]y 24vendor/mck89/peast/lib/Peast/Syntax/Node/Program.php@]:A>vendor/mck89/peast/lib/Peast/Syntax/Node/ImportDeclaration.php@]X9<vendor/mck89/peast/lib/Peast/Syntax/Node/YieldExpression.php3@]35:vendor/mck89/peast/lib/Peast/Syntax/Node/ObjectPattern.php@]ܴCvendor/mck89/peast/lib/Peast/Syntax/Node/ExportNamedDeclaration.php @] ?vendor/mck89/peast/lib/Peast/Syntax/Node/AssignmentProperty.php@]Y<vendor/mck89/peast/lib/Peast/Syntax/Node/ImportSpecifier.php@]H꽴=vendor/mck89/peast/lib/Peast/Syntax/Node/DoWhileStatement.php2@]24vendor/mck89/peast/lib/Peast/Syntax/Node/Comment.phpX@]XX 7vendor/mck89/peast/lib/Peast/Syntax/Node/Identifier.php@]:vendor/mck89/peast/lib/Peast/Syntax/Node/RegExpLiteral.phpX @]X D493vendor/mck89/peast/lib/Peast/Syntax/Node/Class_.phpy@]yn7vendor/mck89/peast/lib/Peast/Syntax/Node/Expression.php@]zw!9vendor/mck89/peast/lib/Peast/Syntax/Node/MetaProperty.php@]: <vendor/mck89/peast/lib/Peast/Syntax/Node/AwaitExpression.phpU@]UBvendor/mck89/peast/lib/Peast/Syntax/Node/ConditionalExpression.php @] 8vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXText.php@]?HCvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXSpreadAttribute.php@]=W>vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXIdentifier.php@]hvDvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXMemberExpression.php^@]^1*G<vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXFragment.php @] P״Bvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXOpeningElement.php@]DDd;vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXElement.php @] !H?vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXSpreadChild.php@]׏ʹCvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXClosingFragment.php@]|<_Bvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXClosingElement.php@]f=vendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXAttribute.phpx@]xb.iCvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXEmptyExpression.php@][-SCvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXBoundaryElement.phpz@]z KNGvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXExpressionContainer.php@]]OCvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXOpeningFragment.php@]p Bvendor/mck89/peast/lib/Peast/Syntax/Node/JSX/JSXNamespacedName.php|@]|ʹ=vendor/mck89/peast/lib/Peast/Syntax/Node/ClassDeclaration.php@]%^j:vendor/mck89/peast/lib/Peast/Syntax/Node/NewExpression.php@]><vendor/mck89/peast/lib/Peast/Syntax/Node/TemplateLiteral.phpN @]N D9vendor/mck89/peast/lib/Peast/Syntax/Node/TryStatement.php @] xk;vendor/mck89/peast/lib/Peast/Syntax/Node/WhileStatement.php*@]*ꮓ@vendor/mck89/peast/lib/Peast/Syntax/Node/FunctionDeclaration.php@]D*Avendor/mck89/peast/lib/Peast/Syntax/Node/AssignmentExpression.php2 @]2 T?vendor/mck89/peast/lib/Peast/Syntax/Node/FunctionExpression.php@]UEvendor/mck89/peast/lib/Peast/Syntax/Node/ExportDefaultDeclaration.php@]3" Dvendor/mck89/peast/lib/Peast/Syntax/Node/ArrowFunctionExpression.php@]х6vendor/mck89/peast/lib/Peast/Syntax/Node/Function_.php @] wv1vendor/mck89/peast/lib/Peast/Syntax/Node/Node.php!@]!?vendor/mck89/peast/lib/Peast/Syntax/Node/VariableDeclarator.php@]bٴ@vendor/mck89/peast/lib/Peast/Syntax/Node/VariableDeclaration.phpc@]cI8vendor/mck89/peast/lib/Peast/Syntax/Node/NullLiteral.php@]K>vendor/mck89/peast/lib/Peast/Syntax/Node/AssignmentPattern.php@]RY;vendor/mck89/peast/lib/Peast/Syntax/Node/ThrowStatement.phpl@]l;vendor/mck89/peast/lib/Peast/Syntax/Node/BlockStatement.php@]@vendor/mck89/peast/lib/Peast/Syntax/Node/ExpressionStatement.php@][m>vendor/mck89/peast/lib/Peast/Syntax/Node/LogicalExpression.phpZ@]ZS9vendor/mck89/peast/lib/Peast/Syntax/Node/ArrayPattern.php@]ʑ(<vendor/mck89/peast/lib/Peast/Syntax/Node/ClassExpression.php@]p~ô=vendor/mck89/peast/lib/Peast/Syntax/Node/LabeledStatement.php@](.vendor/mck89/peast/lib/Peast/Syntax/Parser.phpJ#@]J#v6ʴ3vendor/mck89/peast/lib/Peast/Syntax/JSX/Scanner.phpe @]e Ѵ2vendor/mck89/peast/lib/Peast/Syntax/JSX/Parser.phpr6@]r6q6vendor/mck89/peast/lib/Peast/Syntax/ES2016/Scanner.php@]ȷ5vendor/mck89/peast/lib/Peast/Syntax/ES2016/Parser.phpR@]Ra 66vendor/mck89/peast/lib/Peast/Syntax/ES2018/Scanner.php@]q5vendor/mck89/peast/lib/Peast/Syntax/ES2018/Parser.php6@]6PT-vendor/mck89/peast/lib/Peast/Syntax/Utils.php?@]?1U9vendor/mck89/peast/lib/Peast/Syntax/EncodingException.php@]Lp6vendor/mck89/peast/lib/Peast/Syntax/ES2015/Scanner.php @] HiX5vendor/mck89/peast/lib/Peast/Syntax/ES2015/Parser.phpV@]V=1vendor/mck89/peast/lib/Peast/Syntax/Exception.phpD@]DB͌6vendor/mck89/peast/lib/Peast/Syntax/ES2017/Scanner.php>@]>D5vendor/mck89/peast/lib/Peast/Syntax/ES2017/Parser.php}S@]}Sp0vendor/mck89/peast/lib/Peast/Syntax/Position.php@]#C.6vendor/mck89/peast/lib/Peast/Formatter/PrettyPrint.phpr@]rjϴ2vendor/mck89/peast/lib/Peast/Formatter/Compact.php@]t/vendor/mck89/peast/lib/Peast/Formatter/Base.php @] |n›3vendor/mck89/peast/lib/Peast/Formatter/Expanded.php@]x&vendor/mck89/peast/lib/Peast/Peast.phpC@]C무)vendor/mck89/peast/lib/Peast/Renderer.phpٖ@]ٖb4+vendor/wp-cli/wp-cli/templates/man.mustache@]I<2vendor/wp-cli/wp-cli/templates/man-params.mustache@]C9vendor/wp-cli/config-command/templates/wp-config.mustache @] 6vendor/wp-cli/core-command/templates/versions.mustache@]SU"?vendor/wp-cli/extension-command/templates/theme-status.mustachex@]xǁgѴ@vendor/wp-cli/extension-command/templates/plugin-status.mustache@]o[5;vendor/wp-cli/scaffold-command/templates/block-php.mustache'@]'oBvendor/wp-cli/scaffold-command/templates/plugin-gitignore.mustache^@]^怴8vendor/wp-cli/scaffold-command/templates/plugin.mustacheq@]qGqҴDvendor/wp-cli/scaffold-command/templates/plugin-test-sample.mustache'@]'\~?vendor/wp-cli/scaffold-command/templates/plugin-gitlab.mustache\@]\ ?vendor/wp-cli/scaffold-command/templates/plugin-circle.mustacheB @]B /G2Bvendor/wp-cli/scaffold-command/templates/plugin-bootstrap.mustaches@]sԨvAvendor/wp-cli/scaffold-command/templates/block-style-css.mustache@]شCvendor/wp-cli/scaffold-command/templates/plugin-distignore.mustache@@]@pU%~>vendor/wp-cli/scaffold-command/templates/theme-status.mustachex@]xǁgѴ<vendor/wp-cli/scaffold-command/templates/install-wp-tests.sh@]a*6vendor/wp-cli/scaffold-command/templates/.editorconfig@]hѴ?vendor/wp-cli/scaffold-command/templates/plugin-readme.mustache@]b Cvendor/wp-cli/scaffold-command/templates/theme-test-sample.mustache&@]&Bvendor/wp-cli/scaffold-command/templates/block-editor-css.mustache@],V]Gvendor/wp-cli/scaffold-command/templates/child_theme_functions.mustacheS@]S WDvendor/wp-cli/scaffold-command/templates/post_type_extended.mustache@],@vendor/wp-cli/scaffold-command/templates/block-index-js.mustache @] "0:vendor/wp-cli/scaffold-command/templates/taxonomy.mustacheU @]U 8=vendor/wp-cli/scaffold-command/templates/child_theme.mustache@]Cvendor/wp-cli/scaffold-command/templates/taxonomy_extended.mustache@]0;vendor/wp-cli/scaffold-command/templates/post_type.mustache @] x8vendor/wp-cli/scaffold-command/templates/.phpcs.xml.distg@]g4Avendor/wp-cli/scaffold-command/templates/plugin-packages.mustache^@]^5+9vendor/wp-cli/scaffold-command/templates/phpunit.xml.dist@]%F?vendor/wp-cli/scaffold-command/templates/plugin-travis.mustacheZ@]Z#(Bvendor/wp-cli/scaffold-command/templates/plugin-bitbucket.mustache@]ZBgmAvendor/wp-cli/scaffold-command/templates/theme-bootstrap.mustache@]DBvendor/wp-cli/scaffold-command/templates/plugin-gruntfile.mustache@]Tvendor/autoload.php@]4 vendor/composer/composer/LICENSE,@],Vg1vendor/composer/composer/res/composer-schema.json@] <vendor/rmccue/requests/library/Requests/Transport/cacert.pem~@]~a#^&vendor/wp-cli/wp-cli/COMPOSER_VERSIONS@]Gvendor/wp-cli/wp-cli/VERSION@]:S array( 'runtime' => '=', 'file' => '', 'desc' => 'Path to the WordPress files.', ), 'url' => array( 'runtime' => '=', 'file' => '', 'desc' => 'Pretend request came from given URL. In multisite, this argument is how the target site is specified.', ), 'ssh' => array( 'runtime' => '=[:][@][:][]', 'file' => '[:][@][:][]', 'desc' => 'Perform operation against a remote server over SSH (or a container using scheme of "docker", "docker-compose", "vagrant").', ), 'http' => array( 'runtime' => '=', 'file' => '', 'desc' => 'Perform operation against a remote WordPress installation over HTTP.', ), 'blog' => array( 'deprecated' => 'Use --url instead.', 'runtime' => '=', ), 'user' => array( 'runtime' => '=', 'file' => '', 'desc' => 'Set the WordPress user.', ), 'skip-plugins' => array( 'runtime' => '[=]', 'file' => '', 'desc' => 'Skip loading all plugins, or a comma-separated list of plugins. Note: mu-plugins are still loaded.', 'default' => '', ), 'skip-themes' => array( 'runtime' => '[=]', 'file' => '', 'desc' => 'Skip loading all themes, or a comma-separated list of themes.', 'default' => '', ), 'skip-packages' => array( 'runtime' => '', 'file' => '', 'desc' => 'Skip loading all installed packages.', 'default' => false, ), 'require' => array( 'runtime' => '=', 'file' => '', 'desc' => 'Load PHP file before running the command (may be used more than once).', 'multiple' => true, 'default' => array(), ), 'disabled_commands' => array( 'file' => '', 'default' => array(), 'desc' => '(Sub)commands to disable.', ), 'color' => array( 'runtime' => true, 'file' => '', 'default' => 'auto', 'desc' => 'Whether to colorize the output.', ), 'debug' => array( 'runtime' => '[=]', 'file' => '', 'default' => false, 'desc' => 'Show all PHP errors and add verbosity to WP-CLI output. Built-in groups include: bootstrap, commandfactory, and help.', ), 'prompt' => array( 'runtime' => '[=]', 'file' => false, 'default' => false, 'desc' => 'Prompt the user to enter values for all command arguments, or a subset specified as comma-separated values.', ), 'quiet' => array( 'runtime' => '', 'file' => '', 'default' => false, 'desc' => 'Suppress informational messages.', ), 'apache_modules' => array( 'file' => '', 'desc' => 'List of Apache Modules that are to be reported as loaded.', 'multiple' => true, 'default' => array(), ), # --allow-root => (NOT RECOMMENDED) Allow wp-cli to run as root. This poses # a security risk, so you probably do not want to do this. 'allow-root' => array( 'file' => false, # Explicit. Just in case the default changes. 'runtime' => '', 'hidden' => true, ), ); config ) && ! empty( $composer->config->{'vendor-dir'} ) ) { array_unshift( $vendor_paths, WP_CLI_ROOT . '/../../../' . $composer->config->{'vendor-dir'} ); } } return $vendor_paths; } // Using require() directly inside a class grants access to private methods to the loaded code. function load_file( $path ) { require_once $path; } function load_command( $name ) { $path = WP_CLI_ROOT . "/php/commands/$name.php"; if ( is_readable( $path ) ) { include_once $path; } } /** * Like array_map(), except it returns a new iterator, instead of a modified array. * * Example: * * $arr = array('Football', 'Socker'); * * $it = iterator_map($arr, 'strtolower', function($val) { * return str_replace('foo', 'bar', $val); * }); * * foreach ( $it as $val ) { * var_dump($val); * } * * @param array|object Either a plain array or another iterator. * @param callback The function to apply to an element. * @return object An iterator that applies the given callback(s). */ function iterator_map( $it, $fn ) { if ( is_array( $it ) ) { $it = new ArrayIterator( $it ); } if ( ! method_exists( $it, 'add_transform' ) ) { $it = new Transform( $it ); } foreach ( array_slice( func_get_args(), 1 ) as $fn ) { $it->add_transform( $fn ); } return $it; } /** * Search for file by walking up the directory tree until the first file is found or until $stop_check($dir) returns true. * @param string|array The files (or file) to search for. * @param string|null The directory to start searching from; defaults to CWD. * @param callable Function which is passed the current dir each time a directory level is traversed. * @return null|string Null if the file was not found. */ function find_file_upward( $files, $dir = null, $stop_check = null ) { $files = (array) $files; if ( is_null( $dir ) ) { $dir = getcwd(); } while ( is_readable( $dir ) ) { // Stop walking up when the supplied callable returns true being passed the $dir if ( is_callable( $stop_check ) && call_user_func( $stop_check, $dir ) ) { return null; } foreach ( $files as $file ) { $path = $dir . DIRECTORY_SEPARATOR . $file; if ( file_exists( $path ) ) { return $path; } } $parent_dir = dirname( $dir ); if ( empty( $parent_dir ) || $parent_dir === $dir ) { break; } $dir = $parent_dir; } return null; } function is_path_absolute( $path ) { // Windows if ( isset( $path[1] ) && ':' === $path[1] ) { return true; } return '/' === $path[0]; } /** * Composes positional arguments into a command string. * * @param array * @return string */ function args_to_str( $args ) { return ' ' . implode( ' ', array_map( 'escapeshellarg', $args ) ); } /** * Composes associative arguments into a command string. * * @param array * @return string */ function assoc_args_to_str( $assoc_args ) { $str = ''; foreach ( $assoc_args as $key => $value ) { if ( true === $value ) { $str .= " --$key"; } elseif ( is_array( $value ) ) { foreach ( $value as $_ => $v ) { $str .= assoc_args_to_str( array( $key => $v, ) ); } } else { $str .= " --$key=" . escapeshellarg( $value ); } } return $str; } /** * Given a template string and an arbitrary number of arguments, * returns the final command, with the parameters escaped. */ function esc_cmd( $cmd ) { if ( func_num_args() < 2 ) { trigger_error( 'esc_cmd() requires at least two arguments.', E_USER_WARNING ); } $args = func_get_args(); $cmd = array_shift( $args ); return vsprintf( $cmd, array_map( 'escapeshellarg', $args ) ); } /** * Gets path to WordPress configuration. * * @return string */ function locate_wp_config() { static $path; if ( null === $path ) { $path = false; if ( getenv( 'WP_CONFIG_PATH' ) && file_exists( getenv( 'WP_CONFIG_PATH' ) ) ) { $path = getenv( 'WP_CONFIG_PATH' ); } elseif ( file_exists( ABSPATH . 'wp-config.php' ) ) { $path = ABSPATH . 'wp-config.php'; } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) { $path = dirname( ABSPATH ) . '/wp-config.php'; } if ( $path ) { $path = realpath( $path ); } } return $path; } function wp_version_compare( $since, $operator ) { $wp_version = str_replace( '-src', '', $GLOBALS['wp_version'] ); $since = str_replace( '-src', '', $since ); return version_compare( $wp_version, $since, $operator ); } /** * Render a collection of items as an ASCII table, JSON, CSV, YAML, list of ids, or count. * * Given a collection of items with a consistent data structure: * * ``` * $items = array( * array( * 'key' => 'foo', * 'value' => 'bar', * ) * ); * ``` * * Render `$items` as an ASCII table: * * ``` * WP_CLI\Utils\format_items( 'table', $items, array( 'key', 'value' ) ); * * # +-----+-------+ * # | key | value | * # +-----+-------+ * # | foo | bar | * # +-----+-------+ * ``` * * Or render `$items` as YAML: * * ``` * WP_CLI\Utils\format_items( 'yaml', $items, array( 'key', 'value' ) ); * * # --- * # - * # key: foo * # value: bar * ``` * * @access public * @category Output * * @param string $format Format to use: 'table', 'json', 'csv', 'yaml', 'ids', 'count' * @param array $items An array of items to output. * @param array|string $fields Named fields for each item of data. Can be array or comma-separated list. * @return null */ function format_items( $format, $items, $fields ) { $assoc_args = compact( 'format', 'fields' ); $formatter = new Formatter( $assoc_args ); $formatter->display_items( $items ); } /** * Write data as CSV to a given file. * * @access public * * @param resource $fd File descriptor * @param array $rows Array of rows to output * @param array $headers List of CSV columns (optional) */ function write_csv( $fd, $rows, $headers = array() ) { if ( ! empty( $headers ) ) { fputcsv( $fd, $headers ); } foreach ( $rows as $row ) { if ( ! empty( $headers ) ) { $row = pick_fields( $row, $headers ); } fputcsv( $fd, array_values( $row ) ); } } /** * Pick fields from an associative array or object. * * @param array|object Associative array or object to pick fields from. * @param array List of fields to pick. * @return array */ function pick_fields( $item, $fields ) { $values = array(); if ( is_object( $item ) ) { foreach ( $fields as $field ) { $values[ $field ] = isset( $item->$field ) ? $item->$field : null; } } else { foreach ( $fields as $field ) { $values[ $field ] = isset( $item[ $field ] ) ? $item[ $field ] : null; } } return $values; } /** * Launch system's $EDITOR for the user to edit some text. * * @access public * @category Input * * @param string $content Some form of text to edit (e.g. post content). * @param string $title Title to display in the editor. * @param string $ext Extension to use with the temp file. * @return string|bool Edited text, if file is saved from editor; false, if no change to file. */ function launch_editor_for_input( $input, $title = 'WP-CLI', $ext = 'tmp' ) { check_proc_available( 'launch_editor_for_input' ); $tmpdir = get_temp_dir(); do { $tmpfile = basename( $title ); $tmpfile = preg_replace( '|\.[^.]*$|', '', $tmpfile ); $tmpfile .= '-' . substr( md5( mt_rand() ), 0, 6 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- no crypto and WP not loaded. $tmpfile = $tmpdir . $tmpfile . '.' . $ext; $fp = fopen( $tmpfile, 'xb' ); if ( ! $fp && is_writable( $tmpdir ) && file_exists( $tmpfile ) ) { $tmpfile = ''; continue; } if ( $fp ) { fclose( $fp ); } } while ( ! $tmpfile ); if ( ! $tmpfile ) { WP_CLI::error( 'Error creating temporary file.' ); } file_put_contents( $tmpfile, $input ); $editor = getenv( 'EDITOR' ); if ( ! $editor ) { $editor = is_windows() ? 'notepad' : 'vi'; } $descriptorspec = array( STDIN, STDOUT, STDERR ); $process = proc_open_compat( "$editor " . escapeshellarg( $tmpfile ), $descriptorspec, $pipes ); $r = proc_close( $process ); if ( $r ) { exit( $r ); } $output = file_get_contents( $tmpfile ); unlink( $tmpfile ); if ( $output === $input ) { return false; } return $output; } /** * @param string MySQL host string, as defined in wp-config.php * * @return array */ function mysql_host_to_cli_args( $raw_host ) { $assoc_args = array(); /** * If the host string begins with 'p:' for a persistent db connection, * replace 'p:' with nothing. */ if ( substr( $raw_host, 0, 2 ) === 'p:' ) { $raw_host = substr_replace( $raw_host, '', 0, 2 ); } $host_parts = explode( ':', $raw_host ); if ( count( $host_parts ) === 2 ) { list( $assoc_args['host'], $extra ) = $host_parts; $extra = trim( $extra ); if ( is_numeric( $extra ) ) { $assoc_args['port'] = (int) $extra; $assoc_args['protocol'] = 'tcp'; } elseif ( '' !== $extra ) { $assoc_args['socket'] = $extra; } } else { $assoc_args['host'] = $raw_host; } return $assoc_args; } function run_mysql_command( $cmd, $assoc_args, $descriptors = null ) { check_proc_available( 'run_mysql_command' ); if ( ! $descriptors ) { $descriptors = array( STDIN, STDOUT, STDERR ); } if ( isset( $assoc_args['host'] ) ) { // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_host_to_cli_args -- Misidentified as PHP native MySQL function. $assoc_args = array_merge( $assoc_args, mysql_host_to_cli_args( $assoc_args['host'] ) ); } $pass = $assoc_args['pass']; unset( $assoc_args['pass'] ); $old_pass = getenv( 'MYSQL_PWD' ); putenv( 'MYSQL_PWD=' . $pass ); $final_cmd = force_env_on_nix_systems( $cmd ) . assoc_args_to_str( $assoc_args ); $proc = proc_open_compat( $final_cmd, $descriptors, $pipes ); if ( ! $proc ) { exit( 1 ); } $r = proc_close( $proc ); putenv( 'MYSQL_PWD=' . $old_pass ); if ( $r ) { exit( $r ); } } /** * Render PHP or other types of files using Mustache templates. * * IMPORTANT: Automatic HTML escaping is disabled! */ function mustache_render( $template_name, $data = array() ) { if ( ! file_exists( $template_name ) ) { $template_name = WP_CLI_ROOT . "/templates/$template_name"; } $template = file_get_contents( $template_name ); $m = new Mustache_Engine( array( 'escape' => function ( $val ) { return $val; }, ) ); return $m->render( $template, $data ); } /** * Create a progress bar to display percent completion of a given operation. * * Progress bar is written to STDOUT, and disabled when command is piped. Progress * advances with `$progress->tick()`, and completes with `$progress->finish()`. * Process bar also indicates elapsed time and expected total time. * * ``` * # `wp user generate` ticks progress bar each time a new user is created. * # * # $ wp user generate --count=500 * # Generating users 22 % [=======> ] 0:05 / 0:23 * * $progress = \WP_CLI\Utils\make_progress_bar( 'Generating users', $count ); * for ( $i = 0; $i < $count; $i++ ) { * // uses wp_insert_user() to insert the user * $progress->tick(); * } * $progress->finish(); * ``` * * @access public * @category Output * * @param string $message Text to display before the progress bar. * @param integer $count Total number of ticks to be performed. * @param int $interval Optional. The interval in milliseconds between updates. Default 100. * @return cli\progress\Bar|WP_CLI\NoOp */ function make_progress_bar( $message, $count, $interval = 100 ) { if ( cli\Shell::isPiped() ) { return new WP_CLI\NoOp(); } return new cli\progress\Bar( $message, $count, $interval ); } /** * Helper function to use wp_parse_url when available or fall back to PHP's * parse_url if not. * * Additionally, this adds 'http://' to the URL if no scheme was found. * * @param string $url The URL to parse. * @param int $component Optional. The specific component to retrieve. * Use one of the PHP predefined constants to * specify which one. Defaults to -1 (= return * all parts as an array). * @param bool $auto_add_scheme Optional. Automatically add an http:// scheme if * none was found. Defaults to true. * @return mixed False on parse failure; Array of URL components on success; * When a specific component has been requested: null if the * component doesn't exist in the given URL; a string or - in the * case of PHP_URL_PORT - integer when it does. See parse_url()'s * return values. */ function parse_url( $url, $component = - 1, $auto_add_scheme = true ) { if ( function_exists( 'wp_parse_url' ) && ( -1 === $component || wp_version_compare( '4.7', '>=' ) ) ) { $url_parts = wp_parse_url( $url, $component ); } else { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Fallback. $url_parts = \parse_url( $url, $component ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Own version based on WP one. if ( $auto_add_scheme && ! parse_url( $url, PHP_URL_SCHEME, false ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Own version based on WP one. $url_parts = parse_url( 'http://' . $url, $component, false ); } return $url_parts; } /** * Check if we're running in a Windows environment (cmd.exe). * * @return bool */ function is_windows() { $test_is_windows = getenv( 'WP_CLI_TEST_IS_WINDOWS' ); return false !== $test_is_windows ? (bool) $test_is_windows : strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN'; } /** * Replace magic constants in some PHP source code. * * @param string $source The PHP code to manipulate. * @param string $path The path to use instead of the magic constants * @return string Adapted PHP code. */ function replace_path_consts( $source, $path ) { $replacements = array( '__FILE__' => "'$path'", '__DIR__' => "'" . dirname( $path ) . "'", ); $old = array_keys( $replacements ); $new = array_values( $replacements ); return str_replace( $old, $new, $source ); } /** * Make a HTTP request to a remote URL. * * Wraps the Requests HTTP library to ensure every request includes a cert. * * ``` * # `wp core download` verifies the hash for a downloaded WordPress archive * * $md5_response = Utils\http_request( 'GET', $download_url . '.md5' ); * if ( 20 != substr( $md5_response->status_code, 0, 2 ) ) { * WP_CLI::error( "Couldn't access md5 hash for release (HTTP code {$response->status_code})" ); * } * ``` * * @access public * * @param string $method HTTP method (GET, POST, DELETE, etc.) * @param string $url URL to make the HTTP request to. * @param array $headers Add specific headers to the request. * @param array $options * @return object * @throws RuntimeException If the request failed. * @throws WP_CLI\ExitException If the request failed and $halt_on_error is true. */ function http_request( $method, $url, $data = null, $headers = array(), $options = array() ) { $cert_path = '/rmccue/requests/library/Requests/Transport/cacert.pem'; $halt_on_error = ! isset( $options['halt_on_error'] ) || (bool) $options['halt_on_error']; if ( inside_phar() ) { // cURL can't read Phar archives $options['verify'] = extract_from_phar( WP_CLI_VENDOR_DIR . $cert_path ); } else { foreach ( get_vendor_paths() as $vendor_path ) { if ( file_exists( $vendor_path . $cert_path ) ) { $options['verify'] = $vendor_path . $cert_path; break; } } if ( empty( $options['verify'] ) ) { $error_msg = 'Cannot find SSL certificate.'; if ( $halt_on_error ) { WP_CLI::error( $error_msg ); } throw new RuntimeException( $error_msg ); } } if ( ! class_exists( 'Requests_Hooks' ) ) { // Autoloader for the Requests library has not been registered yet. Requests::register_autoloader(); } try { return Requests::request( $url, $headers, $data, $method, $options ); } catch ( Requests_Exception $ex ) { // CURLE_SSL_CACERT_BADFILE only defined for PHP >= 7. if ( 'curlerror' !== $ex->getType() || ! in_array( curl_errno( $ex->getData() ), array( CURLE_SSL_CONNECT_ERROR, CURLE_SSL_CERTPROBLEM, 77 /*CURLE_SSL_CACERT_BADFILE*/ ), true ) ) { $error_msg = sprintf( "Failed to get url '%s': %s.", $url, $ex->getMessage() ); if ( $halt_on_error ) { WP_CLI::error( $error_msg ); } throw new RuntimeException( $error_msg, null, $ex ); } // Handle SSL certificate issues gracefully WP_CLI::warning( sprintf( "Re-trying without verify after failing to get verified url '%s' %s.", $url, $ex->getMessage() ) ); $options['verify'] = false; try { return Requests::request( $url, $headers, $data, $method, $options ); } catch ( Requests_Exception $ex ) { $error_msg = sprintf( "Failed to get non-verified url '%s' %s.", $url, $ex->getMessage() ); if ( $halt_on_error ) { WP_CLI::error( $error_msg ); } throw new RuntimeException( $error_msg, null, $ex ); } } } /** * Increments a version string using the "x.y.z-pre" format. * * Can increment the major, minor or patch number by one. * If $new_version == "same" the version string is not changed. * If $new_version is not a known keyword, it will be used as the new version string directly. * * @param string $current_version * @param string $new_version * @return string */ function increment_version( $current_version, $new_version ) { // split version assuming the format is x.y.z-pre $current_version = explode( '-', $current_version, 2 ); $current_version[0] = explode( '.', $current_version[0] ); switch ( $new_version ) { case 'same': // do nothing break; case 'patch': $current_version[0][2]++; $current_version = array( $current_version[0] ); // Drop possible pre-release info. break; case 'minor': $current_version[0][1]++; $current_version[0][2] = 0; $current_version = array( $current_version[0] ); // Drop possible pre-release info. break; case 'major': $current_version[0][0]++; $current_version[0][1] = 0; $current_version[0][2] = 0; $current_version = array( $current_version[0] ); // Drop possible pre-release info. break; default: // not a keyword $current_version = array( array( $new_version ) ); break; } // Reconstruct version string. $current_version[0] = implode( '.', $current_version[0] ); $current_version = implode( '-', $current_version ); return $current_version; } /** * Compare two version strings to get the named semantic version. * * @access public * * @param string $new_version * @param string $original_version * @return string $name 'major', 'minor', 'patch' */ function get_named_sem_ver( $new_version, $original_version ) { if ( ! Comparator::greaterThan( $new_version, $original_version ) ) { return ''; } $parts = explode( '-', $original_version ); $bits = explode( '.', $parts[0] ); $major = $bits[0]; if ( isset( $bits[1] ) ) { $minor = $bits[1]; } if ( isset( $bits[2] ) ) { $patch = $bits[2]; } if ( ! is_null( $minor ) && Semver::satisfies( $new_version, "{$major}.{$minor}.x" ) ) { return 'patch'; } if ( Semver::satisfies( $new_version, "{$major}.x.x" ) ) { return 'minor'; } return 'major'; } /** * Return the flag value or, if it's not set, the $default value. * * Because flags can be negated (e.g. --no-quiet to negate --quiet), this * function provides a safer alternative to using * `isset( $assoc_args['quiet'] )` or similar. * * @access public * @category Input * * @param array $assoc_args Arguments array. * @param string $flag Flag to get the value. * @param mixed $default Default value for the flag. Default: NULL * @return mixed */ function get_flag_value( $assoc_args, $flag, $default = null ) { return isset( $assoc_args[ $flag ] ) ? $assoc_args[ $flag ] : $default; } /** * Get the home directory. * * @access public * @category System * * @return string */ function get_home_dir() { $home = getenv( 'HOME' ); if ( ! $home ) { // In Windows $HOME may not be defined $home = getenv( 'HOMEDRIVE' ) . getenv( 'HOMEPATH' ); } return rtrim( $home, '/\\' ); } /** * Appends a trailing slash. * * @access public * @category System * * @param string $string What to add the trailing slash to. * @return string String with trailing slash added. */ function trailingslashit( $string ) { return rtrim( $string, '/\\' ) . '/'; } /** * Normalize a filesystem path. * * On Windows systems, replaces backslashes with forward slashes * and forces upper-case drive letters. * Allows for two leading slashes for Windows network shares, but * ensures that all other duplicate slashes are reduced to a single one. * Ensures upper-case drive letters on Windows systems. * * @access public * @category System * * @param string $path Path to normalize. * @return string Normalized path. */ function normalize_path( $path ) { $path = str_replace( '\\', '/', $path ); $path = preg_replace( '|(?<=.)/+|', '/', $path ); if ( ':' === substr( $path, 1, 1 ) ) { $path = ucfirst( $path ); } return $path; } /** * Convert Windows EOLs to *nix. * * @param string $str String to convert. * @return string String with carriage return / newline pairs reduced to newlines. */ function normalize_eols( $str ) { return str_replace( "\r\n", "\n", $str ); } /** * Get the system's temp directory. Warns user if it isn't writable. * * @access public * @category System * * @return string */ function get_temp_dir() { static $temp = ''; if ( $temp ) { return $temp; } // `sys_get_temp_dir()` introduced PHP 5.2.1. Will always return something. $temp = trailingslashit( sys_get_temp_dir() ); if ( ! is_writable( $temp ) ) { WP_CLI::warning( "Temp directory isn't writable: {$temp}" ); } return $temp; } /** * Parse a SSH url for its host, port, and path. * * Similar to parse_url(), but adds support for defined SSH aliases. * * ``` * host OR host/path/to/wordpress OR host:port/path/to/wordpress * ``` * * @access public * * @return mixed */ function parse_ssh_url( $url, $component = -1 ) { preg_match( '#^((docker|docker\-compose|ssh|vagrant):)?(([^@:]+)@)?([^:/~]+)(:([\d]*))?((/|~)(.+))?$#', $url, $matches ); $bits = array(); foreach ( array( 2 => 'scheme', 4 => 'user', 5 => 'host', 7 => 'port', 8 => 'path', ) as $i => $key ) { if ( ! empty( $matches[ $i ] ) ) { $bits[ $key ] = $matches[ $i ]; } } // Find the hostname from `vagrant ssh-config` automatically. if ( preg_match( '/^vagrant:?/', $url ) ) { if ( 'vagrant' === $bits['host'] && empty( $bits['scheme'] ) ) { $bits['scheme'] = 'vagrant'; $bits['host'] = ''; } } switch ( $component ) { case PHP_URL_SCHEME: return isset( $bits['scheme'] ) ? $bits['scheme'] : null; case PHP_URL_USER: return isset( $bits['user'] ) ? $bits['user'] : null; case PHP_URL_HOST: return isset( $bits['host'] ) ? $bits['host'] : null; case PHP_URL_PATH: return isset( $bits['path'] ) ? $bits['path'] : null; case PHP_URL_PORT: return isset( $bits['port'] ) ? $bits['port'] : null; default: return $bits; } } /** * Report the results of the same operation against multiple resources. * * @access public * @category Input * * @param string $noun Resource being affected (e.g. plugin) * @param string $verb Type of action happening to the noun (e.g. activate) * @param integer $total Total number of resource being affected. * @param integer $successes Number of successful operations. * @param integer $failures Number of failures. * @param null|integer $skips Optional. Number of skipped operations. Default null (don't show skips). */ function report_batch_operation_results( $noun, $verb, $total, $successes, $failures, $skips = null ) { $plural_noun = $noun . 's'; $past_tense_verb = past_tense_verb( $verb ); $past_tense_verb_upper = ucfirst( $past_tense_verb ); if ( $failures ) { $failed_skipped_message = null === $skips ? '' : " ({$failures} failed" . ( $skips ? ", {$skips} skipped" : '' ) . ')'; if ( $successes ) { WP_CLI::error( "Only {$past_tense_verb} {$successes} of {$total} {$plural_noun}{$failed_skipped_message}." ); } else { WP_CLI::error( "No {$plural_noun} {$past_tense_verb}{$failed_skipped_message}." ); } } else { $skipped_message = $skips ? " ({$skips} skipped)" : ''; if ( $successes || $skips ) { WP_CLI::success( "{$past_tense_verb_upper} {$successes} of {$total} {$plural_noun}{$skipped_message}." ); } else { $message = $total > 1 ? ucfirst( $plural_noun ) : ucfirst( $noun ); WP_CLI::success( "{$message} already {$past_tense_verb}." ); } } } /** * Parse a string of command line arguments into an $argv-esqe variable. * * @access public * @category Input * * @param string $arguments * @return array */ function parse_str_to_argv( $arguments ) { preg_match_all( '/(?:--[^\s=]+=(["\'])((\\{2})*|(?:[^\1]+?[^\\\\](\\{2})*))\1|--[^\s=]+=[^\s]+|--[^\s=]+|(["\'])((\\{2})*|(?:[^\5]+?[^\\\\](\\{2})*))\5|[^\s]+)/', $arguments, $matches ); $argv = isset( $matches[0] ) ? $matches[0] : array(); $argv = array_map( static function ( $arg ) { foreach ( array( '"', "'" ) as $char ) { if ( substr( $arg, 0, 1 ) === $char && substr( $arg, -1 ) === $char ) { $arg = substr( $arg, 1, -1 ); break; } } return $arg; }, $argv ); return $argv; } /** * Locale-independent version of basename() * * @access public * * @param string $path * @param string $suffix * @return string */ function basename( $path, $suffix = '' ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode -- Format required by wordpress.org API. return urldecode( \basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) ); } /** * Checks whether the output of the current script is a TTY or a pipe / redirect * * Returns true if STDOUT output is being redirected to a pipe or a file; false is * output is being sent directly to the terminal. * * If an env variable SHELL_PIPE exists, returned result depends on its * value. Strings like 1, 0, yes, no, that validate to booleans are accepted. * * To enable ASCII formatting even when the shell is piped, use the * ENV variable SHELL_PIPE=0. * * @access public * * @return bool */ function isPiped() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid -- Renaming would break BC. $shell_pipe = getenv( 'SHELL_PIPE' ); if ( false !== $shell_pipe ) { return filter_var( $shell_pipe, FILTER_VALIDATE_BOOLEAN ); } return ( function_exists( 'posix_isatty' ) && ! posix_isatty( STDOUT ) ); } /** * Expand within paths to their matching paths. * * Has no effect on paths which do not use glob patterns. * * @param string|array $paths Single path as a string, or an array of paths. * @param int $flags Optional. Flags to pass to glob. Defaults to GLOB_BRACE. * @return array Expanded paths. */ function expand_globs( $paths, $flags = 'default' ) { // Compatibility for systems without GLOB_BRACE. $glob_func = 'glob'; if ( 'default' === $flags ) { if ( ! defined( 'GLOB_BRACE' ) || getenv( 'WP_CLI_TEST_EXPAND_GLOBS_NO_GLOB_BRACE' ) ) { $glob_func = 'WP_CLI\Utils\glob_brace'; } else { $flags = GLOB_BRACE; } } $expanded = array(); foreach ( (array) $paths as $path ) { $matching = array( $path ); if ( preg_match( '/[' . preg_quote( '*?[]{}!', '/' ) . ']/', $path ) ) { $matching = $glob_func( $path, $flags ) ?: array(); } $expanded = array_merge( $expanded, $matching ); } return array_values( array_unique( $expanded ) ); } /** * Simulate a `glob()` with the `GLOB_BRACE` flag set. For systems (eg Alpine Linux) built against a libc library (eg https://www.musl-libc.org/) that lacks it. * Copied and adapted from Zend Framework's `Glob::fallbackGlob()` and Glob::nextBraceSub()`. * * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * * @param string $pattern Filename pattern. * @param void $dummy_flags Not used. * @return array Array of paths. */ function glob_brace( $pattern, $dummy_flags = null ) { static $next_brace_sub; if ( ! $next_brace_sub ) { // Find the end of the subpattern in a brace expression. $next_brace_sub = function ( $pattern, $current ) { $length = strlen( $pattern ); $depth = 0; while ( $current < $length ) { if ( '\\' === $pattern[ $current ] ) { if ( ++$current === $length ) { break; } $current++; } else { if ( ( '}' === $pattern[ $current ] && 0 === $depth-- ) || ( ',' === $pattern[ $current ] && 0 === $depth ) ) { break; } if ( '{' === $pattern[ $current++ ] ) { $depth++; } } } return $current < $length ? $current : null; }; } $length = strlen( $pattern ); // Find first opening brace. for ( $begin = 0; $begin < $length; $begin++ ) { if ( '\\' === $pattern[ $begin ] ) { $begin++; } elseif ( '{' === $pattern[ $begin ] ) { break; } } // Find comma or matching closing brace. $next = $next_brace_sub( $pattern, $begin + 1 ); if ( null === $next ) { return glob( $pattern ); } $rest = $next; // Point `$rest` to matching closing brace. while ( '}' !== $pattern[ $rest ] ) { $rest = $next_brace_sub( $pattern, $rest + 1 ); if ( null === $rest ) { return glob( $pattern ); } } $paths = array(); $p = $begin + 1; // For each comma-separated subpattern. do { $subpattern = substr( $pattern, 0, $begin ) . substr( $pattern, $p, $next - $p ) . substr( $pattern, $rest + 1 ); $result = glob_brace( $subpattern ); if ( ! empty( $result ) ) { $paths = array_merge( $paths, $result ); } if ( '}' === $pattern[ $next ] ) { break; } $p = $next + 1; $next = $next_brace_sub( $pattern, $p ); } while ( null !== $next ); return array_values( array_unique( $paths ) ); } /** * Get the closest suggestion for a mis-typed target term amongst a list of * options. * * Uses the Levenshtein algorithm to calculate the relative "distance" between * terms. * * If the "distance" to the closest term is higher than the threshold, an empty * string is returned. * * @param string $target Target term to get a suggestion for. * @param array $options Array with possible options. * @param int $threshold Threshold above which to return an empty string. * @return string */ function get_suggestion( $target, array $options, $threshold = 2 ) { $suggestion_map = array( 'add' => 'create', 'check' => 'check-update', 'capability' => 'cap', 'clear' => 'flush', 'decrement' => 'decr', 'del' => 'delete', 'directory' => 'dir', 'exec' => 'eval', 'exec-file' => 'eval-file', 'increment' => 'incr', 'language' => 'locale', 'lang' => 'locale', 'new' => 'create', 'number' => 'count', 'remove' => 'delete', 'regen' => 'regenerate', 'rep' => 'replace', 'repl' => 'replace', 'trash' => 'delete', 'v' => 'version', ); if ( array_key_exists( $target, $suggestion_map ) && in_array( $suggestion_map[ $target ], $options, true ) ) { return $suggestion_map[ $target ]; } if ( empty( $options ) ) { return ''; } foreach ( $options as $option ) { $distance = levenshtein( $option, $target ); $levenshtein[ $option ] = $distance; } // Sort known command strings by distance to user entry. asort( $levenshtein ); // Fetch the closest command string. reset( $levenshtein ); $suggestion = key( $levenshtein ); // Only return a suggestion if below a given threshold. return $levenshtein[ $suggestion ] <= $threshold && $suggestion !== $target ? (string) $suggestion : ''; } /** * Get a Phar-safe version of a path. * * For paths inside a Phar, this strips the outer filesystem's location to * reduce the path to what it needs to be within the Phar archive. * * Use the __FILE__ or __DIR__ constants as a starting point. * * @param string $path An absolute path that might be within a Phar. * @return string A Phar-safe version of the path. */ function phar_safe_path( $path ) { if ( ! inside_phar() ) { return $path; } return str_replace( PHAR_STREAM_PREFIX . WP_CLI_PHAR_PATH . '/', PHAR_STREAM_PREFIX, $path ); } /** * Check whether a given Command object is part of the bundled set of * commands. * * This function accepts both a fully qualified class name as a string as * well as an object that extends `WP_CLI\Dispatcher\CompositeCommand`. * * @param \WP_CLI\Dispatcher\CompositeCommand|string $command * @return bool */ function is_bundled_command( $command ) { static $classes; if ( null === $classes ) { $classes = array(); // TODO: This needs to be rebuilt. // $class_map = WP_CLI_VENDOR_DIR . '/composer/autoload_commands_classmap.php'; // if ( file_exists( WP_CLI_VENDOR_DIR . '/composer/' ) ) { // $classes = include $class_map; // } $classes = array( 'CLI_Command' => true ); } if ( is_object( $command ) ) { $command = get_class( $command ); } return is_string( $command ) ? array_key_exists( $command, $classes ) : false; } /** * Maybe prefix command string with "/usr/bin/env". * Removes (if there) if Windows, adds (if not there) if not. * * @param string $command * @return string */ function force_env_on_nix_systems( $command ) { $env_prefix = '/usr/bin/env '; $env_prefix_len = strlen( $env_prefix ); if ( is_windows() ) { if ( 0 === strncmp( $command, $env_prefix, $env_prefix_len ) ) { $command = substr( $command, $env_prefix_len ); } } elseif ( 0 !== strncmp( $command, $env_prefix, $env_prefix_len ) ) { $command = $env_prefix . $command; } return $command; } /** * Check that `proc_open()` and `proc_close()` haven't been disabled. * * @param string $context Optional. If set will appear in error message. Default null. * @param bool $return Optional. If set will return false rather than error out. Default false. * @return bool */ function check_proc_available( $context = null, $return = false ) { if ( ! function_exists( 'proc_open' ) || ! function_exists( 'proc_close' ) ) { if ( $return ) { return false; } $msg = 'The PHP functions `proc_open()` and/or `proc_close()` are disabled. Please check your PHP ini directive `disable_functions` or suhosin settings.'; if ( $context ) { WP_CLI::error( sprintf( "Cannot do '%s': %s", $context, $msg ) ); } else { WP_CLI::error( $msg ); } } return true; } /** * Returns past tense of verb, with limited accuracy. Only regular verbs catered for, apart from "reset". * * @param string $verb Verb to return past tense of. * @return string */ function past_tense_verb( $verb ) { static $irregular = array( 'reset' => 'reset', ); if ( isset( $irregular[ $verb ] ) ) { return $irregular[ $verb ]; } $last = substr( $verb, -1 ); if ( 'e' === $last ) { $verb = substr( $verb, 0, -1 ); } elseif ( 'y' === $last && ! preg_match( '/[aeiou]y$/', $verb ) ) { $verb = substr( $verb, 0, -1 ) . 'i'; } elseif ( preg_match( '/^[^aeiou]*[aeiou][^aeiouhwxy]$/', $verb ) ) { // Rule of thumb that most (all?) one-voweled regular verbs ending in vowel + consonant (excluding "h", "w", "x", "y") double their final consonant - misses many cases (eg "submit"). $verb .= $last; } return $verb . 'ed'; } /** * Get the path to the PHP binary used when executing WP-CLI. * * Environment values permit specific binaries to be indicated. * * @access public * @category System * * @return string */ function get_php_binary() { $wp_cli_php_used = getenv( 'WP_CLI_PHP_USED' ); if ( false !== $wp_cli_php_used ) { return $wp_cli_php_used; } $wp_cli_php = getenv( 'WP_CLI_PHP' ); if ( false !== $wp_cli_php ) { return $wp_cli_php; } // Available since PHP 5.4. if ( defined( 'PHP_BINARY' ) ) { return PHP_BINARY; } if ( @is_executable( PHP_BINDIR . '/php' ) ) { return PHP_BINDIR . '/php'; } if ( is_windows() && @is_executable( PHP_BINDIR . '/php.exe' ) ) { return PHP_BINDIR . '/php.exe'; } return 'php'; } /** * Windows compatible `proc_open()`. * Works around bug in PHP, and also deals with *nix-like `ENV_VAR=blah cmd` environment variable prefixes. * * @access public * * @param string $command Command to execute. * @param array $descriptorspec Indexed array of descriptor numbers and their values. * @param array &$pipes Indexed array of file pointers that correspond to PHP's end of any pipes that are created. * @param string $cwd Initial working directory for the command. * @param array $env Array of environment variables. * @param array $other_options Array of additional options (Windows only). * @return resource Command stripped of any environment variable settings. */ function proc_open_compat( $cmd, $descriptorspec, &$pipes, $cwd = null, $env = null, $other_options = null ) { if ( is_windows() ) { // Need to encompass the whole command in double quotes - PHP bug https://bugs.php.net/bug.php?id=49139 $cmd = '"' . _proc_open_compat_win_env( $cmd, $env ) . '"'; } return proc_open( $cmd, $descriptorspec, $pipes, $cwd, $env, $other_options ); } /** * For use by `proc_open_compat()` only. Separated out for ease of testing. Windows only. * Turns *nix-like `ENV_VAR=blah command` environment variable prefixes into stripped `cmd` with prefixed environment variables added to passed in environment array. * * @access private * * @param string $command Command to execute. * @param array &$env Array of existing environment variables. Will be modified if any settings in command. * @return string Command stripped of any environment variable settings. */ function _proc_open_compat_win_env( $cmd, &$env ) { if ( false !== strpos( $cmd, '=' ) ) { while ( preg_match( '/^([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|[^ ]*) /', $cmd, $matches ) ) { $cmd = substr( $cmd, strlen( $matches[0] ) ); if ( null === $env ) { $env = array(); } $env[ $matches[1] ] = isset( $matches[2][0] ) && '"' === $matches[2][0] ? substr( $matches[2], 1, -1 ) : $matches[2]; } } return $cmd; } /** * First half of escaping for LIKE special characters % and _ before preparing for MySQL. * * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security. * * Copied from core "wp-includes/wp-db.php". Avoids dependency on WP 4.4 wpdb. * * @access public * * @param string $text The raw text to be escaped. The input typed by the user should have no * extra or deleted slashes. * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare() * or real_escape next. */ function esc_like( $text ) { return addcslashes( $text, '_%\\' ); } /** * Escapes (backticks) MySQL identifiers (aka schema object names) - i.e. column names, table names, and database/index/alias/view etc names. * See https://dev.mysql.com/doc/refman/5.5/en/identifiers.html * * @param string|array $idents A single identifier or an array of identifiers. * @return string|array An escaped string if given a string, or an array of escaped strings if given an array of strings. */ function esc_sql_ident( $idents ) { $backtick = static function ( $v ) { // Escape any backticks in the identifier by doubling. return '`' . str_replace( '`', '``', $v ) . '`'; }; if ( is_string( $idents ) ) { return $backtick( $idents ); } return array_map( $backtick, $idents ); } /** * Check whether a given string is a valid JSON representation. * * @param string $argument String to evaluate. * @param bool $ignore_scalars Optional. Whether to ignore scalar values. * Defaults to true. * @return bool Whether the provided string is a valid JSON representation. */ function is_json( $argument, $ignore_scalars = true ) { if ( ! is_string( $argument ) || '' === $argument ) { return false; } if ( $ignore_scalars && ! in_array( $argument[0], array( '{', '[' ), true ) ) { return false; } json_decode( $argument, $assoc = true ); return json_last_error() === JSON_ERROR_NONE; } /** * Parse known shell arrays included in the $assoc_args array. * * @param array $assoc_args Associative array of arguments. * @param array $array_arguments Array of argument keys that should receive an * array through the shell. * @return array */ function parse_shell_arrays( $assoc_args, $array_arguments ) { if ( empty( $assoc_args ) || empty( $array_arguments ) ) { return $assoc_args; } foreach ( $array_arguments as $key ) { if ( array_key_exists( $key, $assoc_args ) && is_json( $assoc_args[ $key ] ) ) { $assoc_args[ $key ] = json_decode( $assoc_args[ $key ], $assoc = true ); } } return $assoc_args; } /** * Describe a callable as a string. * * @param callable $callable The callable to describe. * @return string String description of the callable. */ function describe_callable( $callable ) { try { if ( $callable instanceof Closure ) { $reflection = new ReflectionFunction( $callable ); return "Closure in file {$reflection->getFileName()} at line {$reflection->getStartLine()}"; } if ( is_array( $callable ) ) { if ( is_object( $callable[0] ) ) { return (string) sprintf( '%s->%s()', get_class( $callable[0] ), $callable[1] ); } return (string) sprintf( '%s::%s()', $callable[0], $callable[1] ); } return (string) gettype( $callable ); } catch ( Exception $exception ) { return 'Callable of unknown type'; } } /** * Pluralizes a noun in a grammatically correct way. * * @param string $noun Noun to be pluralized. Needs to be in singular form. * @param int|null $count Optional. Count of the nouns, to decide whether to * pluralize. Will pluralize unconditionally if none * provided. * @return string Pluralized noun. */ function pluralize( $noun, $count = null ) { if ( 1 === $count ) { return $noun; } return Inflector::pluralize( $noun ); } get_name() ); } while ( $command = $command->get_parent() ); return $path; } cache = $cache; // hook into wp http api add_filter( 'pre_http_request', array( $this, 'filter_pre_http_request' ), 10, 3 ); add_filter( 'http_response', array( $this, 'filter_http_response' ), 10, 3 ); } /** * short circuit wp http api with cached file */ public function filter_pre_http_request( $response, $args, $url ) { // check if whitelisted if ( ! isset( $this->whitelist[ $url ] ) ) { return $response; } // check if downloading if ( 'GET' !== $args['method'] || empty( $args['filename'] ) ) { return $response; } // check cache and export to designated location $filename = $this->cache->has( $this->whitelist[ $url ]['key'], $this->whitelist[ $url ]['ttl'] ); if ( $filename ) { WP_CLI::log( sprintf( 'Using cached file \'%s\'...', $filename ) ); if ( copy( $filename, $args['filename'] ) ) { // simulate successful download response return array( 'response' => array( 'code' => 200, 'message' => 'OK', ), 'filename' => $args['filename'], ); } WP_CLI::error( sprintf( 'Error copying cached file %s to %s', $filename, $url ) ); } return $response; } /** * cache wp http api downloads * * @param array $response * @param array $args * @param string $url */ public function filter_http_response( $response, $args, $url ) { // check if whitelisted if ( ! isset( $this->whitelist[ $url ] ) ) { return $response; } // check if downloading if ( 'GET' !== $args['method'] || empty( $args['filename'] ) ) { return $response; } // check if download was successful if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return $response; } // cache downloaded file $this->cache->import( $this->whitelist[ $url ]['key'], $response['filename'] ); return $response; } /** * whitelist a package url * * @param string $url * @param string $group package group (themes, plugins, ...) * @param string $slug package slug * @param string $version package version * @param int $ttl */ public function whitelist_package( $url, $group, $slug, $version, $ttl = null ) { $ext = pathinfo( Utils\parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ); $key = "$group/$slug-$version.$ext"; $this->whitelist_url( $url, $key, $ttl ); wp_update_plugins(); } /** * whitelist a url * * @param string $url * @param string $key * @param int $ttl */ public function whitelist_url( $url, $key = null, $ttl = null ) { $key = $key ? : $url; $this->whitelist[ $url ] = compact( 'key', 'ttl' ); } /** * check if url is whitelisted * * @param string $url * @return bool */ public function is_whitelisted( $url ) { return isset( $this->whitelist[ $url ] ); } } $key; } /** * Register a command for early invocation, generally before WordPress loads. * * @param string $when Named execution hook * @param WP_CLI\Dispatcher\Subcommand $command */ public function register_early_invoke( $when, $command ) { $this->early_invoke[ $when ][] = array_slice( Dispatcher\get_path( $command ), 1 ); } /** * Perform the early invocation of a command. * * @param string $when Named execution hook */ private function do_early_invoke( $when ) { if ( ! isset( $this->early_invoke[ $when ] ) ) { return; } // Search the value of @when from the command method. $real_when = ''; $r = $this->find_command_to_run( $this->arguments ); if ( is_array( $r ) ) { list( $command, $final_args, $cmd_path ) = $r; foreach ( $this->early_invoke as $_when => $_path ) { foreach ( $_path as $cmd ) { if ( $cmd === $cmd_path ) { $real_when = $_when; } } } } foreach ( $this->early_invoke[ $when ] as $path ) { if ( $this->cmd_starts_with( $path ) ) { if ( empty( $real_when ) || ( $real_when && $real_when === $when ) ) { $this->run_command_and_exit(); } } } } /** * Get the path to the global configuration YAML file. * * @return string|false */ public function get_global_config_path() { if ( getenv( 'WP_CLI_CONFIG_PATH' ) ) { $config_path = getenv( 'WP_CLI_CONFIG_PATH' ); $this->global_config_path_debug = 'Using global config from WP_CLI_CONFIG_PATH env var: ' . $config_path; } else { $config_path = Utils\get_home_dir() . '/.wp-cli/config.yml'; $this->global_config_path_debug = 'Using default global config: ' . $config_path; } if ( is_readable( $config_path ) ) { return $config_path; } $this->global_config_path_debug = 'No readable global config found'; return false; } /** * Get the path to the project-specific configuration * YAML file. * wp-cli.local.yml takes priority over wp-cli.yml. * * @return string|false */ public function get_project_config_path() { $config_files = array( 'wp-cli.local.yml', 'wp-cli.yml', ); // Stop looking upward when we find we have emerged from a subdirectory // installation into a parent installation $project_config_path = Utils\find_file_upward( $config_files, getcwd(), static function ( $dir ) { static $wp_load_count = 0; $wp_load_path = $dir . DIRECTORY_SEPARATOR . 'wp-load.php'; if ( file_exists( $wp_load_path ) ) { ++ $wp_load_count; } return $wp_load_count > 1; } ); $this->project_config_path_debug = 'No project config found'; if ( ! empty( $project_config_path ) ) { $this->project_config_path_debug = 'Using project config: ' . $project_config_path; } return $project_config_path; } /** * Get the path to the packages directory * * @return string */ public function get_packages_dir_path() { if ( getenv( 'WP_CLI_PACKAGES_DIR' ) ) { $packages_dir = Utils\trailingslashit( getenv( 'WP_CLI_PACKAGES_DIR' ) ); } else { $packages_dir = Utils\get_home_dir() . '/.wp-cli/packages/'; } return $packages_dir; } /** * Attempts to find the path to the WP installation inside index.php * * @param string $index_path * @return string|false */ private static function extract_subdir_path( $index_path ) { $index_code = file_get_contents( $index_path ); if ( ! preg_match( '|^\s*require\s*\(?\s*(.+?)/wp-blog-header\.php([\'"])|m', $index_code, $matches ) ) { return false; } $wp_path_src = $matches[1] . $matches[2]; $wp_path_src = Utils\replace_path_consts( $wp_path_src, $index_path ); $wp_path = eval( "return $wp_path_src;" ); // phpcs:ignore Squiz.PHP.Eval.Discouraged if ( ! Utils\is_path_absolute( $wp_path ) ) { $wp_path = dirname( $index_path ) . "/$wp_path"; } return $wp_path; } /** * Find the directory that contains the WordPress files. * Defaults to the current working dir. * * @return string An absolute path */ private function find_wp_root() { if ( ! empty( $this->config['path'] ) ) { $path = $this->config['path']; if ( ! Utils\is_path_absolute( $path ) ) { $path = getcwd() . '/' . $path; } return $path; } if ( $this->cmd_starts_with( array( 'core', 'download' ) ) ) { return getcwd(); } $dir = getcwd(); while ( is_readable( $dir ) ) { if ( file_exists( "$dir/wp-load.php" ) ) { return $dir; } if ( file_exists( "$dir/index.php" ) ) { $path = self::extract_subdir_path( "$dir/index.php" ); if ( ! empty( $path ) ) { return $path; } } $parent_dir = dirname( $dir ); if ( empty( $parent_dir ) || $parent_dir === $dir ) { break; } $dir = $parent_dir; } } /** * Set WordPress root as a given path. * * @param string $path */ private static function set_wp_root( $path ) { if ( ! defined( 'ABSPATH' ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Declaring a WP native constant. define( 'ABSPATH', Utils\normalize_path( Utils\trailingslashit( $path ) ) ); } elseif ( ! is_null( $path ) ) { WP_CLI::error_multi_line( array( 'The --path parameter cannot be used when ABSPATH is already defined elsewhere', 'ABSPATH is defined as: "' . ABSPATH . '"', ) ); } WP_CLI::debug( 'ABSPATH defined: ' . ABSPATH, 'bootstrap' ); $_SERVER['DOCUMENT_ROOT'] = realpath( $path ); } /** * Guess which URL context WP-CLI has been invoked under. * * @param array $assoc_args * @return string|false */ private static function guess_url( $assoc_args ) { if ( isset( $assoc_args['blog'] ) ) { $assoc_args['url'] = $assoc_args['blog']; } if ( isset( $assoc_args['url'] ) ) { $url = $assoc_args['url']; if ( true === $url ) { WP_CLI::warning( 'The --url parameter expects a value.' ); } } if ( isset( $url ) ) { return $url; } return false; } private function cmd_starts_with( $prefix ) { return array_slice( $this->arguments, 0, count( $prefix ) ) === $prefix; } /** * Given positional arguments, find the command to execute. * * @param array $args * @return array|string Command, args, and path on success; error message on failure */ public function find_command_to_run( $args ) { $command = \WP_CLI::get_root_command(); WP_CLI::do_hook( 'find_command_to_run_pre' ); $cmd_path = array(); while ( ! empty( $args ) && $command->can_have_subcommands() ) { $cmd_path[] = $args[0]; $full_name = implode( ' ', $cmd_path ); $subcommand = $command->find_subcommand( $args ); if ( ! $subcommand ) { if ( count( $cmd_path ) > 1 ) { $child = array_pop( $cmd_path ); $parent_name = implode( ' ', $cmd_path ); $suggestion = $this->get_subcommand_suggestion( $child, $command ); return sprintf( "'%s' is not a registered subcommand of '%s'. See 'wp help %s' for available subcommands.%s", $child, $parent_name, $parent_name, ! empty( $suggestion ) ? PHP_EOL . "Did you mean '{$suggestion}'?" : '' ); } $suggestion = $this->get_subcommand_suggestion( $full_name, $command ); return sprintf( "'%s' is not a registered wp command. See 'wp help' for available commands.%s", $full_name, ! empty( $suggestion ) ? PHP_EOL . "Did you mean '{$suggestion}'?" : '' ); } if ( $this->is_command_disabled( $subcommand ) ) { return sprintf( "The '%s' command has been disabled from the config file.", $full_name ); } $command = $subcommand; } return array( $command, $args, $cmd_path ); } /** * Find the WP-CLI command to run given arguments, and invoke it. * * @param array $args Positional arguments including command name * @param array $assoc_args Associative arguments for the command. * @param array $options Configuration options for the function. */ public function run_command( $args, $assoc_args = array(), $options = array() ) { WP_CLI::do_hook( 'before_run_command' ); if ( ! empty( $options['back_compat_conversions'] ) ) { list( $args, $assoc_args ) = self::back_compat_conversions( $args, $assoc_args ); } $r = $this->find_command_to_run( $args ); if ( is_string( $r ) ) { WP_CLI::error( $r ); } list( $command, $final_args, $cmd_path ) = $r; $name = implode( ' ', $cmd_path ); $extra_args = array(); if ( isset( $this->extra_config[ $name ] ) ) { $extra_args = $this->extra_config[ $name ]; } WP_CLI::debug( 'Running command: ' . $name, 'bootstrap' ); try { $command->invoke( $final_args, $assoc_args, $extra_args ); } catch ( WP_CLI\Iterators\Exception $e ) { WP_CLI::error( $e->getMessage() ); } } /** * Show synopsis if the called command is a composite command */ public function show_synopsis_if_composite_command() { $r = $this->find_command_to_run( $this->arguments ); if ( is_array( $r ) ) { list( $command ) = $r; if ( $command->can_have_subcommands() ) { $command->show_usage(); exit; } } } private function run_command_and_exit( $help_exit_warning = '' ) { $this->show_synopsis_if_composite_command(); $this->run_command( $this->arguments, $this->assoc_args ); if ( $this->cmd_starts_with( array( 'help' ) ) ) { // Help couldn't find the command so exit with suggestion. $suggestion_or_disabled = $this->find_command_to_run( array_slice( $this->arguments, 1 ) ); if ( is_string( $suggestion_or_disabled ) ) { if ( $help_exit_warning ) { WP_CLI::warning( $help_exit_warning ); } WP_CLI::error( $suggestion_or_disabled ); } // Should never get here. } exit; } /** * Perform a command against a remote server over SSH (or a container using * scheme of "docker" or "docker-compose"). * * @param string $connection_string Passed connection string. * @return void */ private function run_ssh_command( $connection_string ) { WP_CLI::do_hook( 'before_ssh' ); $bits = Utils\parse_ssh_url( $connection_string ); $pre_cmd = getenv( 'WP_CLI_SSH_PRE_CMD' ); if ( $pre_cmd ) { $message = WP_CLI::warning( "WP_CLI_SSH_PRE_CMD found, executing the following command(s) on the remote machine:\n $pre_cmd" ); WP_CLI::log( $message ); $pre_cmd = rtrim( $pre_cmd, ';' ) . '; '; } if ( ! empty( $bits['path'] ) ) { $pre_cmd .= 'cd ' . escapeshellarg( $bits['path'] ) . '; '; } $env_vars = ''; if ( getenv( 'WP_CLI_STRICT_ARGS_MODE' ) ) { $env_vars .= 'WP_CLI_STRICT_ARGS_MODE=1 '; } $wp_binary = 'wp'; $wp_args = array_slice( $GLOBALS['argv'], 1 ); if ( $this->alias && ! empty( $wp_args[0] ) && $this->alias === $wp_args[0] ) { array_shift( $wp_args ); $runtime_alias = array(); foreach ( $this->aliases[ $this->alias ] as $key => $value ) { if ( 'ssh' === $key ) { continue; } $runtime_alias[ $key ] = $value; } if ( ! empty( $runtime_alias ) ) { $encoded_alias = json_encode( array( $this->alias => $runtime_alias, ) ); $wp_binary = "WP_CLI_RUNTIME_ALIAS='{$encoded_alias}' {$wp_binary} {$this->alias}"; } } foreach ( $wp_args as $k => $v ) { if ( preg_match( '#--ssh=#', $v ) ) { unset( $wp_args[ $k ] ); } } $wp_command = $pre_cmd . $env_vars . $wp_binary . ' ' . implode( ' ', array_map( 'escapeshellarg', $wp_args ) ); $escaped_command = $this->generate_ssh_command( $bits, $wp_command ); passthru( $escaped_command, $exit_code ); if ( 255 === $exit_code ) { WP_CLI::error( 'Cannot connect over SSH using provided configuration.', 255 ); } else { exit( $exit_code ); } } /** * Generate a shell command from the parsed connection string. * * @param array $bits Parsed connection string. * @param string $wp_command WP-CLI command to run. * @return string */ private function generate_ssh_command( $bits, $wp_command ) { $escaped_command = ''; // Set default values. foreach ( array( 'scheme', 'user', 'host', 'port', 'path', 'key' ) as $bit ) { if ( ! isset( $bits[ $bit ] ) ) { $bits[ $bit ] = null; } WP_CLI::debug( 'SSH ' . $bit . ': ' . $bits[ $bit ], 'bootstrap' ); } $is_tty = function_exists( 'posix_isatty' ) && posix_isatty( STDOUT ); if ( 'docker' === $bits['scheme'] ) { $command = 'docker exec %s%s%s sh -c %s'; $escaped_command = sprintf( $command, $bits['user'] ? '--user ' . escapeshellarg( $bits['user'] ) . ' ' : '', $is_tty ? '-t ' : '', escapeshellarg( $bits['host'] ), escapeshellarg( $wp_command ) ); } if ( 'docker-compose' === $bits['scheme'] ) { $command = 'docker-compose exec %s%s%s sh -c %s'; $escaped_command = sprintf( $command, $bits['user'] ? '--user ' . escapeshellarg( $bits['user'] ) . ' ' : '', $is_tty ? '' : '-T ', escapeshellarg( $bits['host'] ), escapeshellarg( $wp_command ) ); } // Vagrant ssh-config. if ( 'vagrant' === $bits['scheme'] ) { $cache = WP_CLI::get_cache(); $cache_key = 'vagrant:' . $this->project_config_path; if ( $cache->has( $cache_key ) ) { $cached = $cache->read( $cache_key ); $values = json_decode( $cached, true ); } else { $ssh_config = shell_exec( 'vagrant ssh-config 2>/dev/null' ); if ( preg_match_all( '#\s*(?[a-zA-Z]+)\s(?.+)\s*#', $ssh_config, $matches ) ) { $values = array_combine( $matches['NAME'], $matches['VALUE'] ); $cache->write( $cache_key, json_encode( $values ) ); } } if ( empty( $bits['host'] ) || $bits['host'] === $values['Host'] ) { $bits['scheme'] = 'ssh'; $bits['host'] = $values['HostName']; $bits['port'] = $values['Port']; $bits['user'] = $values['User']; $bits['key'] = $values['IdentityFile']; } // If we could not resolve the bits still, fallback to just `vagrant ssh` if ( 'vagrant' === $bits['scheme'] ) { $command = 'vagrant ssh -c %s %s'; $escaped_command = sprintf( $command, escapeshellarg( $wp_command ), escapeshellarg( $bits['host'] ) ); } } // Default scheme is SSH. if ( 'ssh' === $bits['scheme'] || null === $bits['scheme'] ) { $command = 'ssh -q %s %s %s'; if ( $bits['user'] ) { $bits['host'] = $bits['user'] . '@' . $bits['host']; } $command_args = [ $bits['port'] ? '-p ' . (int) $bits['port'] . ' ' : '', $bits['key'] ? sprintf( '-i %s', $bits['key'] ) : '', $is_tty ? '-t' : '-T', ]; $escaped_command = sprintf( $command, implode( ' ', array_filter( $command_args ) ), escapeshellarg( $bits['host'] ), escapeshellarg( $wp_command ) ); } WP_CLI::debug( 'Running SSH command: ' . $escaped_command, 'bootstrap' ); return $escaped_command; } /** * Check whether a given command is disabled by the config * * @return bool */ public function is_command_disabled( $command ) { $path = implode( ' ', array_slice( \WP_CLI\Dispatcher\get_path( $command ), 1 ) ); return in_array( $path, $this->config['disabled_commands'], true ); } /** * Returns wp-config.php code, skipping the loading of wp-settings.php * * @return string */ public function get_wp_config_code() { $wp_config_path = Utils\locate_wp_config(); $wp_config_code = explode( "\n", file_get_contents( $wp_config_path ) ); $found_wp_settings = false; $lines_to_run = array(); foreach ( $wp_config_code as $line ) { if ( preg_match( '/^\s*require.+wp-settings\.php/', $line ) ) { $found_wp_settings = true; continue; } $lines_to_run[] = $line; } if ( ! $found_wp_settings ) { WP_CLI::error( 'Strange wp-config.php file: wp-settings.php is not loaded directly.' ); } $source = implode( "\n", $lines_to_run ); $source = Utils\replace_path_consts( $source, $wp_config_path ); return preg_replace( '|^\s*\<\?php\s*|', '', $source ); } /** * Transparently convert deprecated syntaxes * * @param array $args * @param array $assoc_args * @return array */ private static function back_compat_conversions( $args, $assoc_args ) { $top_level_aliases = array( 'sql' => 'db', 'blog' => 'site', ); if ( count( $args ) > 0 ) { foreach ( $top_level_aliases as $old => $new ) { if ( $old === $args[0] ) { $args[0] = $new; break; } } } // *-meta -> * meta if ( ! empty( $args ) && preg_match( '/(post|comment|user|network)-meta/', $args[0], $matches ) ) { array_shift( $args ); array_unshift( $args, 'meta' ); array_unshift( $args, $matches[1] ); } // cli aliases -> cli alias list if ( array( 'cli', 'aliases' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1], $args[2] ) = array( 'cli', 'alias', 'list' ); } // core (multsite-)install --admin_name= -> --admin_user= if ( count( $args ) > 0 && 'core' === $args[0] && isset( $assoc_args['admin_name'] ) ) { $assoc_args['admin_user'] = $assoc_args['admin_name']; unset( $assoc_args['admin_name'] ); } // core config -> config create if ( array( 'core', 'config' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1] ) = array( 'config', 'create' ); } // core language -> language core if ( array( 'core', 'language' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1] ) = array( 'language', 'core' ); } // checksum core -> core verify-checksums if ( array( 'checksum', 'core' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1] ) = array( 'core', 'verify-checksums' ); } // checksum plugin -> plugin verify-checksums if ( array( 'checksum', 'plugin' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1] ) = array( 'plugin', 'verify-checksums' ); } // site create --site_id= -> site create --network_id= if ( count( $args ) >= 2 && 'site' === $args[0] && 'create' === $args[1] && isset( $assoc_args['site_id'] ) ) { $assoc_args['network_id'] = $assoc_args['site_id']; unset( $assoc_args['site_id'] ); } // {plugin|theme} update-all -> {plugin|theme} update --all if ( count( $args ) > 1 && in_array( $args[0], array( 'plugin', 'theme' ), true ) && 'update-all' === $args[1] ) { $args[1] = 'update'; $assoc_args['all'] = true; } // transient delete-expired -> transient delete --expired if ( count( $args ) > 1 && 'transient' === $args[0] && 'delete-expired' === $args[1] ) { $args[1] = 'delete'; $assoc_args['expired'] = true; } // transient delete-all -> transient delete --all if ( count( $args ) > 1 && 'transient' === $args[0] && 'delete-all' === $args[1] ) { $args[1] = 'delete'; $assoc_args['all'] = true; } // plugin scaffold -> scaffold plugin if ( array( 'plugin', 'scaffold' ) === array_slice( $args, 0, 2 ) ) { list( $args[0], $args[1] ) = array( $args[1], $args[0] ); } // foo --help -> help foo if ( isset( $assoc_args['help'] ) ) { array_unshift( $args, 'help' ); unset( $assoc_args['help'] ); } // {post|user} list --ids -> {post|user} list --format=ids if ( count( $args ) > 1 && in_array( $args[0], array( 'post', 'user' ), true ) && 'list' === $args[1] && isset( $assoc_args['ids'] ) ) { $assoc_args['format'] = 'ids'; unset( $assoc_args['ids'] ); } // --json -> --format=json if ( isset( $assoc_args['json'] ) ) { $assoc_args['format'] = 'json'; unset( $assoc_args['json'] ); } // --{version|info} -> cli {version|info} if ( empty( $args ) ) { $special_flags = array( 'version', 'info' ); foreach ( $special_flags as $key ) { if ( isset( $assoc_args[ $key ] ) ) { $args = array( 'cli', $key ); unset( $assoc_args[ $key ] ); break; } } } // (post|comment|site|term) url --> (post|comment|site|term) list --*__in --field=url if ( count( $args ) >= 2 && in_array( $args[0], array( 'post', 'comment', 'site', 'term' ), true ) && 'url' === $args[1] ) { switch ( $args[0] ) { case 'post': $post_ids = array_slice( $args, 2 ); $args = array( 'post', 'list' ); $assoc_args['post__in'] = implode( ',', $post_ids ); $assoc_args['post_type'] = 'any'; $assoc_args['orderby'] = 'post__in'; $assoc_args['field'] = 'url'; break; case 'comment': $comment_ids = array_slice( $args, 2 ); $args = array( 'comment', 'list' ); $assoc_args['comment__in'] = implode( ',', $comment_ids ); $assoc_args['orderby'] = 'comment__in'; $assoc_args['field'] = 'url'; break; case 'site': $site_ids = array_slice( $args, 2 ); $args = array( 'site', 'list' ); $assoc_args['site__in'] = implode( ',', $site_ids ); $assoc_args['field'] = 'url'; break; case 'term': $taxonomy = ''; if ( isset( $args[2] ) ) { $taxonomy = $args[2]; } $term_ids = array_slice( $args, 3 ); $args = array( 'term', 'list', $taxonomy ); $assoc_args['include'] = implode( ',', $term_ids ); $assoc_args['orderby'] = 'include'; $assoc_args['field'] = 'url'; break; } } // config get --[global|constant]= --> config get --type=constant|variable // config get --> config list if ( count( $args ) === 2 && 'config' === $args[0] && 'get' === $args[1] ) { if ( isset( $assoc_args['global'] ) ) { $name = $assoc_args['global']; $type = 'variable'; unset( $assoc_args['global'] ); } elseif ( isset( $assoc_args['constant'] ) ) { $name = $assoc_args['constant']; $type = 'constant'; unset( $assoc_args['constant'] ); } if ( ! empty( $name ) && ! empty( $type ) ) { $args[] = $name; $assoc_args['type'] = $type; } else { // We had a 'config get' without a '', so assume 'list' was wanted. $args[1] = 'list'; } } return array( $args, $assoc_args ); } /** * Whether or not the output should be rendered in color * * @return bool */ public function in_color() { return $this->colorize; } public function init_colorization() { if ( 'auto' === $this->config['color'] ) { $this->colorize = ( ! \WP_CLI\Utils\isPiped() && ! \WP_CLI\Utils\is_windows() ); } else { $this->colorize = $this->config['color']; } } public function init_logger() { if ( $this->config['quiet'] ) { $logger = new \WP_CLI\Loggers\Quiet(); } else { $logger = new \WP_CLI\Loggers\Regular( $this->in_color() ); } WP_CLI::set_logger( $logger ); } public function get_required_files() { return $this->required_files; } /** * Do WordPress core files exist? * * @return bool */ private function wp_exists() { return file_exists( ABSPATH . 'wp-includes/version.php' ); } /** * Are WordPress core files readable? * * @return bool */ private function wp_is_readable() { return is_readable( ABSPATH . 'wp-includes/version.php' ); } private function check_wp_version() { $wp_exists = $this->wp_exists(); $wp_is_readable = $this->wp_is_readable(); if ( ! $wp_exists || ! $wp_is_readable ) { $this->show_synopsis_if_composite_command(); // If the command doesn't exist use as error. $args = $this->cmd_starts_with( array( 'help' ) ) ? array_slice( $this->arguments, 1 ) : $this->arguments; $suggestion_or_disabled = $this->find_command_to_run( $args ); if ( is_string( $suggestion_or_disabled ) ) { if ( ! preg_match( '/disabled from the config file.$/', $suggestion_or_disabled ) ) { WP_CLI::warning( "No WordPress installation found. If the command '" . implode( ' ', $args ) . "' is in a plugin or theme, pass --path=`path/to/wordpress`." ); } WP_CLI::error( $suggestion_or_disabled ); } if ( $wp_exists && ! $wp_is_readable ) { WP_CLI::error( 'It seems, the WordPress core files do not have the proper file permissions.' ); } WP_CLI::error( "This does not seem to be a WordPress installation.\n" . 'Pass --path=`path/to/wordpress` or run `wp core download`.' ); } global $wp_version; include ABSPATH . 'wp-includes/version.php'; $minimum_version = '3.7'; if ( version_compare( $wp_version, $minimum_version, '<' ) ) { WP_CLI::error( "WP-CLI needs WordPress $minimum_version or later to work properly. " . "The version currently installed is $wp_version.\n" . 'Try running `wp core download --force`.' ); } } public function init_config() { $configurator = \WP_CLI::get_configurator(); $argv = array_slice( $GLOBALS['argv'], 1 ); $this->alias = null; if ( ! empty( $argv[0] ) && preg_match( '#' . Configurator::ALIAS_REGEX . '#', $argv[0], $matches ) ) { $this->alias = array_shift( $argv ); } // File config { $this->global_config_path = $this->get_global_config_path(); $this->project_config_path = $this->get_project_config_path(); $configurator->merge_yml( $this->global_config_path, $this->alias ); $config = $configurator->to_array(); $this->required_files['global'] = $config[0]['require']; $configurator->merge_yml( $this->project_config_path, $this->alias ); $config = $configurator->to_array(); $this->required_files['project'] = $config[0]['require']; } // Runtime config and args { list( $args, $assoc_args, $this->runtime_config ) = $configurator->parse_args( $argv ); list( $this->arguments, $this->assoc_args ) = self::back_compat_conversions( $args, $assoc_args ); $configurator->merge_array( $this->runtime_config ); } list( $this->config, $this->extra_config ) = $configurator->to_array(); $this->aliases = $configurator->get_aliases(); if ( count( $this->aliases ) && ! isset( $this->aliases['@all'] ) ) { $this->aliases = array_reverse( $this->aliases ); $this->aliases['@all'] = 'Run command against every registered alias.'; $this->aliases = array_reverse( $this->aliases ); } $this->required_files['runtime'] = $this->config['require']; } private function check_root() { if ( $this->config['allow-root'] ) { return; # they're aware of the risks! } if ( count( $this->arguments ) >= 2 && 'cli' === $this->arguments[0] && in_array( $this->arguments[1], array( 'update', 'info' ), true ) ) { return; # make it easier to update root-owned copies } if ( ! function_exists( 'posix_geteuid' ) ) { return; # posix functions not available } if ( posix_geteuid() !== 0 ) { return; # not root } WP_CLI::error( "YIKES! It looks like you're running this as root. You probably meant to " . "run this as the user that your WordPress installation exists under.\n" . "\n" . "If you REALLY mean to run this as root, we won't stop you, but just " . 'bear in mind that any code on this site will then have full control of ' . "your server, making it quite DANGEROUS.\n" . "\n" . "If you'd like to continue as root, please run this again, adding this " . "flag: --allow-root\n" . "\n" . "If you'd like to run it as the user that this site is under, you can " . "run the following to become the respective user:\n" . "\n" . " sudo -u USER -i -- wp \n" . "\n" ); } private function run_alias_group( $aliases ) { Utils\check_proc_available( 'group alias' ); $php_bin = escapeshellarg( Utils\get_php_binary() ); $script_path = $GLOBALS['argv'][0]; if ( getenv( 'WP_CLI_CONFIG_PATH' ) ) { $config_path = getenv( 'WP_CLI_CONFIG_PATH' ); } else { $config_path = Utils\get_home_dir() . '/.wp-cli/config.yml'; } $config_path = escapeshellarg( $config_path ); foreach ( $aliases as $alias ) { WP_CLI::log( $alias ); $args = implode( ' ', array_map( 'escapeshellarg', $this->arguments ) ); $assoc_args = Utils\assoc_args_to_str( $this->assoc_args ); $runtime_config = Utils\assoc_args_to_str( $this->runtime_config ); $full_command = "WP_CLI_CONFIG_PATH={$config_path} {$php_bin} {$script_path} {$alias} {$args}{$assoc_args}{$runtime_config}"; $proc = Utils\proc_open_compat( $full_command, array( STDIN, STDOUT, STDERR ), $pipes ); proc_close( $proc ); } } private function set_alias( $alias ) { $orig_config = $this->config; $alias_config = $this->aliases[ $this->alias ]; $this->config = array_merge( $orig_config, $alias_config ); foreach ( $alias_config as $key => $_ ) { if ( isset( $orig_config[ $key ] ) && ! is_null( $orig_config[ $key ] ) ) { $this->assoc_args[ $key ] = $orig_config[ $key ]; } } } public function start() { // Enable PHP error reporting to stderr if testing. Will need to be re-enabled after WP loads. if ( getenv( 'BEHAT_RUN' ) ) { $this->enable_error_reporting(); } WP_CLI::debug( $this->global_config_path_debug, 'bootstrap' ); WP_CLI::debug( $this->project_config_path_debug, 'bootstrap' ); WP_CLI::debug( 'argv: ' . implode( ' ', $GLOBALS['argv'] ), 'bootstrap' ); $this->check_root(); if ( $this->alias ) { if ( '@all' === $this->alias && ! isset( $this->aliases['@all'] ) ) { WP_CLI::error( "Cannot use '@all' when no aliases are registered." ); } if ( '@all' === $this->alias && is_string( $this->aliases['@all'] ) ) { $aliases = array_keys( $this->aliases ); $k = array_search( '@all', $aliases, true ); unset( $aliases[ $k ] ); $this->run_alias_group( $aliases ); exit; } if ( ! array_key_exists( $this->alias, $this->aliases ) ) { $error_msg = "Alias '{$this->alias}' not found."; $suggestion = Utils\get_suggestion( $this->alias, array_keys( $this->aliases ), $threshold = 2 ); if ( $suggestion ) { $error_msg .= PHP_EOL . "Did you mean '{$suggestion}'?"; } WP_CLI::error( $error_msg ); } // Numerically indexed means a group of aliases if ( isset( $this->aliases[ $this->alias ][0] ) ) { $group_aliases = $this->aliases[ $this->alias ]; $all_aliases = array_keys( $this->aliases ); $diff = array_diff( $group_aliases, $all_aliases ); if ( ! empty( $diff ) ) { WP_CLI::error( "Group '{$this->alias}' contains one or more invalid aliases: " . implode( ', ', $diff ) ); } $this->run_alias_group( $group_aliases ); exit; } $this->set_alias( $this->alias ); } if ( empty( $this->arguments ) ) { $this->arguments[] = 'help'; } // Protect 'cli info' from most of the runtime, // except when the command will be run over SSH if ( 'cli' === $this->arguments[0] && ! empty( $this->arguments[1] ) && 'info' === $this->arguments[1] && ! $this->config['ssh'] ) { $this->run_command_and_exit(); } if ( isset( $this->config['http'] ) && ! class_exists( '\WP_REST_CLI\Runner' ) ) { WP_CLI::error( "RESTful WP-CLI needs to be installed. Try 'wp package install wp-cli/restful'." ); } if ( $this->config['ssh'] ) { $this->run_ssh_command( $this->config['ssh'] ); return; } // Handle --path parameter self::set_wp_root( $this->find_wp_root() ); // First try at showing man page - if help command and either haven't found 'version.php' or 'wp-config.php' (so won't be loading WP & adding commands) or help on subcommand. if ( $this->cmd_starts_with( array( 'help' ) ) && ( ! $this->wp_exists() || ! Utils\locate_wp_config() || count( $this->arguments ) > 2 ) ) { $this->auto_check_update(); $this->run_command( $this->arguments, $this->assoc_args ); // Help didn't exit so failed to find the command at this stage. } // Handle --url parameter $url = self::guess_url( $this->config ); if ( $url ) { \WP_CLI::set_url( $url ); } $this->do_early_invoke( 'before_wp_load' ); $this->check_wp_version(); if ( $this->cmd_starts_with( array( 'config', 'create' ) ) ) { $this->run_command_and_exit(); } if ( ! Utils\locate_wp_config() ) { WP_CLI::error( "'wp-config.php' not found.\n" . 'Either create one manually or use `wp config create`.' ); } // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Declaring WP native constants. if ( $this->cmd_starts_with( array( 'core', 'is-installed' ) ) || $this->cmd_starts_with( array( 'core', 'update-db' ) ) ) { define( 'WP_INSTALLING', true ); } if ( count( $this->arguments ) >= 2 && 'core' === $this->arguments[0] && in_array( $this->arguments[1], array( 'install', 'multisite-install' ), true ) ) { define( 'WP_INSTALLING', true ); // We really need a URL here if ( ! isset( $_SERVER['HTTP_HOST'] ) ) { $url = 'http://example.com'; \WP_CLI::set_url( $url ); } if ( 'multisite-install' === $this->arguments[1] ) { // need to fake some globals to skip the checks in wp-includes/ms-settings.php $url_parts = Utils\parse_url( $url ); self::fake_current_site_blog( $url_parts ); if ( ! defined( 'COOKIEHASH' ) ) { define( 'COOKIEHASH', md5( $url_parts['host'] ) ); } } } if ( $this->cmd_starts_with( array( 'import' ) ) ) { define( 'WP_LOAD_IMPORTERS', true ); define( 'WP_IMPORTING', true ); } if ( $this->cmd_starts_with( array( 'cron', 'event', 'run' ) ) ) { define( 'DOING_CRON', true ); } // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound $this->load_wordpress(); $this->run_command_and_exit(); } /** * Load WordPress, if it hasn't already been loaded */ public function load_wordpress() { static $wp_cli_is_loaded; // Globals not explicitly globalized in WordPress global $site_id, $wpdb, $public, $current_site, $current_blog, $path, $shortcode_tags; if ( ! empty( $wp_cli_is_loaded ) ) { return; } $wp_cli_is_loaded = true; WP_CLI::debug( 'Begin WordPress load', 'bootstrap' ); WP_CLI::do_hook( 'before_wp_load' ); $this->check_wp_version(); $wp_config_path = Utils\locate_wp_config(); if ( ! $wp_config_path ) { WP_CLI::error( "'wp-config.php' not found.\n" . 'Either create one manually or use `wp config create`.' ); } WP_CLI::debug( 'wp-config.php path: ' . $wp_config_path, 'bootstrap' ); WP_CLI::do_hook( 'before_wp_config_load' ); // Load wp-config.php code, in the global scope $wp_cli_original_defined_vars = get_defined_vars(); eval( $this->get_wp_config_code() ); // phpcs:ignore Squiz.PHP.Eval.Discouraged foreach ( get_defined_vars() as $key => $var ) { if ( array_key_exists( $key, $wp_cli_original_defined_vars ) || 'wp_cli_original_defined_vars' === $key ) { continue; } // phpcs:ignore PHPCompatibility.Variables.ForbiddenGlobalVariableVariable.NonBareVariableFound global ${$key}; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ${$key} = $var; } $this->maybe_update_url_from_domain_constant(); WP_CLI::do_hook( 'after_wp_config_load' ); $this->do_early_invoke( 'after_wp_config_load' ); // Prevent error notice from wp_guess_url() when core isn't installed if ( $this->cmd_starts_with( array( 'core', 'is-installed' ) ) && ! defined( 'COOKIEHASH' ) ) { define( 'COOKIEHASH', md5( 'wp-cli' ) ); } // Load WP-CLI utilities require WP_CLI_ROOT . '/php/utils-wp.php'; // Set up WordPress bootstrap actions and filters $this->setup_bootstrap_hooks(); // Load Core, mu-plugins, plugins, themes etc. if ( Utils\wp_version_compare( '4.6-alpha-37575', '>=' ) ) { if ( $this->cmd_starts_with( array( 'help' ) ) ) { // Hack: define `WP_DEBUG` and `WP_DEBUG_DISPLAY` to get `wpdb::bail()` to `wp_die()`. if ( ! defined( 'WP_DEBUG' ) ) { define( 'WP_DEBUG', true ); } if ( ! defined( 'WP_DEBUG_DISPLAY' ) ) { define( 'WP_DEBUG_DISPLAY', true ); } } require ABSPATH . 'wp-settings.php'; } else { require WP_CLI_ROOT . '/php/wp-settings-cli.php'; } // Fix memory limit. See http://core.trac.wordpress.org/ticket/14889 // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Blacklisted -- This is perfectly fine for CLI usage. ini_set( 'memory_limit', -1 ); // Load all the admin APIs, for convenience require ABSPATH . 'wp-admin/includes/admin.php'; add_filter( 'filesystem_method', static function () { return 'direct'; }, 99 ); // Re-enable PHP error reporting to stderr if testing. if ( getenv( 'BEHAT_RUN' ) ) { $this->enable_error_reporting(); } WP_CLI::debug( 'Loaded WordPress', 'bootstrap' ); WP_CLI::do_hook( 'after_wp_load' ); } private static function fake_current_site_blog( $url_parts ) { global $current_site, $current_blog; if ( ! isset( $url_parts['path'] ) ) { $url_parts['path'] = '/'; } // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Intentional override. $current_site = (object) array( 'id' => 1, 'blog_id' => 1, 'domain' => $url_parts['host'], 'path' => $url_parts['path'], 'cookie_domain' => $url_parts['host'], 'site_name' => 'Fake Site', ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Intentional override. $current_blog = (object) array( 'blog_id' => 1, 'site_id' => 1, 'domain' => $url_parts['host'], 'path' => $url_parts['path'], 'public' => '1', 'archived' => '0', 'mature' => '0', 'spam' => '0', 'deleted' => '0', 'lang_id' => '0', ); } /** * Called after wp-config.php is eval'd, to potentially reset `--url` */ private function maybe_update_url_from_domain_constant() { if ( ! empty( $this->config['url'] ) || ! empty( $this->config['blog'] ) ) { return; } if ( defined( 'DOMAIN_CURRENT_SITE' ) ) { $url = DOMAIN_CURRENT_SITE; if ( defined( 'PATH_CURRENT_SITE' ) ) { $url .= PATH_CURRENT_SITE; } \WP_CLI::set_url( $url ); } } /** * Set up hooks meant to run during the WordPress bootstrap process */ private function setup_bootstrap_hooks() { if ( $this->config['skip-plugins'] ) { $this->setup_skip_plugins_filters(); } if ( $this->config['skip-themes'] ) { WP_CLI::add_wp_hook( 'setup_theme', array( $this, 'action_setup_theme_wp_cli_skip_themes' ), 999 ); } if ( $this->cmd_starts_with( array( 'help' ) ) ) { // Try to trap errors on help. $help_handler = array( $this, 'help_wp_die_handler' ); // Avoid any cross PHP version issues by not using $this in anon function. WP_CLI::add_wp_hook( 'wp_die_handler', function () use ( $help_handler ) { return $help_handler; } ); } else { WP_CLI::add_wp_hook( 'wp_die_handler', static function () { return '\WP_CLI\Utils\wp_die_handler'; } ); } // Prevent code from performing a redirect WP_CLI::add_wp_hook( 'wp_redirect', 'WP_CLI\\Utils\\wp_redirect_handler' ); WP_CLI::add_wp_hook( 'nocache_headers', static function ( $headers ) { // WordPress might be calling nocache_headers() because of a dead db global $wpdb; if ( ! empty( $wpdb->error ) ) { Utils\wp_die_handler( $wpdb->error ); } // Otherwise, WP might be calling nocache_headers() because WP isn't installed Utils\wp_not_installed(); return $headers; } ); WP_CLI::add_wp_hook( 'setup_theme', static function () { // Polyfill is_customize_preview(), as it is needed by TwentyTwenty to // check for starter content. if ( ! function_exists( 'is_customize_preview' ) ) { function is_customize_preview() { return false; } } }, 0 ); // ALTERNATE_WP_CRON might trigger a redirect, which we can't handle if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) { WP_CLI::add_wp_hook( 'muplugins_loaded', static function () { remove_action( 'init', 'wp_cron' ); } ); } // Get rid of warnings when converting single site to multisite if ( defined( 'WP_INSTALLING' ) && $this->is_multisite() ) { $values = array( 'ms_files_rewriting' => null, 'active_sitewide_plugins' => array(), '_site_transient_update_core' => null, '_site_transient_update_themes' => null, '_site_transient_update_plugins' => null, 'WPLANG' => '', ); foreach ( $values as $key => $value ) { WP_CLI::add_wp_hook( "pre_site_option_$key", static function () use ( $values, $key ) { return $values[ $key ]; } ); } } // Always permit operations against sites, regardless of status WP_CLI::add_wp_hook( 'ms_site_check', '__return_true' ); // Always permit operations against WordPress, regardless of maintenance mode WP_CLI::add_wp_hook( 'enable_maintenance_mode', static function () { return false; } ); // Use our own debug mode handling instead of WP core WP_CLI::add_wp_hook( 'enable_wp_debug_mode_checks', static function ( $ret ) { Utils\wp_debug_mode(); return false; } ); // Never load advanced-cache.php drop-in when WP-CLI is operating WP_CLI::add_wp_hook( 'enable_loading_advanced_cache_dropin', static function () { return false; } ); // In a multisite installation, die if unable to find site given in --url parameter if ( $this->is_multisite() ) { $run_on_site_not_found = false; if ( $this->cmd_starts_with( array( 'cache', 'flush' ) ) ) { $run_on_site_not_found = 'cache flush'; } if ( $this->cmd_starts_with( array( 'search-replace' ) ) ) { // Table-specified // Bits: search-replace [...] // Or not against a specific blog if ( count( $this->arguments ) > 3 || ! empty( $this->assoc_args['network'] ) || ! empty( $this->assoc_args['all-tables'] ) || ! empty( $this->assoc_args['all-tables-with-prefix'] ) ) { $run_on_site_not_found = 'search-replace'; } } if ( $run_on_site_not_found && Utils\wp_version_compare( '4.0', '>=' ) ) { WP_CLI::add_wp_hook( 'ms_site_not_found', static function () use ( $run_on_site_not_found ) { // esc_sql() isn't yet loaded, but needed. if ( 'search-replace' === $run_on_site_not_found ) { require_once ABSPATH . WPINC . '/formatting.php'; } // PHP 5.3 compatible implementation of run_command_and_exit(). $runner = WP_CLI::get_runner(); $runner->run_command( $runner->arguments, $runner->assoc_args ); exit; }, 1 ); } WP_CLI::add_wp_hook( 'ms_site_not_found', static function ( $current_site, $domain, $path ) { $url = $domain . $path; $message = $url ? "Site '{$url}' not found." : 'Site not found.'; $has_param = isset( WP_CLI::get_runner()->config['url'] ); $has_const = defined( 'DOMAIN_CURRENT_SITE' ); $explanation = ''; if ( $has_param ) { $explanation = 'Verify `--url=` matches an existing site.'; } else { $explanation = "Define DOMAIN_CURRENT_SITE in 'wp-config.php' or use `--url=` to override."; if ( $has_const ) { $explanation = 'Verify DOMAIN_CURRENT_SITE matches an existing site or use `--url=` to override.'; } } if ( $explanation ) { $message .= ' ' . $explanation; } WP_CLI::error( $message ); }, 10, 3 ); } // The APC cache is not available on the command-line, so bail, to prevent cache poisoning WP_CLI::add_wp_hook( 'muplugins_loaded', static function () { if ( $GLOBALS['_wp_using_ext_object_cache'] && class_exists( 'APC_Object_Cache' ) ) { WP_CLI::warning( 'Running WP-CLI while the APC object cache is activated can result in cache corruption.' ); WP_CLI::confirm( 'Given the consequences, do you wish to continue?' ); } }, 0 ); // Handle --user parameter if ( ! defined( 'WP_INSTALLING' ) ) { $config = $this->config; WP_CLI::add_wp_hook( 'init', static function () use ( $config ) { if ( isset( $config['user'] ) ) { $fetcher = new \WP_CLI\Fetchers\User(); $user = $fetcher->get_check( $config['user'] ); wp_set_current_user( $user->ID ); } else { add_action( 'init', 'kses_remove_filters', 11 ); } }, 0 ); } // Avoid uncaught exception when using wp_mail() without defined $_SERVER['SERVER_NAME'] WP_CLI::add_wp_hook( 'wp_mail_from', static function ( $from_email ) { if ( 'wordpress@' === $from_email ) { $sitename = strtolower( Utils\parse_url( site_url(), PHP_URL_HOST ) ); if ( substr( $sitename, 0, 4 ) === 'www.' ) { $sitename = substr( $sitename, 4 ); } $from_email = 'wordpress@' . $sitename; } return $from_email; } ); // Don't apply set_url_scheme in get_site_url() WP_CLI::add_wp_hook( 'site_url', static function ( $url, $path, $scheme, $blog_id ) { if ( empty( $blog_id ) || ! is_multisite() ) { $url = get_option( 'siteurl' ); } else { switch_to_blog( $blog_id ); $url = get_option( 'siteurl' ); restore_current_blog(); } if ( $path && is_string( $path ) ) { $url .= '/' . ltrim( $path, '/' ); } return $url; }, 0, 4 ); // Set up hook for plugins and themes to conditionally add WP-CLI commands. WP_CLI::add_wp_hook( 'init', static function () { do_action( 'cli_init' ); } ); } /** * Set up the filters to skip the loaded plugins */ private function setup_skip_plugins_filters() { $wp_cli_filter_active_plugins = static function ( $plugins ) { $skipped_plugins = WP_CLI::get_runner()->config['skip-plugins']; if ( true === $skipped_plugins ) { return array(); } if ( ! is_array( $plugins ) ) { return $plugins; } foreach ( $plugins as $a => $b ) { // active_sitewide_plugins stores plugin name as the key. if ( false !== strpos( current_filter(), 'active_sitewide_plugins' ) && Utils\is_plugin_skipped( $a ) ) { unset( $plugins[ $a ] ); // active_plugins stores plugin name as the value. } elseif ( false !== strpos( current_filter(), 'active_plugins' ) && Utils\is_plugin_skipped( $b ) ) { unset( $plugins[ $a ] ); } } // Reindex because active_plugins expects a numeric index. if ( false !== strpos( current_filter(), 'active_plugins' ) ) { $plugins = array_values( $plugins ); } return $plugins; }; $hooks = array( 'pre_site_option_active_sitewide_plugins', 'site_option_active_sitewide_plugins', 'pre_option_active_plugins', 'option_active_plugins', ); foreach ( $hooks as $hook ) { WP_CLI::add_wp_hook( $hook, $wp_cli_filter_active_plugins, 999 ); } WP_CLI::add_wp_hook( 'plugins_loaded', static function () use ( $hooks, $wp_cli_filter_active_plugins ) { foreach ( $hooks as $hook ) { remove_filter( $hook, $wp_cli_filter_active_plugins, 999 ); } }, 0 ); } /** * Set up the filters to skip the loaded theme */ public function action_setup_theme_wp_cli_skip_themes() { $wp_cli_filter_active_theme = static function ( $value ) { $skipped_themes = WP_CLI::get_runner()->config['skip-themes']; if ( true === $skipped_themes ) { return ''; } if ( ! is_array( $skipped_themes ) ) { $skipped_themes = explode( ',', $skipped_themes ); } $checked_value = $value; // Always check against the stylesheet value // This ensures a child theme can be skipped when template differs if ( false !== stripos( current_filter(), 'option_template' ) ) { $checked_value = get_option( 'stylesheet' ); } if ( '' === $checked_value || in_array( $checked_value, $skipped_themes, true ) ) { return ''; } return $value; }; $hooks = array( 'pre_option_template', 'option_template', 'pre_option_stylesheet', 'option_stylesheet', ); foreach ( $hooks as $hook ) { add_filter( $hook, $wp_cli_filter_active_theme, 999 ); } // Clean up after the TEMPLATEPATH and STYLESHEETPATH constants are defined WP_CLI::add_wp_hook( 'after_setup_theme', static function () use ( $hooks, $wp_cli_filter_active_theme ) { foreach ( $hooks as $hook ) { remove_filter( $hook, $wp_cli_filter_active_theme, 999 ); } }, 0 ); } /** * Whether or not this WordPress installation is multisite. * * For use after wp-config.php has loaded, but before the rest of WordPress * is loaded. */ private function is_multisite() { if ( defined( 'MULTISITE' ) ) { return MULTISITE; } if ( defined( 'SUBDOMAIN_INSTALL' ) || defined( 'VHOST' ) || defined( 'SUNRISE' ) ) { return true; } return false; } /** * Error handler for `wp_die()` when the command is help to try to trap errors (db connection failure in particular) during WordPress load. */ public function help_wp_die_handler( $message ) { $help_exit_warning = 'Error during WordPress load.'; if ( $message instanceof \WP_Error ) { $help_exit_warning = WP_CLI\Utils\wp_clean_error_message( $message->get_error_message() ); } elseif ( is_string( $message ) ) { $help_exit_warning = WP_CLI\Utils\wp_clean_error_message( $message ); } $this->run_command_and_exit( $help_exit_warning ); } /** * Check whether there's a WP-CLI update available, and suggest update if so. */ private function auto_check_update() { // `wp cli update` only works with Phars at this time. if ( ! Utils\inside_phar() ) { return; } $existing_phar = realpath( $_SERVER['argv'][0] ); // Phar needs to be writable to be easily updateable. if ( ! is_writable( $existing_phar ) || ! is_writable( dirname( $existing_phar ) ) ) { return; } // Only check for update when a human is operating. if ( ! function_exists( 'posix_isatty' ) || ! posix_isatty( STDOUT ) ) { return; } // Allow hosts and other providers to disable automatic check update. if ( getenv( 'WP_CLI_DISABLE_AUTO_CHECK_UPDATE' ) ) { return; } // Permit configuration of number of days between checks. $days_between_checks = getenv( 'WP_CLI_AUTO_CHECK_UPDATE_DAYS' ); if ( false === $days_between_checks ) { $days_between_checks = 1; } $cache = WP_CLI::get_cache(); $cache_key = 'wp-cli-update-check'; // Bail early on the first check, so we don't always check on an unwritable cache. if ( ! $cache->has( $cache_key ) ) { $cache->write( $cache_key, time() ); return; } // Bail if last check is still within our update check time period. $last_check = (int) $cache->read( $cache_key ); if ( ( time() - ( 24 * 60 * 60 * $days_between_checks ) ) < $last_check ) { return; } // In case the operation fails, ensure the timestamp has been updated. $cache->write( $cache_key, time() ); // Check whether any updates are available. ob_start(); WP_CLI::run_command( array( 'cli', 'check-update' ), array( 'format' => 'count', ) ); $count = ob_get_clean(); if ( ! $count ) { return; } // Looks like an update is available, so let's prompt to update. WP_CLI::run_command( array( 'cli', 'update' ) ); // If the Phar was replaced, we can't proceed with the original process. exit; } /** * Get a suggestion on similar (sub)commands when the user entered an * unknown (sub)command. * * @param string $entry User entry that didn't match an * existing command. * @param CompositeCommand $root_command Root command to start search for * suggestions at. * * @return string Suggestion that fits the user entry, or an empty string. */ private function get_subcommand_suggestion( $entry, CompositeCommand $root_command = null ) { $commands = array(); $this->enumerate_commands( $root_command ?: \WP_CLI::get_root_command(), $commands ); return Utils\get_suggestion( $entry, $commands, $threshold = 2 ); } /** * Recursive method to enumerate all known commands. * * @param CompositeCommand $command Composite command to recurse over. * @param array $list Reference to list accumulating results. * @param string $parent Parent command to use as prefix. */ private function enumerate_commands( CompositeCommand $command, array &$list, $parent = '' ) { foreach ( $command->get_subcommands() as $subcommand ) { /** @var CompositeCommand $subcommand */ $command_string = empty( $parent ) ? $subcommand->get_name() : "{$parent} {$subcommand->get_name()}"; $list[] = $command_string; $this->enumerate_commands( $subcommand, $list, $command_string ); } } /** * Enables (almost) full PHP error reporting to stderr. */ private function enable_error_reporting() { if ( E_ALL !== error_reporting() ) { // Don't enable E_DEPRECATED as old versions of WP use PHP 4 style constructors and the mysql extension. error_reporting( E_ALL & ~E_DEPRECATED ); } ini_set( 'display_errors', 'stderr' ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted } } get_protected_commands(); $current_command = $this->get_current_command(); foreach ( $commands as $command ) { if ( 0 === strpos( $current_command, $command ) ) { $state->setValue( BootstrapState::IS_PROTECTED_COMMAND, true ); } } return $state; } /** * Get the list of protected commands. * * @return array */ private function get_protected_commands() { return array( 'cli info', 'package', ); } /** * Get the current command as a string. * * @return string Current command to be executed. */ private function get_current_command() { $runner = new RunnerInstance(); return implode( ' ', (array) $runner()->arguments ); } } get_custom_vendor_folder(); if ( false !== $custom_vendor ) { array_unshift( $autoloader_paths, WP_CLI_ROOT . '/../../../' . $custom_vendor . '/autoload.php' ); } \WP_CLI::debug( sprintf( 'Fallback autoloader paths: %s', implode( ', ', $autoloader_paths ) ), 'bootstrap' ); return $autoloader_paths; } } WP_CLI_ROOT . '/php/WP_CLI', 'cli' => WP_CLI_VENDOR_DIR . '/wp-cli/php-cli-tools/lib/cli', 'Requests' => WP_CLI_VENDOR_DIR . '/rmccue/requests/library/Requests', 'Symfony\Component\Finder' => WP_CLI_VENDOR_DIR . '/symfony/finder/', ]; foreach ( $mappings as $namespace => $folder ) { $autoloader->add_namespace( $namespace, $folder ); } include_once WP_CLI_VENDOR_DIR . '/rmccue/requests/library/Requests.php'; include_once WP_CLI_VENDOR_DIR . '/wp-cli/mustangostang-spyc/Spyc.php'; $autoloader->register(); return $state; } } state = $state; $found_autoloader = false; $autoloader_paths = $this->get_autoloader_paths(); if ( false === $autoloader_paths ) { // Skip this autoloading step. return $state; } foreach ( $autoloader_paths as $autoloader_path ) { if ( is_readable( $autoloader_path ) ) { try { \WP_CLI::debug( sprintf( 'Loading detected autoloader: %s', $autoloader_path ), 'bootstrap' ); require $autoloader_path; $found_autoloader = true; } catch ( \Exception $exception ) { \WP_CLI::warning( "Failed to load autoloader '{$autoloader_path}'. Reason: " . $exception->getMessage() ); } } } if ( ! $found_autoloader ) { $this->handle_failure(); } return $this->state; } /** * Get the name of the custom vendor folder as set in `composer.json`. * * @return string|false Name of the custom vendor folder or false if none. */ protected function get_custom_vendor_folder() { $maybe_composer_json = WP_CLI_ROOT . '/../../../composer.json'; if ( ! is_readable( $maybe_composer_json ) ) { return false; } $composer = json_decode( file_get_contents( $maybe_composer_json ) ); if ( ! empty( $composer->config ) && ! empty( $composer->config->{'vendor-dir'} ) ) { return $composer->config->{'vendor-dir'}; } return false; } /** * Handle the failure to find an autoloader. * * @return void */ protected function handle_failure() { } /** * Get the autoloader paths to scan for an autoloader. * * @return string[]|false Array of strings with autoloader paths, or false * to skip. */ abstract protected function get_autoloader_paths(); } start(); return $state; } } add_deferred_commands(); // Process deferred command additions for commands added through // plugins. \WP_CLI::add_hook( 'before_run_command', array( $this, 'add_deferred_commands' ) ); return $state; } /** * Add deferred commands that are still waiting to be processed. */ public function add_deferred_commands() { $deferred_additions = \WP_CLI::get_deferred_additions(); foreach ( $deferred_additions as $name => $addition ) { $addition_data = array(); foreach ( $addition as $addition_key => $addition_value ) { // Describe the callable as a string instead of directly printing it // for better debug info if ( 'callable' === $addition_key ) { $addition_value = \WP_CLI\Utils\describe_callable( $addition_value ); } elseif ( is_array( $addition_value ) ) { $addition_value = json_encode( $addition_value ); } $addition_data[] = sprintf( '%s: %s', $addition_key, $addition_value ); } \WP_CLI::debug( sprintf( 'Adding deferred command: %s (%s)', $name, implode( ', ', $addition_data ) ), 'bootstrap' ); \WP_CLI::add_command( $name, $addition['callable'], $addition['args'] ); } } } declare_loggers(); $runner = new RunnerInstance(); $runner()->init_logger(); return $state; } /** * Load the class declarations for the loggers. */ private function declare_loggers() { $logger_dir = WP_CLI_ROOT . '/php/WP_CLI/Loggers'; $iterator = new \DirectoryIterator( $logger_dir ); // Make sure the base class is declared first. include_once "$logger_dir/Base.php"; foreach ( $iterator as $filename ) { if ( '.php' !== substr( $filename, - 4 ) ) { continue; } include_once "$logger_dir/$filename"; } } } ` option. * * @package WP_CLI\Bootstrap */ final class LoadRequiredCommand implements BootstrapStep { /** * Process this single bootstrapping step. * * @param BootstrapState $state Contextual state to pass into the step. * * @return BootstrapState Modified state to pass to the next step. */ public function process( BootstrapState $state ) { if ( $state->getValue( BootstrapState::IS_PROTECTED_COMMAND, false ) ) { return $state; } $runner = new RunnerInstance(); if ( ! isset( $runner()->config['require'] ) ) { return $state; } foreach ( $runner()->config['require'] as $path ) { if ( ! file_exists( $path ) ) { $context = ''; $required_files = $runner()->get_required_files(); foreach ( array( 'global', 'project', 'runtime' ) as $scope ) { if ( in_array( $path, $required_files[ $scope ], true ) ) { switch ( $scope ) { case 'global': $context = ' (from global ' . Utils\basename( $runner()->get_global_config_path() ) . ')'; break; case 'project': $context = ' (from project\'s ' . Utils\basename( $runner()->get_project_config_path() ) . ')'; break; case 'runtime': $context = ' (from runtime argument)'; break; } break; } } WP_CLI::error( sprintf( "Required file '%s' doesn't exist%s.", Utils\basename( $path ), $context ) ); } Utils\load_file( $path ); WP_CLI::debug( 'Required file from config: ' . $path, 'bootstrap' ); } return $state; } } getMessage() ); } } return $state; } } init_colorization(); return $state; } } state->getValue( BootstrapState::IS_PROTECTED_COMMAND, false ) ) { return false; } $runner = new RunnerInstance(); $skip_packages = $runner()->config['skip-packages']; if ( true === $skip_packages ) { \WP_CLI::debug( 'Skipped loading packages.', 'bootstrap' ); return false; } $autoloader_path = $runner()->get_packages_dir_path() . 'vendor/autoload.php'; if ( is_readable( $autoloader_path ) ) { \WP_CLI::debug( 'Loading packages from: ' . $autoloader_path, 'bootstrap' ); return array( $autoloader_path, ); } return false; } /** * Handle the failure to find an autoloader. * * @return void */ protected function handle_failure() { \WP_CLI::debug( 'No package autoload found to load.', 'bootstrap' ); } } state ) ? $this->state[ $key ] : $fallback; } /** * Set the state value for a given key. * * @param string $key Key to set the state for. * @param mixed $value Value to set the state for the given key to. * * @return void */ public function setValue( $key, $value ) { $this->state[ $key ] = $value; } } init_config(); return $state; } } * Jordi Boggiano */ namespace WP_CLI; use Symfony\Component\Finder\Finder; use WP_CLI\Utils; /** * Reads/writes to a filesystem cache */ class FileCache { /** * @var string cache path */ protected $root; /** * @var bool */ protected $enabled = true; /** * @var int files time to live */ protected $ttl; /** * @var int max total size */ protected $max_size; /** * @var string key allowed chars (regex class) */ protected $whitelist; /** * @param string $cache_dir location of the cache * @param int $ttl cache files default time to live (expiration) * @param int $max_size max total cache size * @param string $whitelist List of characters that are allowed in path names (used in a regex character class) */ public function __construct( $cache_dir, $ttl, $max_size, $whitelist = 'a-z0-9._-' ) { $this->root = Utils\trailingslashit( $cache_dir ); $this->ttl = (int) $ttl; $this->max_size = (int) $max_size; $this->whitelist = $whitelist; if ( ! $this->ensure_dir_exists( $this->root ) ) { $this->enabled = false; } } /** * Cache is enabled * * @return bool */ public function is_enabled() { return $this->enabled; } /** * Cache root * * @return string */ public function get_root() { return $this->root; } /** * Check if a file is in cache and return its filename * * @param string $key cache key * @param int $ttl time to live * @return bool|string filename or false */ public function has( $key, $ttl = null ) { if ( ! $this->enabled ) { return false; } $filename = $this->filename( $key ); if ( ! file_exists( $filename ) ) { return false; } // use ttl param or global ttl if ( null === $ttl ) { $ttl = $this->ttl; } elseif ( $this->ttl > 0 ) { $ttl = min( (int) $ttl, $this->ttl ); } else { $ttl = (int) $ttl; } // if ( $ttl > 0 && ( filemtime( $filename ) + $ttl ) < time() ) { if ( $this->ttl > 0 && $ttl >= $this->ttl ) { unlink( $filename ); } return false; } return $filename; } /** * Write to cache file * * @param string $key cache key * @param string $contents file contents * @return bool */ public function write( $key, $contents ) { $filename = $this->prepare_write( $key ); if ( $filename ) { return file_put_contents( $filename, $contents ) && touch( $filename ); } return false; } /** * Read from cache file * * @param string $key cache key * @param int $ttl time to live * @return bool|string file contents or false */ public function read( $key, $ttl = null ) { $filename = $this->has( $key, $ttl ); if ( $filename ) { return file_get_contents( $filename ); } return false; } /** * Copy a file into the cache * * @param string $key cache key * @param string $source source filename * @return bool */ public function import( $key, $source ) { $filename = $this->prepare_write( $key ); if ( $filename ) { return copy( $source, $filename ) && touch( $filename ); } return false; } /** * Copy a file out of the cache * * @param string $key cache key * @param string $target target filename * @param int $ttl time to live * @return bool */ public function export( $key, $target, $ttl = null ) { $filename = $this->has( $key, $ttl ); if ( $filename && $this->ensure_dir_exists( dirname( $target ) ) ) { return copy( $filename, $target ); } return false; } /** * Remove file from cache * * @param string $key cache key * @return bool */ public function remove( $key ) { if ( ! $this->enabled ) { return false; } $filename = $this->filename( $key ); if ( file_exists( $filename ) ) { return unlink( $filename ); } return false; } /** * Clean cache based on time to live and max size * * @return bool */ public function clean() { if ( ! $this->enabled ) { return false; } $ttl = $this->ttl; $max_size = $this->max_size; // unlink expired files if ( $ttl > 0 ) { try { $expire = new \DateTime(); } catch ( \Exception $e ) { \WP_CLI::error( $e->getMessage() ); } $expire->modify( '-' . $ttl . ' seconds' ); $finder = $this->get_finder()->date( 'until ' . $expire->format( 'Y-m-d H:i:s' ) ); foreach ( $finder as $file ) { unlink( $file->getRealPath() ); } } // unlink older files if max cache size is exceeded if ( $max_size > 0 ) { $files = array_reverse( iterator_to_array( $this->get_finder()->sortByAccessedTime()->getIterator() ) ); $total = 0; foreach ( $files as $file ) { if ( ( $total + $file->getSize() ) <= $max_size ) { $total += $file->getSize(); } else { unlink( $file->getRealPath() ); } } } return true; } /** * Remove all cached files. * * @return bool */ public function clear() { if ( ! $this->enabled ) { return false; } $finder = $this->get_finder(); foreach ( $finder as $file ) { unlink( $file->getRealPath() ); } return true; } /** * Remove all cached files except for the newest version of one. * * @return bool */ public function prune() { if ( ! $this->enabled ) { return false; } /** @var Finder $finder */ $finder = $this->get_finder()->sortByName(); $files_to_delete = array(); foreach ( $finder as $file ) { $pieces = explode( '-', $file->getBasename( $file->getExtension() ) ); $timestamp = end( $pieces ); // No way to compare versions, do nothing. if ( ! is_numeric( $timestamp ) ) { continue; } $basename_without_timestamp = str_replace( '-' . $timestamp, '', $file->getBasename() ); // There's a file with an older timestamp, delete it. if ( isset( $files_to_delete[ $basename_without_timestamp ] ) ) { unlink( $files_to_delete[ $basename_without_timestamp ] ); } $files_to_delete[ $basename_without_timestamp ] = $file->getRealPath(); } return true; } /** * Ensure directory exists * * @param string $dir directory * @return bool */ protected function ensure_dir_exists( $dir ) { if ( ! is_dir( $dir ) ) { // Disable the cache if a null device like /dev/null is being used. if ( preg_match( '{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $dir ) ) { return false; } if ( ! @mkdir( $dir, 0777, true ) ) { $error = error_get_last(); \WP_CLI::warning( sprintf( "Failed to create directory '%s': %s.", $dir, $error['message'] ) ); return false; } } return true; } /** * Prepare cache write * * @param string $key cache key * @return bool|string filename or false */ protected function prepare_write( $key ) { if ( ! $this->enabled ) { return false; } $filename = $this->filename( $key ); if ( ! $this->ensure_dir_exists( dirname( $filename ) ) ) { return false; } return $filename; } /** * Validate cache key * * @param string $key cache key * @return string relative filename */ protected function validate_key( $key ) { $url_parts = Utils\parse_url( $key, -1, false ); if ( array_key_exists( 'path', $url_parts ) && ! empty( $url_parts['scheme'] ) ) { // is url $parts = [ 'misc' ]; $parts[] = $url_parts['scheme'] . ( empty( $url_parts['host'] ) ? '' : '-' . $url_parts['host'] ) . ( empty( $url_parts['port'] ) ? '' : '-' . $url_parts['port'] ); $parts[] = substr( $url_parts['path'], 1 ) . ( empty( $url_parts['query'] ) ? '' : '-' . $url_parts['query'] ); } else { $key = str_replace( '\\', '/', $key ); $parts = explode( '/', ltrim( $key ) ); } $parts = preg_replace( "#[^{$this->whitelist}]#i", '-', $parts ); return implode( '/', $parts ); } /** * Filename from key * * @param string $key * @return string filename */ protected function filename( $key ) { return $this->root . $this->validate_key( $key ); } /** * Get a Finder that iterates in cache root only the files * * @return Finder */ protected function get_finder() { return Finder::create()->in( $this->root )->files(); } } get( $arg ); if ( ! $item ) { \WP_CLI::error( sprintf( $this->msg, $arg ) ); } return $item; } /** * @param array The raw CLI arguments * @return array The list of found items */ public function get_many( $args ) { $items = array(); foreach ( $args as $arg ) { $item = $this->get( $arg ); if ( $item ) { $items[] = $item; } else { \WP_CLI::warning( sprintf( $this->msg, $arg ) ); } } return $items; } } doc_comment = self::remove_decorations( $doc_comment ); } /** * Remove unused cruft from PHPdoc comment. * * @param string $comment PHPdoc comment. * @return string */ private static function remove_decorations( $comment ) { $comment = preg_replace( '|^/\*\*[\r\n]+|', '', $comment ); $comment = preg_replace( '|\n[\t ]*\*/$|', '', $comment ); $comment = preg_replace( '|^[\t ]*\* ?|m', '', $comment ); return $comment; } /** * Get the command's short description (e.g. summary). * * @return string */ public function get_shortdesc() { if ( ! preg_match( '|^([^@][^\n]+)\n*|', $this->doc_comment, $matches ) ) { return ''; } return $matches[1]; } /** * Get the command's full description * * @return string */ public function get_longdesc() { $shortdesc = $this->get_shortdesc(); if ( ! $shortdesc ) { return ''; } $longdesc = substr( $this->doc_comment, strlen( $shortdesc ) ); $lines = array(); foreach ( explode( "\n", $longdesc ) as $line ) { if ( 0 === strpos( $line, '@' ) ) { break; } $lines[] = $line; } $longdesc = trim( implode( "\n", $lines ) ); return $longdesc; } /** * Get the value for a given tag (e.g. "@alias" or "@subcommand") * * @param string $name Name for the tag, without '@' * @return string */ public function get_tag( $name ) { if ( preg_match( '|^@' . $name . '\s+([a-z-_0-9]+)|m', $this->doc_comment, $matches ) ) { return $matches[1]; } return ''; } /** * Get the command's synopsis. * * @return string */ public function get_synopsis() { if ( ! preg_match( '|^@synopsis\s+(.+)|m', $this->doc_comment, $matches ) ) { return ''; } return $matches[1]; } /** * Get the description for a given argument. * * @param string $name Argument's doc name. * @return string */ public function get_arg_desc( $name ) { if ( preg_match( "/\[?<{$name}>.+\n: (.+?)(\n|$)/", $this->doc_comment, $matches ) ) { return $matches[1]; } return ''; } /** * Get the arguments for a given argument. * * @param string $name Argument's doc name. * @return mixed|null */ public function get_arg_args( $name ) { return $this->get_arg_or_param_args( "/^\[?<{$name}>.*/" ); } /** * Get the description for a given parameter. * * @param string $key Parameter's key. * @return string */ public function get_param_desc( $key ) { if ( preg_match( "/\[?--{$key}=.+\n: (.+?)(\n|$)/", $this->doc_comment, $matches ) ) { return $matches[1]; } return ''; } /** * Get the arguments for a given parameter. * * @param string $key Parameter's key. * @return mixed|null */ public function get_param_args( $key ) { return $this->get_arg_or_param_args( "/^\[?--{$key}=.*/" ); } /** * Get the args for an arg or param * * @param string $regex Pattern to match against * @return array|null Interpreted YAML document, or null. */ private function get_arg_or_param_args( $regex ) { $bits = explode( "\n", $this->doc_comment ); $within_arg = false; $within_doc = false; $document = array(); foreach ( $bits as $bit ) { if ( preg_match( $regex, $bit ) ) { $within_arg = true; } if ( $within_arg && $within_doc && '---' === $bit ) { $within_doc = false; } if ( $within_arg && ! $within_doc && '---' === $bit ) { $within_doc = true; } if ( $within_doc ) { $document[] = $bit; } if ( $within_arg && '' === $bit ) { $within_arg = false; break; } } if ( $document ) { return Spyc::YAMLLoadString( implode( "\n", $document ) ); } return null; } } 'table', 'fields' => $fields, 'field' => null, ); foreach ( array( 'format', 'fields', 'field' ) as $key ) { if ( isset( $assoc_args[ $key ] ) ) { $format_args[ $key ] = $assoc_args[ $key ]; unset( $assoc_args[ $key ] ); } } if ( ! is_array( $format_args['fields'] ) ) { $format_args['fields'] = explode( ',', $format_args['fields'] ); } $format_args['fields'] = array_map( 'trim', $format_args['fields'] ); $this->args = $format_args; $this->prefix = $prefix; } /** * Magic getter for arguments. * * @param string $key * @return mixed */ public function __get( $key ) { return $this->args[ $key ]; } /** * Display multiple items according to the output arguments. * * @param array|\Iterator $items The items to display. * @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `format()` if items in the table are pre-colorized. Default false. */ public function display_items( $items, $ascii_pre_colorized = false ) { if ( $this->args['field'] ) { $this->show_single_field( $items, $this->args['field'] ); } else { if ( in_array( $this->args['format'], array( 'csv', 'json', 'table' ), true ) ) { $item = is_array( $items ) && ! empty( $items ) ? array_shift( $items ) : false; if ( $item && ! empty( $this->args['fields'] ) ) { foreach ( $this->args['fields'] as &$field ) { $field = $this->find_item_key( $item, $field ); } array_unshift( $items, $item ); } } if ( in_array( $this->args['format'], array( 'table', 'csv' ), true ) ) { if ( $items instanceof \Iterator ) { $items = \WP_CLI\Utils\iterator_map( $items, array( $this, 'transform_item_values_to_json' ) ); } else { $items = array_map( array( $this, 'transform_item_values_to_json' ), $items ); } } $this->format( $items, $ascii_pre_colorized ); } } /** * Display a single item according to the output arguments. * * @param mixed $item * @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_multiple_fields()` if the item in the table is pre-colorized. Default false. */ public function display_item( $item, $ascii_pre_colorized = false ) { if ( isset( $this->args['field'] ) ) { $item = (object) $item; $key = $this->find_item_key( $item, $this->args['field'] ); $value = $item->$key; if ( in_array( $this->args['format'], array( 'table', 'csv' ), true ) && ( is_object( $value ) || is_array( $value ) ) ) { $value = json_encode( $value ); } \WP_CLI::print_value( $value, array( 'format' => $this->args['format'], ) ); } else { $this->show_multiple_fields( $item, $this->args['format'], $ascii_pre_colorized ); } } /** * Format items according to arguments. * * @param array $items * @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if items in the table are pre-colorized. Default false. */ private function format( $items, $ascii_pre_colorized = false ) { $fields = $this->args['fields']; switch ( $this->args['format'] ) { case 'count': if ( ! is_array( $items ) ) { $items = iterator_to_array( $items ); } echo count( $items ); break; case 'ids': if ( ! is_array( $items ) ) { $items = iterator_to_array( $items ); } echo implode( ' ', $items ); break; case 'table': self::show_table( $items, $fields, $ascii_pre_colorized ); break; case 'csv': \WP_CLI\Utils\write_csv( STDOUT, $items, $fields ); break; case 'json': case 'yaml': $out = array(); foreach ( $items as $item ) { $out[] = \WP_CLI\Utils\pick_fields( $item, $fields ); } if ( 'json' === $this->args['format'] ) { if ( defined( 'JSON_PARTIAL_OUTPUT_ON_ERROR' ) ) { // phpcs:ignore PHPCompatibility.Constants.NewConstants.json_partial_output_on_errorFound echo json_encode( $out, JSON_PARTIAL_OUTPUT_ON_ERROR ); } else { echo json_encode( $out ); } } elseif ( 'yaml' === $this->args['format'] ) { echo Spyc::YAMLDump( $out, 2, 0 ); } break; default: \WP_CLI::error( 'Invalid format: ' . $this->args['format'] ); } } /** * Show a single field from a list of items. * * @param array Array of objects to show fields from * @param string The field to show */ private function show_single_field( $items, $field ) { $key = null; $values = array(); foreach ( $items as $item ) { $item = (object) $item; if ( null === $key ) { $key = $this->find_item_key( $item, $field ); } if ( 'json' === $this->args['format'] ) { $values[] = $item->$key; } else { \WP_CLI::print_value( $item->$key, array( 'format' => $this->args['format'], ) ); } } if ( 'json' === $this->args['format'] ) { echo json_encode( $values ); } } /** * Find an object's key. * If $prefix is set, a key with that prefix will be prioritized. * * @param object $item * @param string $field * @return string $key */ private function find_item_key( $item, $field ) { foreach ( array( $field, $this->prefix . '_' . $field ) as $maybe_key ) { if ( ( is_object( $item ) && ( property_exists( $item, $maybe_key ) || isset( $item->$maybe_key ) ) ) || ( is_array( $item ) && array_key_exists( $maybe_key, $item ) ) ) { $key = $maybe_key; break; } } if ( ! isset( $key ) ) { \WP_CLI::error( "Invalid field: $field." ); } return $key; } /** * Show multiple fields of an object. * * @param object|array $data Data to display * @param string $format Format to display the data in * @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if the item in the table is pre-colorized. Default false. */ private function show_multiple_fields( $data, $format, $ascii_pre_colorized = false ) { $true_fields = array(); foreach ( $this->args['fields'] as $field ) { $true_fields[] = $this->find_item_key( $data, $field ); } foreach ( $data as $key => $value ) { if ( ! in_array( $key, $true_fields, true ) ) { if ( is_array( $data ) ) { unset( $data[ $key ] ); } elseif ( is_object( $data ) ) { unset( $data->$key ); } } } switch ( $format ) { case 'table': case 'csv': $rows = $this->assoc_array_to_rows( $data ); $fields = array( 'Field', 'Value' ); if ( 'table' === $format ) { self::show_table( $rows, $fields, $ascii_pre_colorized ); } elseif ( 'csv' === $format ) { \WP_CLI\Utils\write_csv( STDOUT, $rows, $fields ); } break; case 'yaml': case 'json': \WP_CLI::print_value( $data, array( 'format' => $format, ) ); break; default: \WP_CLI::error( 'Invalid format: ' . $format ); break; } } /** * Show items in a \cli\Table. * * @param array $items * @param array $fields * @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `Table::setAsciiPreColorized()` if items in the table are pre-colorized. Default false. */ private static function show_table( $items, $fields, $ascii_pre_colorized = false ) { $table = new \cli\Table(); $enabled = \cli\Colors::shouldColorize(); if ( $enabled ) { \cli\Colors::disable( true ); } $table->setAsciiPreColorized( $ascii_pre_colorized ); $table->setHeaders( $fields ); foreach ( $items as $item ) { $table->addRow( array_values( \WP_CLI\Utils\pick_fields( $item, $fields ) ) ); } foreach ( $table->getDisplayLines() as $line ) { \WP_CLI::line( $line ); } if ( $enabled ) { \cli\Colors::enable( true ); } } /** * Format an associative array as a table. * * @param array $fields Fields and values to format * @return array $rows */ private function assoc_array_to_rows( $fields ) { $rows = array(); foreach ( $fields as $field => $value ) { if ( ! is_string( $value ) ) { $value = json_encode( $value ); } $rows[] = (object) array( 'Field' => $field, 'Value' => $value, ); } return $rows; } /** * Transforms objects and arrays to JSON as necessary * * @param mixed $item * @return mixed */ public function transform_item_values_to_json( $item ) { foreach ( $this->args['fields'] as $field ) { $true_field = $this->find_item_key( $item, $field ); $value = is_object( $item ) ? $item->$true_field : $item[ $true_field ]; if ( is_array( $value ) || is_object( $value ) ) { if ( is_object( $item ) ) { $item->$true_field = json_encode( $value ); } elseif ( is_array( $item ) ) { $item[ $true_field ] = json_encode( $value ); } } } return $item; } } $value ) { $this->$key = $value; } } /** * Return properties of executed command as a string. * * @return string */ public function __toString() { $out = "$ $this->command\n"; $out .= "$this->stdout\n$this->stderr"; $out .= "cwd: $this->cwd\n"; $out .= "run time: $this->run_time\n"; $out .= "exit status: $this->return_code"; return $out; } } 'pre_install', PackageEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { $operation_message = $event->getOperation()->__toString(); WP_CLI::log( ' - ' . $operation_message ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT: case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( ' - Warning: %s', $composer_error ) ); } } } } process_feedback( $string, $args ); } } process_feedback( $string, $args ); } } = 50600 ) { require_once __DIR__ . '/Min_PHP_5_6/FeedbackMethodTrait.php'; trait FeedbackMethodTrait { use Min_PHP_5_6\FeedbackMethodTrait; } return; } require_once __DIR__ . '/Min_PHP_5_4/FeedbackMethodTrait.php'; trait FeedbackMethodTrait { use Min_PHP_5_4\FeedbackMethodTrait; } in_color = $in_color; } /** * Write an informational message to STDOUT. * * @param string $message Message to write. */ public function info( $message ) { $this->write( STDOUT, $message . "\n" ); } /** * Write a success message, prefixed with "Success: ". * * @param string $message Message to write. */ public function success( $message ) { $this->_line( $message, 'Success', '%G' ); } /** * Write a warning message to STDERR, prefixed with "Warning: ". * * @param string $message Message to write. */ public function warning( $message ) { $this->_line( $message, 'Warning', '%C', STDERR ); } /** * Write an message to STDERR, prefixed with "Error: ". * * @param string $message Message to write. */ public function error( $message ) { $this->_line( $message, 'Error', '%R', STDERR ); } /** * Similar to error( $message ), but outputs $message in a red box * * @param array $message Message to write. */ public function error_multi_line( $message_lines ) { // convert tabs to four spaces, as some shells will output the tabs as variable-length $message_lines = array_map( function( $line ) { return str_replace( "\t", ' ', $line ); }, $message_lines ); $longest = max( array_map( 'strlen', $message_lines ) ); // write an empty line before the message $empty_line = \cli\Colors::colorize( '%w%1 ' . str_repeat( ' ', $longest ) . ' %n' ); $this->write( STDERR, "\n\t$empty_line\n" ); foreach ( $message_lines as $line ) { $padding = str_repeat( ' ', $longest - strlen( $line ) ); $line = \cli\Colors::colorize( "%w%1 $line $padding%n" ); $this->write( STDERR, "\t$line\n" ); } // write an empty line after the message $this->write( STDERR, "\t$empty_line\n\n" ); } } write( STDERR, \WP_CLI::colorize( "%RError:%n $message\n" ) ); } /** * Similar to error( $message ), but outputs $message in a red box * * @param array $message Message to write. */ public function error_multi_line( $message_lines ) { $message = implode( "\n", $message_lines ); $this->write( STDERR, \WP_CLI::colorize( "%RError:%n\n$message\n" ) ); $this->write( STDERR, \WP_CLI::colorize( "%R---------%n\n\n" ) ); } } get_runner()->config['debug']; if ( ! $debug ) { return; } if ( true !== $debug && $group !== $debug ) { return; } $time = round( microtime( true ) - ( defined( 'WP_CLI_START_MICROTIME' ) ? WP_CLI_START_MICROTIME : $start_time ), 3 ); $prefix = 'Debug'; if ( $group && true === $debug ) { $prefix = 'Debug (' . $group . ')'; } $this->_line( "$message ({$time}s)", $prefix, '%B', STDERR ); } /** * Write a string to a resource. * * @param resource $handle Commonly STDOUT or STDERR. * @param string $str Message to write. */ protected function write( $handle, $str ) { fwrite( $handle, $str ); } /** * Output one line of message to a resource. * * @param string $message Message to write. * @param string $label Prefix message with a label. * @param string $color Colorize label with a given color. * @param resource $handle Resource to write to. Defaults to STDOUT. */ protected function _line( $message, $label, $color, $handle = STDOUT ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Used in third party extensions. if ( class_exists( 'cli\Colors' ) ) { $label = \cli\Colors::colorize( "$color$label:%n", $this->in_color ); } else { $label = "$label:"; } $this->write( $handle, "$label $message\n" ); } } write( STDERR, \WP_CLI::colorize( "%RError:%n\n$message\n" ) ); $this->write( STDERR, \WP_CLI::colorize( "%R---------%n\n\n" ) ); } /** * Write a string to a resource. * * @param resource $handle Commonly STDOUT or STDERR. * @param string $str Message to write. */ protected function write( $handle, $str ) { switch ( $handle ) { case STDOUT: $this->stdout .= $str; break; case STDERR: $this->stderr .= $str; break; } } /** * Starts output buffering, using a callback to capture output from `echo`, `print`, `printf` (which write to the output buffer 'php://output' rather than STDOUT). */ public function ob_start() { // To ensure sequential output, give a chunk size of 1 (or 2 if PHP < 5.4 as 1 was a special value meaning a 4KB chunk) to `ob_start()`, so that each write gets flushed immediately. ob_start( array( $this, 'ob_start_callback' ), version_compare( PHP_VERSION, '5.4.0', '<' ) ? 2 : 1 ); } /** * Callback for `ob_start()`. * * @param string $str String to write. * @return string Returns zero-length string so nothing gets written to the output buffer. */ public function ob_start_callback( $str ) { $this->write( STDOUT, $str ); return ''; } /** * To match `ob_start() above. Does an `ob_end_flush()`. */ public function ob_end() { ob_end_flush(); } } upgrader->strings[ $error ] ) ) { $error = $this->upgrader->strings[ $error ]; } // TODO: show all errors, not just the first one WP_CLI::warning( $error ); } /** * Process the feedback collected through the compat indirection. * * @param string $string String to use as feedback message. * @param array $args Array of additional arguments to process. */ public function process_feedback( $string, $args ) { if ( 'parent_theme_prepare_install' === $string ) { WP_CLI::get_http_cache_manager()->whitelist_package( $this->api->download_link, 'theme', $this->api->slug, $this->api->version ); } if ( isset( $this->upgrader->strings[ $string ] ) ) { $string = $this->upgrader->strings[ $string ]; } if ( ! empty( $args ) && strpos( $string, '%' ) !== false ) { $string = vsprintf( $string, $args ); } if ( empty( $string ) ) { return; } $string = str_replace( '…', '...', Utils\strip_tags( $string ) ); $string = html_entity_decode( $string, ENT_QUOTES, get_bloginfo( 'charset' ) ); WP_CLI::log( $string ); } } words = explode( ' ', $line ); // first word is always `wp` array_shift( $this->words ); // last word is either empty or an incomplete subcommand $this->cur_word = end( $this->words ); if ( '' !== $this->cur_word && ! preg_match( '/^\-/', $this->cur_word ) ) { array_pop( $this->words ); } $is_alias = false; $is_help = false; if ( ! empty( $this->words[0] ) && preg_match( '/^@/', $this->words[0] ) ) { array_shift( $this->words ); // `wp @al` is false, but `wp @all ` is true. if ( count( $this->words ) ) { $is_alias = true; } } elseif ( ! empty( $this->words[0] ) && 'help' === $this->words[0] ) { array_shift( $this->words ); $is_help = true; } $r = $this->get_command( $this->words ); if ( ! is_array( $r ) ) { return; } list( $command, $args, $assoc_args ) = $r; $spec = SynopsisParser::parse( $command->get_synopsis() ); foreach ( $spec as $arg ) { if ( 'positional' === $arg['type'] && 'file' === $arg['name'] ) { $this->add( ' ' ); return; } } if ( $command->can_have_subcommands() ) { // add completion when command is `wp` and alias isn't set. if ( 'wp' === $command->get_name() && false === $is_alias && false === $is_help ) { $aliases = \WP_CLI::get_configurator()->get_aliases(); foreach ( $aliases as $name => $_ ) { $this->add( "$name " ); } } foreach ( $command->get_subcommands() as $name => $_ ) { $this->add( "$name " ); } } else { foreach ( $spec as $arg ) { if ( in_array( $arg['type'], array( 'flag', 'assoc' ), true ) ) { if ( isset( $assoc_args[ $arg['name'] ] ) ) { continue; } $opt = "--{$arg['name']}"; if ( 'flag' === $arg['type'] ) { $opt .= ' '; } elseif ( ! $arg['value']['optional'] ) { $opt .= '='; } $this->add( $opt ); } } foreach ( $this->get_global_parameters() as $param => $runtime ) { if ( isset( $assoc_args[ $param ] ) ) { continue; } $opt = "--{$param}"; if ( '' === $runtime || ! is_string( $runtime ) ) { $opt .= ' '; } else { $opt .= '='; } $this->add( $opt ); } } } private function get_command( $words ) { $positional_args = array(); $assoc_args = array(); foreach ( $words as $arg ) { if ( preg_match( '|^--([^=]+)=?|', $arg, $matches ) ) { $assoc_args[ $matches[1] ] = true; } else { $positional_args[] = $arg; } } $r = \WP_CLI::get_runner()->find_command_to_run( $positional_args ); if ( ! is_array( $r ) && array_pop( $positional_args ) === $this->cur_word ) { $r = \WP_CLI::get_runner()->find_command_to_run( $positional_args ); } if ( ! is_array( $r ) ) { return $r; } list( $command, $args ) = $r; return array( $command, $args, $assoc_args ); } private function get_global_parameters() { $params = array(); foreach ( \WP_CLI::get_configurator()->get_spec() as $key => $details ) { if ( false === $details['runtime'] ) { continue; } if ( isset( $details['deprecated'] ) ) { continue; } if ( isset( $details['hidden'] ) ) { continue; } $params[ $key ] = $details['runtime']; // Add additional option like `--[no-]color`. if ( true === $details['runtime'] ) { $params[ 'no-' . $key ] = ''; } } return $params; } private function add( $opt ) { if ( '' !== $this->cur_word ) { if ( 0 !== strpos( $opt, $this->cur_word ) ) { return; } } $this->opts[] = $opt; } public function render() { foreach ( $this->opts as $opt ) { \WP_CLI::line( $opt ); } } } unregister(); } /** * Registers the autoload callback with the SPL autoload system. */ public function register() { spl_autoload_register( array( $this, 'autoload' ) ); } /** * Unregisters the autoload callback with the SPL autoload system. */ public function unregister() { spl_autoload_unregister( array( $this, 'autoload' ) ); } /** * Add a specific namespace structure with our custom autoloader. * * @param string $root Root namespace name. * @param string $base_dir Directory containing the class files. * @param string $prefix Prefix to be added before the class. * @param string $suffix Suffix to be added after the class. * @param boolean $lowercase Whether the class should be changed to * lowercase. * @param boolean $underscores Whether the underscores should be changed to * hyphens. * * @return self */ public function add_namespace( $root, $base_dir, $prefix = '', $suffix = '.php', $lowercase = false, $underscores = false ) { $this->namespaces[] = array( 'root' => $this->normalize_root( (string) $root ), 'base_dir' => $this->add_trailing_slash( (string) $base_dir ), 'prefix' => (string) $prefix, 'suffix' => (string) $suffix, 'lowercase' => (bool) $lowercase, 'underscores' => (bool) $underscores, ); return $this; } /** * The autoload function that gets registered with the SPL Autoloader * system. * * @param string $class The class that got requested by the spl_autoloader. */ public function autoload( $class ) { // Iterate over namespaces to find a match. foreach ( $this->namespaces as $namespace ) { // Move on if the object does not belong to the current namespace. if ( 0 !== strpos( $class, $namespace['root'] ) ) { continue; } // Remove namespace root level to correspond with root filesystem, and // replace the namespace separator "\" by the system-dependent directory separator. $filename = str_replace( array( $namespace['root'], '\\' ), array( '', DIRECTORY_SEPARATOR ), $class ); // Remove a leading backslash from the class name. $filename = $this->remove_leading_backslash( $filename ); // Change to lower case if requested. if ( $namespace['lowercase'] ) { $filename = strtolower( $filename ); } // Change underscores into hyphens if requested. if ( $namespace['underscores'] ) { $filename = str_replace( '_', '-', $filename ); } // Add base_dir, prefix and suffix. $filepath = $namespace['base_dir'] . $namespace['prefix'] . $filename . $namespace['suffix']; // Throw an exception if the file does not exist or is not readable. if ( is_readable( $filepath ) ) { require_once $filepath; } } } /** * Normalize a namespace root. * * @param string $root Namespace root that needs to be normalized. * * @return string Normalized namespace root. */ protected function normalize_root( $root ) { $root = $this->remove_leading_backslash( $root ); return $this->add_trailing_backslash( $root ); } /** * Remove a leading backslash from a string. * * @param string $string String to remove the leading backslash from. * * @return string Modified string. */ protected function remove_leading_backslash( $string ) { return ltrim( $string, '\\' ); } /** * Make sure a string ends with a trailing backslash. * * @param string $string String to check the trailing backslash of. * * @return string Modified string. */ protected function add_trailing_backslash( $string ) { return rtrim( $string, '\\' ) . '\\'; } /** * Make sure a string ends with a trailing slash. * * @param string $string String to check the trailing slash of. * * @return string Modified string. */ protected function add_trailing_slash( $string ) { return rtrim( $string, '/\\' ) . '/'; } } abort = true; $this->reason = (string) $reason; } /** * Check whether the command addition was aborted. * * @return bool */ public function was_aborted() { return $this->abort; } /** * Get the reason as to why the addition was aborted. * * @return string */ public function get_reason() { return $this->reason; } } get_subcommands(); $i = 0; $count = 0; foreach ( $methods as $name => $subcommand ) { $prefix = ( 0 === $i ) ? 'usage: ' : ' or: '; $i++; if ( \WP_CLI::get_runner()->is_command_disabled( $subcommand ) ) { continue; } \WP_CLI::line( $subcommand->get_usage( $prefix ) ); $count++; } $cmd_name = implode( ' ', array_slice( get_path( $this ), 1 ) ); $message = $count > 0 ? "See 'wp help $cmd_name ' for more information on a specific command." : "The namespace $cmd_name does not contain any usable commands in the current context."; \WP_CLI::line(); \WP_CLI::line( $message ); } } parent = $parent; $this->name = $name; $this->shortdesc = $docparser->get_shortdesc(); $this->longdesc = $docparser->get_longdesc(); $this->docparser = $docparser; $when_to_invoke = $docparser->get_tag( 'when' ); if ( $when_to_invoke ) { \WP_CLI::get_runner()->register_early_invoke( $when_to_invoke, $this ); } } /** * Get the parent composite (or root) command * * @return mixed */ public function get_parent() { return $this->parent; } /** * Add a named subcommand to this composite command's * set of contained subcommands. * * @param string $name Represents how subcommand should be invoked * @param Subcommand|CompositeCommand */ public function add_subcommand( $name, $command ) { $this->subcommands[ $name ] = $command; } /** * Remove a named subcommand from this composite command's set of contained * subcommands * * @param string $name Represents how subcommand should be invoked */ public function remove_subcommand( $name ) { if ( isset( $this->subcommands[ $name ] ) ) { unset( $this->subcommands[ $name ] ); } } /** * Composite commands always contain subcommands. * * @return true */ public function can_have_subcommands() { return true; } /** * Get the subcommands contained by this composite * command. * * @return array */ public function get_subcommands() { ksort( $this->subcommands ); return $this->subcommands; } /** * Get the name of this composite command. * * @return string */ public function get_name() { return $this->name; } /** * Get the short description for this composite * command. * * @return string */ public function get_shortdesc() { return $this->shortdesc; } /** * Set the short description for this composite command. * * @param string */ public function set_shortdesc( $shortdesc ) { $this->shortdesc = Utils\normalize_eols( $shortdesc ); } /** * Get the long description for this composite * command. * * @return string */ public function get_longdesc() { return $this->longdesc . $this->get_global_params(); } /** * Set the long description for this composite command * * @param string */ public function set_longdesc( $longdesc ) { $this->longdesc = Utils\normalize_eols( $longdesc ); } /** * Get the synopsis for this composite command. * As a collection of subcommands, the composite * command is only intended to invoke those * subcommands. * * @return string */ public function get_synopsis() { return ''; } /** * Get the usage for this composite command. * * @return string */ public function get_usage( $prefix ) { return sprintf( '%s%s %s', $prefix, implode( ' ', get_path( $this ) ), $this->get_synopsis() ); } /** * Show the usage for all subcommands contained * by the composite command. */ public function show_usage() { $methods = $this->get_subcommands(); $i = 0; foreach ( $methods as $name => $subcommand ) { $prefix = ( 0 === $i ) ? 'usage: ' : ' or: '; $i++; if ( \WP_CLI::get_runner()->is_command_disabled( $subcommand ) ) { continue; } \WP_CLI::line( $subcommand->get_usage( $prefix ) ); } $cmd_name = implode( ' ', array_slice( get_path( $this ), 1 ) ); \WP_CLI::line(); \WP_CLI::line( "See 'wp help $cmd_name ' for more information on a specific command." ); } /** * When a composite command is invoked, it shows usage * docs for its subcommands. * * @param array $args * @param array $assoc_args * @param array $extra_args */ public function invoke( $args, $assoc_args, $extra_args ) { $this->show_usage(); } /** * Given supplied arguments, find a contained * subcommand * * @param array $args * @return \WP_CLI\Dispatcher\Subcommand|false */ public function find_subcommand( &$args ) { $name = array_shift( $args ); $subcommands = $this->get_subcommands(); if ( ! isset( $subcommands[ $name ] ) ) { $aliases = self::get_aliases( $subcommands ); if ( isset( $aliases[ $name ] ) ) { $name = $aliases[ $name ]; } } if ( ! isset( $subcommands[ $name ] ) ) { return false; } return $subcommands[ $name ]; } /** * Get any registered aliases for this composite command's * subcommands. * * @param array $subcommands * @return array */ private static function get_aliases( $subcommands ) { $aliases = array(); foreach ( $subcommands as $name => $subcommand ) { $alias = $subcommand->get_alias(); if ( $alias ) { $aliases[ $alias ] = $name; } } return $aliases; } /** * Composite commands can only be known by one name. * * @return false */ public function get_alias() { return false; } /*** * Get the list of global parameters * * @param string $root_command whether to include or not root command specific description * @return string */ protected function get_global_params( $root_command = false ) { $binding = array(); $binding['root_command'] = $root_command; if ( ! $this->can_have_subcommands() || ( is_object( $this->parent ) && get_class( $this->parent ) === 'WP_CLI\Dispatcher\CompositeCommand' ) ) { $binding['is_subcommand'] = true; } foreach ( \WP_CLI::get_configurator()->get_spec() as $key => $details ) { if ( false === $details['runtime'] ) { continue; } if ( isset( $details['deprecated'] ) ) { continue; } if ( isset( $details['hidden'] ) ) { continue; } if ( true === $details['runtime'] ) { $synopsis = "--[no-]$key"; } else { $synopsis = "--$key" . $details['runtime']; } $binding['parameters'][] = array( 'synopsis' => $synopsis, 'desc' => $details['desc'], ); } if ( $this->get_subcommands() ) { $binding['has_subcommands'] = true; } return Utils\mustache_render( 'man-params.mustache', $binding ); } } getMethod( $callable[1] ) ); } else { $reflection = new ReflectionClass( $callable ); if ( $reflection->isSubclassOf( '\WP_CLI\Dispatcher\CommandNamespace' ) ) { $command = self::create_namespace( $parent, $name, $callable ); } elseif ( $reflection->hasMethod( '__invoke' ) ) { $class = is_object( $callable ) ? $callable : $reflection->name; $command = self::create_subcommand( $parent, $name, array( $class, '__invoke' ), $reflection->getMethod( '__invoke' ) ); } else { $command = self::create_composite_command( $parent, $name, $callable ); } } return $command; } /** * Clear the file contents cache. */ public static function clear_file_contents_cache() { self::$file_contents = array(); } /** * Create a new Subcommand instance. * * @param mixed $parent The new command's parent Composite command * @param string|bool $name Represents how the command should be invoked. * If false, will be determined from the documented subject, represented by `$reflection`. * @param mixed $callable A callable function or closure, or class name and method * @param object $reflection Reflection instance, for doc parsing * @param string $class A subclass of WP_CLI_Command * @param string $method Class method to be called upon invocation. */ private static function create_subcommand( $parent, $name, $callable, $reflection ) { $doc_comment = self::get_doc_comment( $reflection ); $docparser = new \WP_CLI\DocParser( $doc_comment ); if ( is_array( $callable ) ) { if ( ! $name ) { $name = $docparser->get_tag( 'subcommand' ); } if ( ! $name ) { $name = $reflection->name; } } if ( ! $doc_comment ) { \WP_CLI::debug( null === $doc_comment ? "Failed to get doc comment for {$name}." : "No doc comment for {$name}.", 'commandfactory' ); } $when_invoked = function ( $args, $assoc_args ) use ( $callable ) { if ( is_array( $callable ) ) { $callable[0] = is_object( $callable[0] ) ? $callable[0] : new $callable[0](); call_user_func( array( $callable[0], $callable[1] ), $args, $assoc_args ); } else { call_user_func( $callable, $args, $assoc_args ); } }; return new Subcommand( $parent, $name, $docparser, $when_invoked ); } /** * Create a new Composite command instance. * * @param mixed $parent The new command's parent Root or Composite command * @param string $name Represents how the command should be invoked * @param mixed $callable */ private static function create_composite_command( $parent, $name, $callable ) { $reflection = new ReflectionClass( $callable ); $doc_comment = self::get_doc_comment( $reflection ); if ( ! $doc_comment ) { \WP_CLI::debug( null === $doc_comment ? "Failed to get doc comment for {$name}." : "No doc comment for {$name}.", 'commandfactory' ); } $docparser = new \WP_CLI\DocParser( $doc_comment ); $container = new CompositeCommand( $parent, $name, $docparser ); foreach ( $reflection->getMethods() as $method ) { if ( ! self::is_good_method( $method ) ) { continue; } $class = is_object( $callable ) ? $callable : $reflection->name; $subcommand = self::create_subcommand( $container, false, array( $class, $method->name ), $method ); $subcommand_name = $subcommand->get_name(); $container->add_subcommand( $subcommand_name, $subcommand ); } return $container; } /** * Create a new command namespace instance. * * @param mixed $parent The new namespace's parent Root or Composite command. * @param string $name Represents how the command should be invoked * @param mixed $callable */ private static function create_namespace( $parent, $name, $callable ) { $reflection = new ReflectionClass( $callable ); $doc_comment = self::get_doc_comment( $reflection ); if ( ! $doc_comment ) { \WP_CLI::debug( null === $doc_comment ? "Failed to get doc comment for {$name}." : "No doc comment for {$name}.", 'commandfactory' ); } $docparser = new \WP_CLI\DocParser( $doc_comment ); return new CommandNamespace( $parent, $name, $docparser ); } /** * Check whether a method is actually callable. * * @param ReflectionMethod $method * @return bool */ private static function is_good_method( $method ) { return $method->isPublic() && ! $method->isStatic() && 0 !== strpos( $method->getName(), '__' ); } /** * Gets the document comment. Caters for PHP directive `opcache.save comments` being disabled. * * @param ReflectionMethod|ReflectionClass|ReflectionFunction $reflection Reflection instance. * @return string|false|null Doc comment string if any, false if none (same as `Reflection*::getDocComment()`), null if error. */ private static function get_doc_comment( $reflection ) { $doc_comment = $reflection->getDocComment(); if ( false !== $doc_comment || ! ( ini_get( 'opcache.enable_cli' ) && ! ini_get( 'opcache.save_comments' ) ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.NewIniDirectives // Either have doc comment, or no doc comment and save comments enabled - standard situation. if ( ! getenv( 'WP_CLI_TEST_GET_DOC_COMMENT' ) ) { return $doc_comment; } } $filename = $reflection->getFileName(); if ( isset( self::$file_contents[ $filename ] ) ) { $contents = self::$file_contents[ $filename ]; } elseif ( is_readable( $filename ) ) { $contents = file_get_contents( $filename ); if ( is_string( $contents ) && '' !== $contents ) { $contents = explode( "\n", $contents ); self::$file_contents[ $filename ] = $contents; } } if ( ! empty( $contents ) ) { return self::extract_last_doc_comment( implode( "\n", array_slice( $contents, 0, $reflection->getStartLine() ) ) ); } \WP_CLI::debug( "Could not read contents for filename '{$filename}'.", 'commandfactory' ); return null; } /** * Returns the last doc comment if any in `$content`. * * @param string $content The content, which should end at the class or function declaration. * @return string|bool The last doc comment if any, or false if none. */ private static function extract_last_doc_comment( $content ) { $content = trim( $content ); $comment_end_pos = strrpos( $content, '*/' ); if ( false === $comment_end_pos ) { return false; } // Make sure comment end belongs to this class/function. if ( preg_match_all( '/(?:^|[\s;}])(?:class|function)\s+/', substr( $content, $comment_end_pos + 2 ), $dummy /*needed for PHP 5.3*/ ) > 1 ) { return false; } $content = substr( $content, 0, $comment_end_pos + 2 ); $comment_start_pos = strrpos( $content, '/**' ); if ( false === $comment_start_pos || ( $comment_start_pos + 2 ) === $comment_end_pos ) { return false; } // Make sure comment start belongs to this comment end. $comment_end2_pos = strpos( substr( $content, $comment_start_pos ), '*/' ); if ( false !== $comment_end2_pos && ( $comment_start_pos + $comment_end2_pos ) < $comment_end_pos ) { return false; } // Allow for '/**' within doc comment. $subcontent = substr( $content, 0, $comment_start_pos ); while ( false !== ( $comment_start2_pos = strrpos( $subcontent, '/**' ) ) && false === strpos( $subcontent, '*/', $comment_start2_pos ) ) { $comment_start_pos = $comment_start2_pos; $subcontent = substr( $subcontent, 0, $comment_start_pos ); } return substr( $content, $comment_start_pos, $comment_end_pos + 2 ); } } parent = false; $this->name = 'wp'; $this->shortdesc = 'Manage WordPress through the command-line.'; } /** * Get the human-readable long description. * * @return string */ public function get_longdesc() { return $this->get_global_params( true ); } /** * Find a subcommand registered on the root * command. * * @param array $args * @return \WP_CLI\Dispatcher\Subcommand|false */ public function find_subcommand( &$args ) { $command = array_shift( $args ); Utils\load_command( $command ); if ( ! isset( $this->subcommands[ $command ] ) ) { return false; } return $this->subcommands[ $command ]; } } when_invoked = $when_invoked; $this->alias = $docparser->get_tag( 'alias' ); $this->synopsis = $docparser->get_synopsis(); if ( ! $this->synopsis && $this->longdesc ) { $this->synopsis = self::extract_synopsis( $this->longdesc ); } } /** * Extract the synopsis from PHPdoc string. * * @param string $longdesc Command docs via PHPdoc * @return string */ private static function extract_synopsis( $longdesc ) { preg_match_all( '/(.+?)[\r\n]+:/', $longdesc, $matches ); return implode( ' ', $matches[1] ); } /** * Subcommands can't have subcommands because they * represent code to be executed. * * @return bool */ public function can_have_subcommands() { return false; } /** * Get the synopsis string for this subcommand. * A synopsis defines what runtime arguments are * expected, useful to humans and argument validation. * * @return string */ public function get_synopsis() { return $this->synopsis; } /** * Set the synopsis string for this subcommand. * * @param string */ public function set_synopsis( $synopsis ) { $this->synopsis = $synopsis; } /** * If an alias is set, grant access to it. * Aliases permit subcommands to be instantiated * with a secondary identity. * * @return string */ public function get_alias() { return $this->alias; } /** * Print the usage details to the end user. * * @param string $prefix */ public function show_usage( $prefix = 'usage: ' ) { \WP_CLI::line( $this->get_usage( $prefix ) ); } /** * Get the usage of the subcommand as a formatted string. * * @param string $prefix * @return string */ public function get_usage( $prefix ) { return sprintf( '%s%s %s', $prefix, implode( ' ', get_path( $this ) ), $this->get_synopsis() ); } /** * Wrapper for CLI Tools' prompt() method. * * @param string $question * @param string $default * @return string|false */ private function prompt( $question, $default ) { $question .= ': '; if ( function_exists( 'readline' ) ) { return readline( $question ); } echo $question; $ret = stream_get_line( STDIN, 1024, "\n" ); if ( Utils\is_windows() && "\r" === substr( $ret, -1 ) ) { $ret = substr( $ret, 0, -1 ); } return $ret; } /** * Interactively prompt the user for input * based on defined synopsis and passed arguments. * * @param array $args * @param array $assoc_args * @return array */ private function prompt_args( $args, $assoc_args ) { $synopsis = $this->get_synopsis(); if ( ! $synopsis ) { return array( $args, $assoc_args ); } // To skip the already provided positional arguments, we need to count // how many we had already received. $arg_index = 0; $spec = array_filter( \WP_CLI\SynopsisParser::parse( $synopsis ), function( $spec_arg ) use ( $args, $assoc_args, &$arg_index ) { switch ( $spec_arg['type'] ) { case 'positional': // Only prompt for the positional arguments that are not // yet provided, based purely on number. return $arg_index++ >= count( $args ); case 'generic': // Always prompt for generic arguments. return true; case 'assoc': case 'flag': default: // Prompt for the specific flags that were not provided // yet, based on name. return ! isset( $assoc_args[ $spec_arg['name'] ] ); } } ); $spec = array_values( $spec ); $prompt_args = WP_CLI::get_config( 'prompt' ); if ( true !== $prompt_args ) { $prompt_args = explode( ',', $prompt_args ); } // 'positional' arguments are positional (aka zero-indexed) // so $args needs to be reset before prompting for new arguments $args = array(); foreach ( $spec as $key => $spec_arg ) { // When prompting for specific arguments (e.g. --prompt=user_pass), // ignore all arguments that don't match. if ( is_array( $prompt_args ) ) { if ( 'assoc' !== $spec_arg['type'] ) { continue; } if ( ! in_array( $spec_arg['name'], $prompt_args, true ) ) { continue; } } $current_prompt = ( $key + 1 ) . '/' . count( $spec ) . ' '; $default = $spec_arg['optional'] ? '' : false; // 'generic' permits arbitrary key=value (e.g. [--=] ) if ( 'generic' === $spec_arg['type'] ) { list( $key_token, $value_token ) = explode( '=', $spec_arg['token'] ); $repeat = false; do { if ( ! $repeat ) { $key_prompt = $current_prompt . $key_token; } else { $key_prompt = str_repeat( ' ', strlen( $current_prompt ) ) . $key_token; } $key = $this->prompt( $key_prompt, $default ); if ( false === $key ) { return array( $args, $assoc_args ); } if ( $key ) { $key_prompt_count = strlen( $key_prompt ) - strlen( $value_token ) - 1; $value_prompt = str_repeat( ' ', $key_prompt_count ) . '=' . $value_token; $value = $this->prompt( $value_prompt, $default ); if ( false === $value ) { return array( $args, $assoc_args ); } $assoc_args[ $key ] = $value; $repeat = true; } else { $repeat = false; } } while ( $repeat ); } else { $prompt = $current_prompt . $spec_arg['token']; if ( 'flag' === $spec_arg['type'] ) { $prompt .= ' (Y/n)'; } $response = $this->prompt( $prompt, $default ); if ( false === $response ) { return array( $args, $assoc_args ); } if ( $response ) { switch ( $spec_arg['type'] ) { case 'positional': if ( $spec_arg['repeating'] ) { $response = explode( ' ', $response ); } else { $response = array( $response ); } $args = array_merge( $args, $response ); break; case 'assoc': $assoc_args[ $spec_arg['name'] ] = $response; break; case 'flag': if ( 'Y' === strtoupper( $response ) ) { $assoc_args[ $spec_arg['name'] ] = true; } break; } } } } return array( $args, $assoc_args ); } /** * Validate the supplied arguments to the command. * Throws warnings or errors if arguments are missing * or invalid. * * @param array $args * @param array $assoc_args * @param array $extra_args * @return array list of invalid $assoc_args keys to unset */ private function validate_args( $args, $assoc_args, $extra_args ) { $synopsis = $this->get_synopsis(); if ( ! $synopsis ) { return array( array(), $args, $assoc_args, $extra_args ); } $validator = new \WP_CLI\SynopsisValidator( $synopsis ); $cmd_path = implode( ' ', get_path( $this ) ); foreach ( $validator->get_unknown() as $token ) { \WP_CLI::warning( sprintf( 'The `%s` command has an invalid synopsis part: %s', $cmd_path, $token ) ); } if ( ! $validator->enough_positionals( $args ) ) { $this->show_usage(); exit( 1 ); } $unknown_positionals = $validator->unknown_positionals( $args ); if ( ! empty( $unknown_positionals ) ) { \WP_CLI::error( 'Too many positional arguments: ' . implode( ' ', $unknown_positionals ) ); } $synopsis_spec = \WP_CLI\SynopsisParser::parse( $synopsis ); $i = 0; $errors = array( 'fatal' => array(), 'warning' => array(), ); $mock_doc = array( $this->get_shortdesc(), '' ); $mock_doc = array_merge( $mock_doc, explode( "\n", $this->get_longdesc() ) ); $mock_doc = '/**' . PHP_EOL . '* ' . implode( PHP_EOL . '* ', $mock_doc ) . PHP_EOL . '*/'; $docparser = new \WP_CLI\DocParser( $mock_doc ); foreach ( $synopsis_spec as $spec ) { if ( 'positional' === $spec['type'] ) { $spec_args = $docparser->get_arg_args( $spec['name'] ); if ( ! isset( $args[ $i ] ) ) { if ( isset( $spec_args['default'] ) ) { $args[ $i ] = $spec_args['default']; } } if ( isset( $spec_args['options'] ) ) { if ( ! empty( $spec['repeating'] ) ) { do { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design. if ( isset( $args[ $i ] ) && ! in_array( $args[ $i ], $spec_args['options'] ) ) { \WP_CLI::error( 'Invalid value specified for positional arg.' ); } $i++; } while ( isset( $args[ $i ] ) ); } else { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design. if ( isset( $args[ $i ] ) && ! in_array( $args[ $i ], $spec_args['options'] ) ) { \WP_CLI::error( 'Invalid value specified for positional arg.' ); } } } $i++; } elseif ( 'assoc' === $spec['type'] ) { $spec_args = $docparser->get_param_args( $spec['name'] ); if ( ! isset( $assoc_args[ $spec['name'] ] ) && ! isset( $extra_args[ $spec['name'] ] ) ) { if ( isset( $spec_args['default'] ) ) { $assoc_args[ $spec['name'] ] = $spec_args['default']; } } if ( isset( $assoc_args[ $spec['name'] ] ) && isset( $spec_args['options'] ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design. if ( ! in_array( $assoc_args[ $spec['name'] ], $spec_args['options'] ) ) { $errors['fatal'][ $spec['name'] ] = "Invalid value specified for '{$spec['name']}'"; } } } } list( $returned_errors, $to_unset ) = $validator->validate_assoc( array_merge( \WP_CLI::get_config(), $extra_args, $assoc_args ) ); foreach ( array( 'fatal', 'warning' ) as $error_type ) { $errors[ $error_type ] = array_merge( $errors[ $error_type ], $returned_errors[ $error_type ] ); } if ( 'help' !== $this->name ) { foreach ( $validator->unknown_assoc( $assoc_args ) as $key ) { $suggestion = Utils\get_suggestion( $key, $this->get_parameters( $synopsis_spec ), $threshold = 2 ); $errors['fatal'][] = sprintf( 'unknown --%s parameter%s', $key, ! empty( $suggestion ) ? PHP_EOL . "Did you mean '--{$suggestion}'?" : '' ); } } if ( ! empty( $errors['fatal'] ) ) { $out = 'Parameter errors:'; foreach ( $errors['fatal'] as $key => $error ) { $out .= "\n {$error}"; $desc = $docparser->get_param_desc( $key ); if ( '' !== $desc ) { $out .= " ({$desc})"; } } \WP_CLI::error( $out ); } array_map( '\\WP_CLI::warning', $errors['warning'] ); return array( $to_unset, $args, $assoc_args, $extra_args ); } /** * Invoke the subcommand with the supplied arguments. * Given a --prompt argument, interactively request input * from the end user. * * @param array $args * @param array $assoc_args */ public function invoke( $args, $assoc_args, $extra_args ) { if ( 'help' !== $this->name ) { static $prompted_once = false; if ( \WP_CLI::get_config( 'prompt' ) && ! $prompted_once ) { list( $_args, $assoc_args ) = $this->prompt_args( $args, $assoc_args ); $args = array_merge( $args, $_args ); $prompted_once = true; } } $extra_positionals = array(); foreach ( $extra_args as $k => $v ) { if ( is_numeric( $k ) ) { if ( ! isset( $args[ $k ] ) ) { $extra_positionals[ $k ] = $v; } unset( $extra_args[ $k ] ); } } $args += $extra_positionals; list( $to_unset, $args, $assoc_args, $extra_args ) = $this->validate_args( $args, $assoc_args, $extra_args ); foreach ( $to_unset as $key ) { unset( $assoc_args[ $key ] ); } $path = get_path( $this->get_parent() ); $parent = implode( ' ', array_slice( $path, 1 ) ); $cmd = $this->name; if ( $parent ) { WP_CLI::do_hook( "before_invoke:{$parent}" ); $cmd = $parent . ' ' . $cmd; } WP_CLI::do_hook( "before_invoke:{$cmd}" ); call_user_func( $this->when_invoked, $args, array_merge( $extra_args, $assoc_args ) ); if ( $parent ) { WP_CLI::do_hook( "after_invoke:{$parent}" ); } WP_CLI::do_hook( "after_invoke:{$cmd}" ); } /** * Get an array of parameter names, by merging the command-specific and the * global parameters. * * @param array $spec Optional. Specification of the current command. * * @return array Array of parameter names */ private function get_parameters( $spec = array() ) { $local_parameters = array_column( $spec, 'name' ); $global_parameters = array_column( WP_CLI\SynopsisParser::parse( $this->get_global_params() ), 'name' ); return array_unique( array_merge( $local_parameters, $global_parameters ) ); } } ..." * into [ optional=>false, type=>positional, repeating=>true, name=>object-id ] */ class SynopsisParser { /** * @param string A synopsis * @return array List of parameters */ public static function parse( $synopsis ) { $tokens = array_filter( preg_split( '/[\s\t]+/', $synopsis ) ); $params = array(); foreach ( $tokens as $token ) { $param = self::classify_token( $token ); // Some types of parameters shouldn't be mandatory if ( isset( $param['optional'] ) && ! $param['optional'] ) { if ( 'flag' === $param['type'] || ( 'assoc' === $param['type'] && $param['value']['optional'] ) ) { $param['type'] = 'unknown'; } } $param['token'] = $token; $params[] = $param; } return $params; } /** * Render the Synopsis into a format string. * * @param array $synopsis A structured synopsis. This might get reordered * to match the parsed output. * @return string Rendered synopsis. */ public static function render( &$synopsis ) { if ( ! is_array( $synopsis ) ) { return ''; } $bits = [ 'positional' => '', 'assoc' => '', 'generic' => '', 'flag' => '', ]; $reordered_synopsis = [ 'positional' => [], 'assoc' => [], 'generic' => [], 'flag' => [], ]; foreach ( $bits as $key => &$value ) { foreach ( $synopsis as $arg ) { if ( empty( $arg['type'] ) || $key !== $arg['type'] ) { continue; } if ( empty( $arg['name'] ) && 'generic' !== $arg['type'] ) { continue; } if ( 'positional' === $key ) { $rendered_arg = "<{$arg['name']}>"; $reordered_synopsis['positional'] [] = $arg; } elseif ( 'assoc' === $key ) { $arg_value = isset( $arg['value']['name'] ) ? $arg['value']['name'] : $arg['name']; $rendered_arg = "--{$arg['name']}=<{$arg_value}>"; $reordered_synopsis['assoc'] [] = $arg; } elseif ( 'generic' === $key ) { $rendered_arg = '--='; $reordered_synopsis['generic'] [] = $arg; } elseif ( 'flag' === $key ) { $rendered_arg = "--{$arg['name']}"; $reordered_synopsis['flag'] [] = $arg; } if ( ! empty( $arg['repeating'] ) ) { $rendered_arg = "{$rendered_arg}..."; } if ( ! empty( $arg['optional'] ) ) { $rendered_arg = "[{$rendered_arg}]"; } $value .= "{$rendered_arg} "; } } $rendered = ''; foreach ( $bits as $v ) { if ( ! empty( $v ) ) { $rendered .= $v; } } $synopsis = array_merge( $reordered_synopsis['positional'], $reordered_synopsis['assoc'], $reordered_synopsis['generic'], $reordered_synopsis['flag'] ); return rtrim( $rendered, ' ' ); } /** * Classify argument attributes based on its syntax. * * @param string $token * @return array $param */ private static function classify_token( $token ) { $param = array(); list( $param['optional'], $token ) = self::is_optional( $token ); list( $param['repeating'], $token ) = self::is_repeating( $token ); $p_name = '([a-z-_0-9]+)'; $p_value = '([a-zA-Z-_|,0-9]+)'; if ( '--=' === $token ) { $param['type'] = 'generic'; } elseif ( preg_match( "/^<($p_value)>$/", $token, $matches ) ) { $param['type'] = 'positional'; $param['name'] = $matches[1]; } elseif ( preg_match( "/^--(?:\\[no-\\])?$p_name/", $token, $matches ) ) { $param['name'] = $matches[1]; $value = substr( $token, strlen( $matches[0] ) ); // substr returns false <= PHP 5.6, and '' PHP 7+ if ( false === $value || '' === $value ) { $param['type'] = 'flag'; } else { $param['type'] = 'assoc'; list( $param['value']['optional'], $value ) = self::is_optional( $value ); if ( preg_match( "/^=<$p_value>$/", $value, $matches ) ) { $param['value']['name'] = $matches[1]; } else { $param = array( 'type' => 'unknown', ); } } } else { $param['type'] = 'unknown'; } return $param; } /** * An optional parameter is surrounded by square brackets. * * @param string $token * @return array */ private static function is_optional( $token ) { if ( '[' === substr( $token, 0, 1 ) && ']' === substr( $token, -1 ) ) { return array( true, substr( $token, 1, -1 ) ); } return array( false, $token ); } /** * A repeating parameter is followed by an ellipsis. * * @param string $token * @return array */ private static function is_repeating( $token ) { if ( '...' === substr( $token, -3 ) ) { return array( true, substr( $token, 0, -3 ) ); } return array( false, $token ); } } spec = SynopsisParser::parse( $synopsis ); } /** * Get any unknown arguments. * * @return array */ public function get_unknown() { return array_column( $this->query_spec( array( 'type' => 'unknown', ) ), 'token' ); } /** * Check whether there are enough positional arguments. * * @param array $args Positional arguments. * @return bool */ public function enough_positionals( $args ) { $positional = $this->query_spec( array( 'type' => 'positional', 'optional' => false, ) ); return count( $args ) >= count( $positional ); } /** * Check for any unknown positionals. * * @param array $args Positional arguments. * @return array */ public function unknown_positionals( $args ) { $positional_repeating = $this->query_spec( array( 'type' => 'positional', 'repeating' => true, ) ); // At least one positional supports as many as possible. if ( ! empty( $positional_repeating ) ) { return array(); } $positional = $this->query_spec( array( 'type' => 'positional', 'repeating' => false, ) ); return array_slice( $args, count( $positional ) ); } /** * Check that all required keys are present and that they have values. * * @param array $assoc_args Parameters passed to command. * @return array */ public function validate_assoc( $assoc_args ) { $assoc_spec = $this->query_spec( array( 'type' => 'assoc', ) ); $errors = array( 'fatal' => array(), 'warning' => array(), ); $to_unset = array(); foreach ( $assoc_spec as $param ) { $key = $param['name']; if ( ! isset( $assoc_args[ $key ] ) ) { if ( ! $param['optional'] ) { $errors['fatal'][ $key ] = "missing --$key parameter"; } } else { if ( true === $assoc_args[ $key ] && ! $param['value']['optional'] ) { $error_type = ( ! $param['optional'] ) ? 'fatal' : 'warning'; $errors[ $error_type ][ $key ] = "--$key parameter needs a value"; $to_unset[] = $key; } } } return array( $errors, $to_unset ); } /** * Check whether there are unknown parameters supplied. * * @param array $assoc_args Parameters passed to command. * @return array|false */ public function unknown_assoc( $assoc_args ) { $generic = $this->query_spec( array( 'type' => 'generic', ) ); if ( count( $generic ) ) { return array(); } $known_assoc = array(); foreach ( $this->spec as $param ) { if ( in_array( $param['type'], array( 'assoc', 'flag' ), true ) ) { $known_assoc[] = $param['name']; } } return array_diff( array_keys( $assoc_args ), $known_assoc ); } /** * Filters a list of associative arrays, based on a set of key => value arguments. * * @param array $args An array of key => value arguments to match against * @param string $operator * @return array */ private function query_spec( $args, $operator = 'AND' ) { $operator = strtoupper( $operator ); $count = count( $args ); $filtered = array(); foreach ( $this->spec as $key => $to_match ) { $matched = 0; foreach ( $args as $m_key => $m_value ) { if ( array_key_exists( $m_key, $to_match ) && $m_value === $to_match[ $m_key ] ) { $matched++; } } if ( ( 'AND' === $operator && $matched === $count ) || ( 'OR' === $operator && $matched > 0 ) || ( 'NOT' === $operator && 0 === $matched ) ) { $filtered[ $key ] = $to_match; } } return $filtered; } } spec = include $path; $defaults = array( 'runtime' => false, 'file' => false, 'synopsis' => '', 'default' => null, 'multiple' => false, ); foreach ( $this->spec as $key => &$details ) { $details = array_merge( $defaults, $details ); $this->config[ $key ] = $details['default']; } } /** * Get declared configuration values as an array. * * @return array */ public function to_array() { return array( $this->config, $this->extra_config ); } /** * Get configuration specification, i.e. list of accepted keys. * * @return array */ public function get_spec() { return $this->spec; } /** * Get any aliases defined in config files. * * @return array */ public function get_aliases() { $runtime_alias = getenv( 'WP_CLI_RUNTIME_ALIAS' ); if ( false !== $runtime_alias ) { $returned_aliases = array(); foreach ( json_decode( $runtime_alias, true ) as $key => $value ) { if ( preg_match( '#' . self::ALIAS_REGEX . '#', $key ) ) { $returned_aliases[ $key ] = array(); foreach ( self::$alias_spec as $i ) { if ( isset( $value[ $i ] ) ) { $returned_aliases[ $key ][ $i ] = $value[ $i ]; } } } } return $returned_aliases; } return $this->aliases; } /** * Splits a list of arguments into positional, associative and config. * * @param array(string) * @return array(array) */ public function parse_args( $arguments ) { list( $positional_args, $mixed_args, $global_assoc, $local_assoc ) = self::extract_assoc( $arguments ); list( $assoc_args, $runtime_config ) = $this->unmix_assoc_args( $mixed_args, $global_assoc, $local_assoc ); return array( $positional_args, $assoc_args, $runtime_config ); } /** * Splits positional args from associative args. * * @param array * @return array(array) */ public static function extract_assoc( $arguments ) { $positional_args = array(); $assoc_args = array(); $global_assoc = array(); $local_assoc = array(); foreach ( $arguments as $arg ) { $positional_arg = null; $assoc_arg = null; if ( preg_match( '|^--no-([^=]+)$|', $arg, $matches ) ) { $assoc_arg = array( $matches[1], false ); } elseif ( preg_match( '|^--([^=]+)$|', $arg, $matches ) ) { $assoc_arg = array( $matches[1], true ); } elseif ( preg_match( '|^--([^=]+)=(.*)|s', $arg, $matches ) ) { $assoc_arg = array( $matches[1], $matches[2] ); } else { $positional = $arg; } if ( ! is_null( $assoc_arg ) ) { $assoc_args[] = $assoc_arg; if ( count( $positional_args ) ) { $local_assoc[] = $assoc_arg; } else { $global_assoc[] = $assoc_arg; } } elseif ( ! is_null( $positional ) ) { $positional_args[] = $positional; } } return array( $positional_args, $assoc_args, $global_assoc, $local_assoc ); } /** * Separate runtime parameters from command-specific parameters. * * @param array $mixed_args * @return array */ private function unmix_assoc_args( $mixed_args, $global_assoc = array(), $local_assoc = array() ) { $assoc_args = array(); $runtime_config = array(); if ( getenv( 'WP_CLI_STRICT_ARGS_MODE' ) ) { foreach ( $global_assoc as $tmp ) { list( $key, $value ) = $tmp; if ( isset( $this->spec[ $key ] ) && false !== $this->spec[ $key ]['runtime'] ) { $this->assoc_arg_to_runtime_config( $key, $value, $runtime_config ); } } foreach ( $local_assoc as $tmp ) { $assoc_args[ $tmp[0] ] = $tmp[1]; } } else { foreach ( $mixed_args as $tmp ) { list( $key, $value ) = $tmp; if ( isset( $this->spec[ $key ] ) && false !== $this->spec[ $key ]['runtime'] ) { $this->assoc_arg_to_runtime_config( $key, $value, $runtime_config ); } else { $assoc_args[ $key ] = $value; } } } return array( $assoc_args, $runtime_config ); } /** * Handle turning an $assoc_arg into a runtime arg. */ private function assoc_arg_to_runtime_config( $key, $value, &$runtime_config ) { $details = $this->spec[ $key ]; if ( isset( $details['deprecated'] ) ) { fwrite( STDERR, "WP-CLI: The --{$key} global parameter is deprecated. {$details['deprecated']}\n" ); } if ( $details['multiple'] ) { $runtime_config[ $key ][] = $value; } else { $runtime_config[ $key ] = $value; } } /** * Load a YAML file of parameters into scope. * * @param string $path Path to YAML file. */ public function merge_yml( $path, $current_alias = null ) { $yaml = self::load_yml( $path ); if ( ! empty( $yaml['_']['inherit'] ) ) { $this->merge_yml( $yaml['_']['inherit'], $current_alias ); } // Prepare the base path for absolutized alias paths $yml_file_dir = $path ? dirname( $path ) : false; foreach ( $yaml as $key => $value ) { if ( preg_match( '#' . self::ALIAS_REGEX . '#', $key ) ) { $this->aliases[ $key ] = array(); $is_alias = false; foreach ( self::$alias_spec as $i ) { if ( isset( $value[ $i ] ) ) { if ( 'path' === $i && ! isset( $value['ssh'] ) ) { self::absolutize( $value[ $i ], $yml_file_dir ); } $this->aliases[ $key ][ $i ] = $value[ $i ]; $is_alias = true; } } // If it's not an alias, it might be a group of aliases if ( ! $is_alias && is_array( $value ) ) { $alias_group = array(); foreach ( $value as $i => $k ) { if ( preg_match( '#' . self::ALIAS_REGEX . '#', $k ) ) { $alias_group[] = $k; } } $this->aliases[ $key ] = $alias_group; } } elseif ( ! isset( $this->spec[ $key ] ) || false === $this->spec[ $key ]['file'] ) { if ( isset( $this->extra_config[ $key ] ) && ! empty( $yaml['_']['merge'] ) && is_array( $this->extra_config[ $key ] ) && is_array( $value ) ) { $this->extra_config[ $key ] = array_merge( $this->extra_config[ $key ], $value ); } else { $this->extra_config[ $key ] = $value; } } elseif ( $this->spec[ $key ]['multiple'] ) { self::arrayify( $value ); $this->config[ $key ] = array_merge( $this->config[ $key ], $value ); } else { if ( $current_alias && in_array( $key, self::$alias_spec, true ) ) { continue; } $this->config[ $key ] = $value; } } } /** * Merge an array of values into the configurator config. * * @param array $config */ public function merge_array( $config ) { foreach ( $this->spec as $key => $details ) { if ( false !== $details['runtime'] && isset( $config[ $key ] ) ) { $value = $config[ $key ]; if ( 'require' === $key ) { $value = \WP_CLI\Utils\expand_globs( $value ); } if ( $details['multiple'] ) { self::arrayify( $value ); $this->config[ $key ] = array_merge( $this->config[ $key ], $value ); } else { $this->config[ $key ] = $value; } } } } /** * Load values from a YAML file. * * @param string $yml_file Path to the YAML file * @return array $config Declared configuration values */ private static function load_yml( $yml_file ) { if ( ! $yml_file ) { return array(); } $config = Spyc::YAMLLoad( $yml_file ); // Make sure config-file-relative paths are made absolute. $yml_file_dir = dirname( $yml_file ); if ( isset( $config['path'] ) ) { self::absolutize( $config['path'], $yml_file_dir ); } if ( isset( $config['require'] ) ) { self::arrayify( $config['require'] ); $config['require'] = \WP_CLI\Utils\expand_globs( $config['require'] ); foreach ( $config['require'] as &$path ) { self::absolutize( $path, $yml_file_dir ); } } // Backwards compat // Command 'core config' was moved to 'config create'. if ( isset( $config['core config'] ) ) { $config['config create'] = $config['core config']; unset( $config['core config'] ); } // Command 'checksum core' was moved to 'core verify-checksums'. if ( isset( $config['checksum core'] ) ) { $config['core verify-checksums'] = $config['checksum core']; unset( $config['checksum core'] ); } // Command 'checksum plugin' was moved to 'plugin verify-checksums'. if ( isset( $config['checksum plugin'] ) ) { $config['plugin verify-checksums'] = $config['checksum plugin']; unset( $config['checksum plugin'] ); } return $config; } /** * Conform a variable to an array. * * @param mixed $val A string or an array */ private static function arrayify( &$val ) { $val = (array) $val; } /** * Make a path absolute. * * @param string $path Path to file. * @param string $base Base path to prepend. */ private static function absolutize( &$path, $base ) { if ( ! empty( $path ) && ! \WP_CLI\Utils\is_path_absolute( $path ) ) { $path = $base . DIRECTORY_SEPARATOR . $path; } } } ]+)>#', '$1$2', $message ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags WP_CLI::log( strip_tags( trim( $message ) ) ); } } STDIN, 1 => array( 'pipe', 'w' ), 2 => array( 'pipe', 'w' ), ); /** * @var bool Whether to log run time info or not. */ public static $log_run_times = false; /** * @var array Array of process run time info, keyed by process command, each a 2-element array containing run time and run count. */ public static $run_times = array(); /** * @param string $command Command to execute. * @param string $cwd Directory to execute the command in. * @param array $env Environment variables to set when running the command. * * @return Process */ public static function create( $command, $cwd = null, $env = array() ) { $proc = new self(); $proc->command = $command; $proc->cwd = $cwd; $proc->env = $env; return $proc; } private function __construct() {} /** * Run the command. * * @return \WP_CLI\ProcessRun */ public function run() { $start_time = microtime( true ); $proc = Utils\proc_open_compat( $this->command, self::$descriptors, $pipes, $this->cwd, $this->env ); $stdout = stream_get_contents( $pipes[1] ); fclose( $pipes[1] ); $stderr = stream_get_contents( $pipes[2] ); fclose( $pipes[2] ); $return_code = proc_close( $proc ); $run_time = microtime( true ) - $start_time; if ( self::$log_run_times ) { if ( ! isset( self::$run_times[ $this->command ] ) ) { self::$run_times[ $this->command ] = array( 0, 0 ); } self::$run_times[ $this->command ][0] += $run_time; self::$run_times[ $this->command ][1]++; } return new ProcessRun( array( 'stdout' => $stdout, 'stderr' => $stderr, 'return_code' => $return_code, 'command' => $this->command, 'cwd' => $this->cwd, 'env' => $this->env, 'run_time' => $run_time, ) ); } /** * Run the command, but throw an Exception on error. * * @return \WP_CLI\ProcessRun */ public function run_check() { $r = $this->run(); if ( $r->return_code ) { throw new \RuntimeException( $r ); } return $r; } /** * Run the command, but throw an Exception on error. * Same as `run_check()` above, but checks the correct stderr. * * @return \WP_CLI\ProcessRun */ public function run_check_stderr() { $r = $this->run(); if ( $r->return_code || ! empty( $r->stderr ) ) { throw new \RuntimeException( $r ); } return $r; } } . */ namespace WP_CLI; /** * Doctrine inflector has static methods for inflecting text. * * The methods in these classes are from several different sources collected * across several different php projects and several different authors. The * original author names and emails are not known. * * Pluralize & Singularize implementation are borrowed from CakePHP with some modifications. * * @link www.doctrine-project.org * @since 1.0 * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Inflector { /** * Plural inflector rules. * * @var array */ private static $plural = array( 'rules' => array( '/(s)tatus$/i' => '\1\2tatuses', '/(quiz)$/i' => '\1zes', '/^(ox)$/i' => '\1\2en', '/([m|l])ouse$/i' => '\1ice', '/(matr|vert|ind)(ix|ex)$/i' => '\1ices', '/(x|ch|ss|sh)$/i' => '\1es', '/([^aeiouy]|qu)y$/i' => '\1ies', '/(hive)$/i' => '\1s', '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves', '/sis$/i' => 'ses', '/([ti])um$/i' => '\1a', '/(p)erson$/i' => '\1eople', '/(m)an$/i' => '\1en', '/(c)hild$/i' => '\1hildren', '/(f)oot$/i' => '\1eet', '/(buffal|her|potat|tomat|volcan)o$/i' => '\1\2oes', '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i', '/us$/i' => 'uses', '/(alias)$/i' => '\1es', '/(analys|ax|cris|test|thes)is$/i' => '\1es', '/s$/' => 's', '/^$/' => '', '/$/' => 's', ), 'uninflected' => array( '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people', 'cookie', ), 'irregular' => array( 'atlas' => 'atlases', 'axe' => 'axes', 'beef' => 'beefs', 'brother' => 'brothers', 'cafe' => 'cafes', 'chateau' => 'chateaux', 'child' => 'children', 'cookie' => 'cookies', 'corpus' => 'corpuses', 'cow' => 'cows', 'criterion' => 'criteria', 'curriculum' => 'curricula', 'demo' => 'demos', 'domino' => 'dominoes', 'echo' => 'echoes', 'foot' => 'feet', 'fungus' => 'fungi', 'ganglion' => 'ganglions', 'genie' => 'genies', 'genus' => 'genera', 'graffito' => 'graffiti', 'hippopotamus' => 'hippopotami', 'hoof' => 'hoofs', 'human' => 'humans', 'iris' => 'irises', 'leaf' => 'leaves', 'loaf' => 'loaves', 'man' => 'men', 'medium' => 'media', 'memorandum' => 'memoranda', 'money' => 'monies', 'mongoose' => 'mongooses', 'motto' => 'mottoes', 'move' => 'moves', 'mythos' => 'mythoi', 'niche' => 'niches', 'nucleus' => 'nuclei', 'numen' => 'numina', 'occiput' => 'occiputs', 'octopus' => 'octopuses', 'opus' => 'opuses', 'ox' => 'oxen', 'penis' => 'penises', 'person' => 'people', 'plateau' => 'plateaux', 'runner-up' => 'runners-up', 'sex' => 'sexes', 'soliloquy' => 'soliloquies', 'son-in-law' => 'sons-in-law', 'syllabus' => 'syllabi', 'testis' => 'testes', 'thief' => 'thieves', 'tooth' => 'teeth', 'tornado' => 'tornadoes', 'trilby' => 'trilbys', 'turf' => 'turfs', 'volcano' => 'volcanoes', ), ); /** * Singular inflector rules. * * @var array */ private static $singular = array( 'rules' => array( '/(s)tatuses$/i' => '\1\2tatus', '/^(.*)(menu)s$/i' => '\1\2', '/(quiz)zes$/i' => '\\1', '/(matr)ices$/i' => '\1ix', '/(vert|ind)ices$/i' => '\1ex', '/^(ox)en/i' => '\1', '/(alias)(es)*$/i' => '\1', '/(buffal|her|potat|tomat|volcan)oes$/i' => '\1o', '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us', '/([ftw]ax)es/i' => '\1', '/(analys|ax|cris|test|thes)es$/i' => '\1is', '/(shoe|slave)s$/i' => '\1', '/(o)es$/i' => '\1', '/ouses$/' => 'ouse', '/([^a])uses$/' => '\1us', '/([m|l])ice$/i' => '\1ouse', '/(x|ch|ss|sh)es$/i' => '\1', '/(m)ovies$/i' => '\1\2ovie', '/(s)eries$/i' => '\1\2eries', '/([^aeiouy]|qu)ies$/i' => '\1y', '/([lr])ves$/i' => '\1f', '/(tive)s$/i' => '\1', '/(hive)s$/i' => '\1', '/(drive)s$/i' => '\1', '/([^fo])ves$/i' => '\1fe', '/(^analy)ses$/i' => '\1sis', '/(analy|diagno|^ba|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis', '/([ti])a$/i' => '\1um', '/(p)eople$/i' => '\1\2erson', '/(m)en$/i' => '\1an', '/(c)hildren$/i' => '\1\2hild', '/(f)eet$/i' => '\1oot', '/(n)ews$/i' => '\1\2ews', '/eaus$/' => 'eau', '/^(.*us)$/' => '\\1', '/s$/i' => '', ), 'uninflected' => array( '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss', ), 'irregular' => array( 'criteria' => 'criterion', 'curves' => 'curve', 'emphases' => 'emphasis', 'foes' => 'foe', 'hoaxes' => 'hoax', 'media' => 'medium', 'neuroses' => 'neurosis', 'waves' => 'wave', 'oases' => 'oasis', ), ); /** * Words that should not be inflected. * * @var array */ private static $uninflected = array( 'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps', 'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder', 'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti', 'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings', 'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', '.*?media', 'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese', 'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese', 'proceedings', 'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors', 'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'staff', 'swine', 'testes', 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest', 'Yengeese', ); /** * Method cache array. * * @var array */ private static $cache = array(); /** * The initial state of Inflector so reset() works. * * @var array */ private static $initial_state = array(); /** * Converts a word into the format for a Doctrine table name. Converts 'ModelName' to 'model_name'. * * @param string $word The word to tableize. * * @return string The tableized word. */ public static function tableize( $word ) { return strtolower( preg_replace( '~(?<=\\w)([A-Z])~', '_$1', $word ) ); } /** * Converts a word into the format for a Doctrine class name. Converts 'table_name' to 'TableName'. * * @param string $word The word to classify. * * @return string The classified word. */ public static function classify( $word ) { return str_replace( ' ', '', ucwords( strtr( $word, '_-', ' ' ) ) ); } /** * Camelizes a word. This uses the classify() method and turns the first character to lowercase. * * @param string $word The word to camelize. * * @return string The camelized word. */ public static function camelize( $word ) { return lcfirst( self::classify( $word ) ); } /** * Uppercases words with configurable delimeters between words. * * Takes a string and capitalizes all of the words, like PHP's built-in * ucwords function. This extends that behavior, however, by allowing the * word delimeters to be configured, rather than only separating on * whitespace. * * Here is an example: * * * * * @param string $string The string to operate on. * @param string $delimiters A list of word separators. * * @return string The string with all delimeter-separated words capitalized. */ public static function ucwords( $string, $delimiters = " \n\t\r\0\x0B-" ) { return preg_replace_callback( '/[^' . preg_quote( $delimiters, '/' ) . ']+/', function( $matches ) { return ucfirst( $matches[0] ); }, $string ); } /** * Clears Inflectors inflected value caches, and resets the inflection * rules to the initial values. * * @return void */ public static function reset() { if ( empty( self::$initial_state ) ) { self::$initial_state = get_class_vars( 'Inflector' ); return; } foreach ( self::$initial_state as $key => $val ) { if ( 'initial_state' !== $key ) { self::${$key} = $val; } } } /** * Adds custom inflection $rules, of either 'plural' or 'singular' $type. * * ### Usage: * * {{{ * Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables')); * Inflector::rules('plural', array( * 'rules' => array('/^(inflect)ors$/i' => '\1ables'), * 'uninflected' => array('dontinflectme'), * 'irregular' => array('red' => 'redlings') * )); * }}} * * @param string $type The type of inflection, either 'plural' or 'singular' * @param array $rules An array of rules to be added. * @param boolean $reset If true, will unset default inflections for all * new rules that are being defined in $rules. * * @return void */ public static function rules( $type, $rules, $reset = false ) { foreach ( $rules as $rule => $pattern ) { if ( ! is_array( $pattern ) ) { continue; } if ( $reset ) { self::${$type}[ $rule ] = $pattern; } else { self::${$type}[ $rule ] = ( 'uninflected' === $rule ) ? array_merge( $pattern, self::${$type}[ $rule ] ) : $pattern + self::${$type}[ $rule ]; } unset( $rules[ $rule ], self::${$type}[ 'cache' . ucfirst( $rule ) ] ); if ( isset( self::${$type}['merged'][ $rule ] ) ) { unset( self::${$type}['merged'][ $rule ] ); } if ( 'plural' === $type ) { self::$cache['pluralize'] = array(); self::$cache['tableize'] = array(); } elseif ( 'singular' === $type ) { self::$cache['singularize'] = array(); } } self::${$type}['rules'] = $rules + self::${$type}['rules']; } /** * Returns a word in plural form. * * @param string $word The word in singular form. * * @return string The word in plural form. */ public static function pluralize( $word ) { if ( isset( self::$cache['pluralize'][ $word ] ) ) { return self::$cache['pluralize'][ $word ]; } if ( ! isset( self::$plural['merged']['irregular'] ) ) { self::$plural['merged']['irregular'] = self::$plural['irregular']; } if ( ! isset( self::$plural['merged']['uninflected'] ) ) { self::$plural['merged']['uninflected'] = array_merge( self::$plural['uninflected'], self::$uninflected ); } if ( ! isset( self::$plural['cacheUninflected'] ) || ! isset( self::$plural['cacheIrregular'] ) ) { self::$plural['cacheUninflected'] = '(?:' . implode( '|', self::$plural['merged']['uninflected'] ) . ')'; self::$plural['cacheIrregular'] = '(?:' . implode( '|', array_keys( self::$plural['merged']['irregular'] ) ) . ')'; } if ( preg_match( '/(.*)\\b(' . self::$plural['cacheIrregular'] . ')$/i', $word, $regs ) ) { self::$cache['pluralize'][ $word ] = $regs[1] . substr( $word, 0, 1 ) . substr( self::$plural['merged']['irregular'][ strtolower( $regs[2] ) ], 1 ); return self::$cache['pluralize'][ $word ]; } if ( preg_match( '/^(' . self::$plural['cacheUninflected'] . ')$/i', $word, $regs ) ) { self::$cache['pluralize'][ $word ] = $word; return $word; } foreach ( self::$plural['rules'] as $rule => $replacement ) { if ( preg_match( $rule, $word ) ) { self::$cache['pluralize'][ $word ] = preg_replace( $rule, $replacement, $word ); return self::$cache['pluralize'][ $word ]; } } } /** * Returns a word in singular form. * * @param string $word The word in plural form. * * @return string The word in singular form. */ public static function singularize( $word ) { if ( isset( self::$cache['singularize'][ $word ] ) ) { return self::$cache['singularize'][ $word ]; } if ( ! isset( self::$singular['merged']['uninflected'] ) ) { self::$singular['merged']['uninflected'] = array_merge( self::$singular['uninflected'], self::$uninflected ); } if ( ! isset( self::$singular['merged']['irregular'] ) ) { self::$singular['merged']['irregular'] = array_merge( self::$singular['irregular'], array_flip( self::$plural['irregular'] ) ); } if ( ! isset( self::$singular['cacheUninflected'] ) || ! isset( self::$singular['cacheIrregular'] ) ) { self::$singular['cacheUninflected'] = '(?:' . join( '|', self::$singular['merged']['uninflected'] ) . ')'; self::$singular['cacheIrregular'] = '(?:' . join( '|', array_keys( self::$singular['merged']['irregular'] ) ) . ')'; } if ( preg_match( '/(.*)\\b(' . self::$singular['cacheIrregular'] . ')$/i', $word, $regs ) ) { self::$cache['singularize'][ $word ] = $regs[1] . substr( $word, 0, 1 ) . substr( self::$singular['merged']['irregular'][ strtolower( $regs[2] ) ], 1 ); return self::$cache['singularize'][ $word ]; } if ( preg_match( '/^(' . self::$singular['cacheUninflected'] . ')$/i', $word, $regs ) ) { self::$cache['singularize'][ $word ] = $word; return $word; } foreach ( self::$singular['rules'] as $rule => $replacement ) { if ( preg_match( $rule, $word ) ) { self::$cache['singularize'][ $word ] = preg_replace( $rule, $replacement, $word ); return self::$cache['singularize'][ $word ]; } } self::$cache['singularize'][ $word ] = $word; return $word; } } open( $zipfile ); if ( true === $res ) { $name = Utils\basename( $zipfile ); $tempdir = Utils\get_temp_dir() . uniqid( 'wp-cli-extract-zipfile-', true ) . "-{$name}"; $zip->extractTo( $tempdir ); $zip->close(); self::copy_overwrite_files( self::get_first_subfolder( $tempdir ), $dest ); self::rmdir( $tempdir ); } else { throw new Exception( sprintf( "ZipArchive failed to unzip '%s': %s.", $zipfile, self::zip_error_msg( $res ) ) ); } } /** * Extract a tarball to a specific destination. * * @param string $tarball * @param string $dest */ private static function extract_tarball( $tarball, $dest ) { // Ensure the destination folder exists or can be created. if ( ! self::ensure_dir_exists( $dest ) ) { throw new Exception( "Could not create folder '{$dest}'." ); } if ( class_exists( 'PharData' ) ) { try { $phar = new PharData( $tarball ); $name = Utils\basename( $tarball ); $tempdir = Utils\get_temp_dir() . uniqid( 'wp-cli-extract-tarball-', true ) . "-{$name}"; $phar->extractTo( $tempdir ); self::copy_overwrite_files( self::get_first_subfolder( $tempdir ), $dest ); self::rmdir( $tempdir ); return; } catch ( Exception $e ) { WP_CLI::warning( "PharData failed, falling back to 'tar xz' (" . $e->getMessage() . ')' ); // Fall through to trying `tar xz` below } } // Ensure relative paths cannot be misinterpreted as hostnames. // Prepending `./` will force tar to interpret it as a filesystem path. if ( self::path_is_relative( $tarball ) ) { $tarball = "./{$tarball}"; } if ( ! file( $tarball ) || ! is_readable( $tarball ) || filesize( $tarball ) <= 0 ) { throw new Exception( "Invalid zip file '{$tarball}'." ); } // Note: directory must exist for tar --directory to work. $cmd = Utils\esc_cmd( 'tar xz --strip-components=1 --directory=%s -f %s', $dest, $tarball ); $process_run = WP_CLI::launch( $cmd, false /*exit_on_error*/, true /*return_detailed*/ ); if ( 0 !== $process_run->return_code ) { throw new Exception( sprintf( 'Failed to execute `%s`: %s.', $cmd, self::tar_error_msg( $process_run ) ) ); } } /** * Copy files from source directory to destination directory. Source * directory must exist. * * @param string $source * @param string $dest */ public static function copy_overwrite_files( $source, $dest ) { $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $source, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST ); $error = 0; if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777, true ); } foreach ( $iterator as $item ) { $dest_path = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); if ( $item->isDir() ) { if ( ! is_dir( $dest_path ) ) { mkdir( $dest_path ); } } else { if ( file_exists( $dest_path ) && is_writable( $dest_path ) ) { copy( $item, $dest_path ); } elseif ( ! file_exists( $dest_path ) ) { copy( $item, $dest_path ); } else { $error = 1; WP_CLI::warning( "Unable to copy '" . $iterator->getSubPathName() . "' to current directory." ); } } } if ( $error ) { throw new Exception( 'There was an error overwriting existing files.' ); } } /** * Delete all files and directories recursively from directory. Directory * must exist. * * @param string $dir */ public static function rmdir( $dir ) { $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ); foreach ( $files as $fileinfo ) { $todo = $fileinfo->isDir() ? 'rmdir' : 'unlink'; $path = $fileinfo->getRealPath(); if ( 0 !== strpos( $path, $fileinfo->getRealPath() ) ) { WP_CLI::warning( "Temporary file or folder to be removed was found outside of temporary folder, aborting removal: '{$path}'" ); } $todo( $path ); } rmdir( $dir ); } /** * Return formatted ZipArchive error message from error code. * * @param int $error_code * @return string|int The error message corresponding to the specified * code, if found; Other wise the same error code, * unmodified. */ public static function zip_error_msg( $error_code ) { // From https://github.com/php/php-src/blob/php-5.3.0/ext/zip/php_zip.c#L2623-L2646 static $zip_err_msgs = array( ZipArchive::ER_OK => 'No error', ZipArchive::ER_MULTIDISK => 'Multi-disk zip archives not supported', ZipArchive::ER_RENAME => 'Renaming temporary file failed', ZipArchive::ER_CLOSE => 'Closing zip archive failed', ZipArchive::ER_SEEK => 'Seek error', ZipArchive::ER_READ => 'Read error', ZipArchive::ER_WRITE => 'Write error', ZipArchive::ER_CRC => 'CRC error', ZipArchive::ER_ZIPCLOSED => 'Containing zip archive was closed', ZipArchive::ER_NOENT => 'No such file', ZipArchive::ER_EXISTS => 'File already exists', ZipArchive::ER_OPEN => 'Can\'t open file', ZipArchive::ER_TMPOPEN => 'Failure to create temporary file', ZipArchive::ER_ZLIB => 'Zlib error', ZipArchive::ER_MEMORY => 'Malloc failure', ZipArchive::ER_CHANGED => 'Entry has been changed', ZipArchive::ER_COMPNOTSUPP => 'Compression method not supported', ZipArchive::ER_EOF => 'Premature EOF', ZipArchive::ER_INVAL => 'Invalid argument', ZipArchive::ER_NOZIP => 'Not a zip archive', ZipArchive::ER_INTERNAL => 'Internal error', ZipArchive::ER_INCONS => 'Zip archive inconsistent', ZipArchive::ER_REMOVE => 'Can\'t remove file', ZipArchive::ER_DELETED => 'Entry has been deleted', ); if ( isset( $zip_err_msgs[ $error_code ] ) ) { return sprintf( '%s (%d)', $zip_err_msgs[ $error_code ], $error_code ); } return $error_code; } /** * Return formatted error message from ProcessRun of tar command. * * @param Processrun $process_run * @return string|int The error message of the process, if available; * otherwise the return code. */ public static function tar_error_msg( $process_run ) { $stderr = trim( $process_run->stderr ); $nl_pos = strpos( $stderr, "\n" ); if ( false !== $nl_pos ) { $stderr = trim( substr( $stderr, 0, $nl_pos ) ); } if ( $stderr ) { return sprintf( '%s (%d)', $stderr, $process_run->return_code ); } return $process_run->return_code; } /** * Return the first subfolder within a given path. * * Falls back to the provided path if no subfolder was detected. * * @param string $path Path to find the first subfolder in. * @return string First subfolder, or same as $path if none found. */ private static function get_first_subfolder( $path ) { $iterator = new DirectoryIterator( $path ); foreach ( $iterator as $fileinfo ) { if ( $fileinfo->isDir() && ! $fileinfo->isDot() ) { return "{$path}/{$fileinfo->getFilename()}"; } } return $path; } /** * Ensure directory exists. * * @param string $dir Directory to ensure the existence of. * @return bool Whether the existence could be asserted. */ private static function ensure_dir_exists( $dir ) { if ( ! is_dir( $dir ) ) { if ( ! @mkdir( $dir, 0777, true ) ) { $error = error_get_last(); WP_CLI::warning( sprintf( "Failed to create directory '%s': %s.", $dir, $error['message'] ) ); return false; } } return true; } /** * Check whether a path is relative- * * @param string $path Path to check. * @return bool Whether the path is relative. */ private static function path_is_relative( $path ) { if ( '' === $path ) { return true; } // Strip scheme. $scheme_position = strpos( $path, '://' ); if ( false !== $scheme_position ) { $path = substr( $path, $scheme_position + 3 ); } // UNIX root "/" or "\" (Windows style). if ( '/' === $path[0] || '\\' === $path[0] ) { return false; } // Windows root. if ( strlen( $path ) > 1 && ctype_alpha( $path[0] ) && ':' === $path[1] ) { // Special case: only drive letter, like "C:". if ( 2 === strlen( $path ) ) { return false; } // Regular Windows path starting with drive letter, like "C:/ or "C:\". if ( '/' === $path[2] || '\\' === $path[2] ) { return false; } } return true; } } * foreach( new Iterators\Query( 'SELECT * FROM users', 100 ) as $user ) { * tickle( $user ); * } * * * @param string $query The query as a string. It shouldn't include any LIMIT clauses * @param int $chunk_size How many rows to retrieve at once; default value is 500 (optional) */ public function __construct( $query, $chunk_size = 500 ) { $this->query = $query; $this->count_query = preg_replace( '/^.*? FROM /', 'SELECT COUNT(*) FROM ', $query, 1, $replacements ); if ( 1 !== $replacements ) { $this->count_query = ''; } $this->chunk_size = $chunk_size; $this->db = $GLOBALS['wpdb']; } /** * Reduces the offset when the query row count shrinks * * In cases where the iterated rows are being updated such that they will no * longer be returned by the original query, the offset must be reduced to * iterate over all remaining rows. */ private function adjust_offset_for_shrinking_result_set() { if ( empty( $this->count_query ) ) { return; } $row_count = $this->db->get_var( $this->count_query ); if ( $row_count < $this->row_count ) { $this->offset -= $this->row_count - $row_count; } $this->row_count = $row_count; } private function load_items_from_db() { $this->adjust_offset_for_shrinking_result_set(); $query = $this->query . sprintf( ' LIMIT %d OFFSET %d', $this->chunk_size, $this->offset ); $this->results = $this->db->get_results( $query ); if ( ! $this->results ) { if ( $this->db->last_error ) { throw new Exception( 'Database error: ' . $this->db->last_error ); } return false; } $this->offset += $this->chunk_size; return true; } public function current() { return $this->results[ $this->index_in_results ]; } public function key() { return $this->global_index; } public function next() { $this->index_in_results++; $this->global_index++; } public function rewind() { $this->results = array(); $this->global_index = 0; $this->index_in_results = 0; $this->offset = 0; $this->depleted = false; } public function valid() { if ( $this->depleted ) { return false; } if ( ! isset( $this->results[ $this->index_in_results ] ) ) { $items_loaded = $this->load_items_from_db(); if ( ! $items_loaded ) { $this->rewind(); $this->depleted = true; return false; } $this->index_in_results = 0; } return true; } } transformers[] = $fn; } public function current() { $value = parent::current(); foreach ( $this->transformers as $fn ) { $value = call_user_func( $fn, $value ); } return $value; } } * foreach( new Iterators\Table( array( 'table' => $wpdb->posts, 'fields' => array( 'ID', 'post_content' ) ) ) as $post ) { * count_words_for( $post->ID, $post->post_content ); * } * * * * foreach( new Iterators\Table( array( 'table' => $wpdb->posts, 'where' => 'ID = 8 OR post_status = "publish"' ) ) as $post ) { * … * } * * * * foreach( new PostIterator( array( 'table' => $wpdb->posts, 'where' => array( 'post_status' => 'publish', 'post_date_gmt BETWEEN x AND y' ) ) ) as $post ) { * … * } * * * * @param array $args Supported arguments: * table – the name of the database table * fields – an array of columns to get from the table, '*' is a valid value and the default * where – conditions for filtering rows. Supports two formats: * = string – this will be the where clause * = array – each element is treated as a condition if it's positional, or as column => value if * it's a key/value pair. In the latter case the value is automatically quoted and escaped * append - add arbitrary extra SQL */ public function __construct( $args = array() ) { $defaults = array( 'fields' => '*', 'where' => array(), 'append' => '', 'table' => null, 'chunk_size' => 500, ); $table = $args['table']; $args = array_merge( $defaults, $args ); $fields = self::build_fields( $args['fields'] ); $conditions = self::build_where_conditions( $args['where'] ); $where_sql = $conditions ? " WHERE $conditions" : ''; $query = "SELECT $fields FROM `$table` $where_sql {$args['append']}"; parent::__construct( $query, $args['chunk_size'] ); } private static function build_fields( $fields ) { if ( '*' === $fields ) { return $fields; } return implode( ', ', array_map( function ( $v ) { return "`$v`"; }, $fields ) ); } private static function build_where_conditions( $where ) { global $wpdb; if ( is_array( $where ) ) { $conditions = array(); foreach ( $where as $key => $value ) { if ( is_array( $value ) ) { $conditions[] = $key . ' IN (' . esc_sql( implode( ',', $value ) ) . ')'; } elseif ( is_numeric( $key ) ) { $conditions[] = $value; } else { $conditions[] = $key . $wpdb->prepare( ' = %s', $value ); } } $where = implode( ' AND ', $conditions ); } return $where; } } filename = $filename; $this->file_pointer = fopen( $filename, 'rb' ); if ( ! $this->file_pointer ) { \WP_CLI::error( sprintf( 'Could not open file: %s', $filename ) ); } $this->delimiter = $delimiter; } public function rewind() { rewind( $this->file_pointer ); $this->columns = fgetcsv( $this->file_pointer, self::ROW_SIZE, $this->delimiter ); $this->current_index = -1; $this->next(); } public function current() { return $this->current_element; } public function key() { return $this->current_index; } public function next() { $this->current_element = false; while ( true ) { $str = fgets( $this->file_pointer ); if ( false === $str ) { break; } $row = str_getcsv( $str, $this->delimiter ); $element = array(); foreach ( $this->columns as $i => $key ) { if ( isset( $row[ $i ] ) ) { $element[ $key ] = $row[ $i ]; } } if ( ! empty( $element ) ) { $this->current_element = $element; $this->current_index++; break; } } } public function count() { $file = new \SplFileObject( $this->filename, 'r' ); $file->seek( PHP_INT_MAX ); return $file->key() + 1; } public function valid() { return is_array( $this->current_element ); } } add_namespace( 'WP_CLI\Bootstrap', WP_CLI_ROOT . '/php/WP_CLI/Bootstrap' )->register(); } /** * Initialize and return the bootstrap state to pass from step to step. * * @return BootstrapState */ function initialize_bootstrap_state() { return new BootstrapState(); } /** * Process the bootstrapping steps. * * Loops over each of the provided steps, instantiates it and then calls its * `process()` method. */ function bootstrap() { prepare_bootstrap(); $state = initialize_bootstrap_state(); foreach ( get_bootstrap_steps() as $step ) { /** @var \WP_CLI\Bootstrap\BootstrapStep $step_instance */ $step_instance = new $step(); $state = $step_instance->process( $state ); } } ...] * : Get help on a specific command. * * ## EXAMPLES * * # get help for `core` command * wp help core * * # get help for `core download` subcommand * wp help core download */ public function __invoke( $args, $assoc_args ) { $r = WP_CLI::get_runner()->find_command_to_run( $args ); if ( is_array( $r ) ) { list( $command ) = $r; self::show_help( $command ); exit; } } private static function show_help( $command ) { $out = self::get_initial_markdown( $command ); // Remove subcommands if in columns - will wordwrap separately. $subcommands = ''; $column_subpattern = '[ \t]+[^\t]+\t+'; if ( preg_match( '/(^## SUBCOMMANDS[^\n]*\n+' . $column_subpattern . '.+?)(?:^##|\z)/ms', $out, $matches, PREG_OFFSET_CAPTURE ) ) { $subcommands = $matches[1][0]; $subcommands_header = "## SUBCOMMANDS\n"; $out = substr_replace( $out, $subcommands_header, $matches[1][1], strlen( $subcommands ) ); } $out .= self::parse_reference_links( $command->get_longdesc() ); // definition lists $out = preg_replace_callback( '/([^\n]+)\n: (.+?)(\n\n|$)/s', array( __CLASS__, 'rewrap_param_desc' ), $out ); // Ensure lines with no leading whitespace that aren't section headers are indented. $out = preg_replace( '/^((?! |\t|##).)/m', "\t$1", $out ); $tab = str_repeat( ' ', 2 ); // Need to de-tab for wordwrapping to work properly. $out = str_replace( "\t", $tab, $out ); $wordwrap_width = \cli\Shell::columns(); // Wordwrap with indent. $out = preg_replace_callback( '/^( *)([^\n]+)\n/m', function ( $matches ) use ( $wordwrap_width ) { return $matches[1] . str_replace( "\n", "\n{$matches[1]}", wordwrap( $matches[2], $wordwrap_width - strlen( $matches[1] ) ) ) . "\n"; }, $out ); if ( $subcommands ) { // Wordwrap with column indent. $subcommands = preg_replace_callback( '/^(' . $column_subpattern . ')([^\n]+)\n/m', function ( $matches ) use ( $wordwrap_width, $tab ) { // Need to de-tab for wordwrapping to work properly. $matches[1] = str_replace( "\t", $tab, $matches[1] ); $matches[2] = str_replace( "\t", $tab, $matches[2] ); $padding_len = strlen( $matches[1] ); $padding = str_repeat( ' ', $padding_len ); return $matches[1] . str_replace( "\n", "\n$padding", wordwrap( $matches[2], $wordwrap_width - $padding_len ) ) . "\n"; }, $subcommands ); // Put subcommands back. $out = str_replace( $subcommands_header, $subcommands, $out ); } // section headers $out = preg_replace( '/^## ([A-Z ]+)/m', WP_CLI::colorize( '%9\1%n' ), $out ); self::pass_through_pager( $out ); } private static function rewrap_param_desc( $matches ) { $param = $matches[1]; $desc = self::indent( "\t\t", $matches[2] ); return "\t$param\n$desc\n\n"; } private static function indent( $whitespace, $text ) { $lines = explode( "\n", $text ); foreach ( $lines as &$line ) { $line = $whitespace . $line; } return implode( "\n", $lines ); } private static function pass_through_pager( $out ) { if ( ! Utils\check_proc_available( null /*context*/, true /*return*/ ) ) { WP_CLI::line( $out ); WP_CLI::debug( 'Warning: check_proc_available() failed in pass_through_pager().', 'help' ); return -1; } $pager = getenv( 'PAGER' ); if ( false === $pager ) { $pager = Utils\is_windows() ? 'more' : 'less -r'; } // For Windows 7 need to set code page to something other than Unicode (65001) to get around "Not enough memory." error with `more.com` on PHP 7.1+. if ( 'more' === $pager && defined( 'PHP_WINDOWS_VERSION_MAJOR' ) && PHP_WINDOWS_VERSION_MAJOR < 10 && function_exists( 'sapi_windows_cp_set' ) ) { // Note will also apply to Windows 8 (see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832.aspx) but probably harmless anyway. $cp = getenv( 'WP_CLI_WINDOWS_CODE_PAGE' ) ?: 1252; // Code page 1252 is the most used so probably the most compat. // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions -- Wrapped in function_exists() call. sapi_windows_cp_set( $cp ); // `sapi_windows_cp_set()` introduced PHP 7.1. } // convert string to file handle $fd = fopen( 'php://temp', 'r+b' ); fwrite( $fd, $out ); rewind( $fd ); $descriptorspec = array( 0 => $fd, 1 => STDOUT, 2 => STDERR, ); return proc_close( Utils\proc_open_compat( $pager, $descriptorspec, $pipes ) ); } private static function get_initial_markdown( $command ) { $name = implode( ' ', Dispatcher\get_path( $command ) ); $binding = array( 'name' => $name, 'shortdesc' => $command->get_shortdesc(), ); $binding['synopsis'] = "$name " . $command->get_synopsis(); $alias = $command->get_alias(); if ( $alias ) { $binding['alias'] = $alias; } if ( $command->can_have_subcommands() ) { $binding['has-subcommands']['subcommands'] = self::render_subcommands( $command ); } return Utils\mustache_render( 'man.mustache', $binding ); } private static function render_subcommands( $command ) { $subcommands = array(); foreach ( $command->get_subcommands() as $subcommand ) { if ( WP_CLI::get_runner()->is_command_disabled( $subcommand ) ) { continue; } $subcommands[ $subcommand->get_name() ] = $subcommand->get_shortdesc(); } $max_len = self::get_max_len( array_keys( $subcommands ) ); $lines = array(); foreach ( $subcommands as $name => $desc ) { $lines[] = str_pad( $name, $max_len ) . "\t\t\t" . $desc; } return $lines; } private static function get_max_len( $strings ) { $max_len = 0; foreach ( $strings as $str ) { $len = strlen( $str ); if ( $len > $max_len ) { $max_len = $len; } } return $max_len; } /** * Parse reference links from longdescription. * * @param string $longdesc The longdescription from the `$command->get_longdesc()`. * @return string The longdescription which has links as footnote. */ private static function parse_reference_links( $longdesc ) { $description = ''; foreach ( explode( "\n", $longdesc ) as $line ) { if ( 0 === strpos( $line, '#' ) ) { break; } $description .= $line . "\n"; } // Fires if it has description text at the head of `$longdesc`. if ( $description ) { $links = array(); // An array of URLs from the description. $pattern = '/\[.+?\]\((https?:\/\/.+?)\)/'; $newdesc = preg_replace_callback( $pattern, function( $matches ) use ( &$links ) { static $count = 0; $count++; $links[] = $matches[1]; return str_replace( '(' . $matches[1] . ')', '[' . $count . ']', $matches[0] ); }, $description ); $footnote = ''; $link_count = count( $links ); for ( $i = 0; $i < $link_count; $i++ ) { $n = $i + 1; $footnote .= '[' . $n . '] ' . $links[ $i ] . "\n"; } if ( $footnote ) { $newdesc = trim( $newdesc ) . "\n\n---\n" . $footnote; $longdesc = str_replace( trim( $description ), trim( $newdesc ), $longdesc ); } } return $longdesc; } } ] * : Render output in a particular format. * --- * default: yaml * options: * - yaml * - json * - var_export * --- * * ## EXAMPLES * * # List all available aliases. * $ wp cli alias list * --- * @all: Run command against every registered alias. * @prod: * ssh: runcommand@runcommand.io~/webapps/production * @dev: * ssh: vagrant@192.168.50.10/srv/www/runcommand.dev * @both: * - @prod * - @dev * * @subcommand list */ public function list_( $args, $assoc_args ) { WP_CLI::print_value( WP_CLI::get_runner()->aliases, $assoc_args ); } /** * Gets the value for an alias. * * ## OPTIONS * * * : Key for the alias. * * ## EXAMPLES * * # Get alias. * $ wp cli alias get @prod * ssh: dev@somedeve.env:12345/home/dev/ */ public function get( $args, $assoc_args ) { list( $alias ) = $args; $aliases = WP_CLI::get_runner()->aliases; if ( empty( $aliases[ $alias ] ) ) { WP_CLI::error( "No alias found with key '{$alias}'." ); } foreach ( $aliases[ $alias ] as $key => $value ) { WP_CLI::log( "{$key}: {$value}" ); } } /** * Creates an alias. * * ## OPTIONS * * * : Key for the alias. * * [--set-user=] * : Set user for alias. * * [--set-url=] * : Set url for alias. * * [--set-path=] * : Set path for alias. * * [--set-ssh=] * : Set ssh for alias. * * [--set-http=] * : Set http for alias. * * [--grouping=] * : For grouping multiple aliases. * * [--config=] * : Config file to be considered for operations. * --- * default: global * options: * - global * - project * --- * * ## EXAMPLES * * # Add alias to global config. * $ wp cli alias add @prod --set-ssh=login@host --set-path=/path/to/wordpress/install/ --set-user=wpcli * Success: Added '@prod' alias. * * # Add alias to project config. * $ wp cli alias add @prod --set-ssh=login@host --set-path=/path/to/wordpress/install/ --set-user=wpcli --config=project * Success: Added '@prod' alias. * * # Add group of aliases. * $ wp cli alias add @multiservers --grouping=servera,serverb * Success: Added '@multiservers' alias. */ public function add( $args, $assoc_args ) { $config = ( ! empty( $assoc_args['config'] ) ? $assoc_args['config'] : 'global' ); list( $config_path, $aliases ) = $this->get_aliases_data( $config, '' ); $this->validate_config_file( $config_path ); $alias = $args[0]; $grouping = WP_CLI\Utils\get_flag_value( $assoc_args, 'grouping' ); $this->validate_input( $assoc_args, $grouping ); if ( isset( $aliases[ $alias ] ) ) { WP_CLI::error( "Key '{$alias}' exists already." ); } if ( null === $grouping ) { $aliases = $this->build_aliases( $aliases, $alias, $assoc_args, false ); } else { $aliases = $this->build_aliases( $aliases, $alias, $assoc_args, true, $grouping ); } $this->process_aliases( $aliases, $alias, $config_path, 'Added' ); } /** * Deletes an alias. * * ## OPTIONS * * * : Key for the alias. * * [--config=] * : Config file to be considered for operations. * --- * options: * - global * - project * --- * * ## EXAMPLES * * # Delete alias. * $ wp cli alias delete @prod * Success: Deleted '@prod' alias. * * # Delete project alias. * $ wp cli alias delete @prod --config=project * Success: Deleted '@prod' alias. */ public function delete( $args, $assoc_args ) { list( $alias ) = $args; $config = ( ! empty( $assoc_args['config'] ) ? $assoc_args['config'] : '' ); list( $config_path, $aliases ) = $this->get_aliases_data( $config, $alias ); $this->validate_config_file( $config_path ); if ( empty( $aliases[ $alias ] ) ) { WP_CLI::error( "No alias found with key '{$alias}'." ); } unset( $aliases[ $alias ] ); $this->process_aliases( $aliases, $alias, $config_path, 'Deleted' ); } /** * Updates an alias. * * ## OPTIONS * * * : Key for the alias. * * [--set-user=] * : Set user for alias. * * [--set-url=] * : Set url for alias. * * [--set-path=] * : Set path for alias. * * [--set-ssh=] * : Set ssh for alias. * * [--set-http=] * : Set http for alias. * * [--grouping=] * : For grouping multiple aliases. * * [--config=] * : Config file to be considered for operations. * --- * options: * - global * - project * --- * * ## EXAMPLES * * # Update alias. * $ wp cli alias update @prod --set-user=newuser --set-path=/new/path/to/wordpress/install/ * Success: Updated 'prod' alias. * * # Update project alias. * $ wp cli alias update @prod --set-user=newuser --set-path=/new/path/to/wordpress/install/ --config=project * Success: Updated 'prod' alias. */ public function update( $args, $assoc_args ) { $config = ( ! empty( $assoc_args['config'] ) ? $assoc_args['config'] : '' ); $alias = $args[0]; $grouping = WP_CLI\Utils\get_flag_value( $assoc_args, 'grouping' ); list( $config_path, $aliases ) = $this->get_aliases_data( $config, $alias ); $this->validate_config_file( $config_path ); $this->validate_input( $assoc_args, $grouping ); if ( empty( $aliases[ $alias ] ) ) { WP_CLI::error( "No alias found with key '{$alias}'." ); } if ( null === $grouping ) { $aliases = $this->build_aliases( $aliases, $alias, $assoc_args, false, '', true ); } else { $aliases = $this->build_aliases( $aliases, $alias, $assoc_args, true, $grouping, true ); } $this->process_aliases( $aliases, $alias, $config_path, 'Updated' ); } /** * Get config path and aliases data based on config type. * * @param string $config Type of config to get data from. * @param string $alias Alias to be used for Add/Update/Delete. * * @return array Config Path and Aliases in it. */ private function get_aliases_data( $config, $alias ) { $global_config_path = WP_CLI::get_runner()->get_global_config_path(); $global_aliases = Spyc::YAMLLoad( $global_config_path ); $project_config_path = WP_CLI::get_runner()->get_project_config_path(); $project_aliases = Spyc::YAMLLoad( $project_config_path ); if ( 'global' === $config ) { $config_path = $global_config_path; $aliases = $global_aliases; } elseif ( 'project' === $config ) { $config_path = $project_config_path; $aliases = $project_aliases; } else { $is_global_alias = array_key_exists( $alias, $global_aliases ); $is_project_alias = array_key_exists( $alias, $project_aliases ); if ( $is_global_alias && $is_project_alias ) { WP_CLI::error( "Key '{$alias}' found in more than one path. Please pass --config param." ); } elseif ( $is_global_alias ) { $config_path = $global_config_path; $aliases = $global_aliases; } else { $config_path = $project_config_path; $aliases = $project_aliases; } } return array( $config_path, $aliases ); } /** * Check if the config file exists and is writable. * * @param string $config_path Path to config file. * * @return void */ private function validate_config_file( $config_path ) { if ( ! file_exists( $config_path ) || ! is_writable( $config_path ) ) { WP_CLI::error( "Config file does not exist: {$config_path}" ); } } /** * Return aliases array. * * @param array $aliases Current aliases data. * @param string $alias Name of alias. * @param array $key_args Associative arguments. * @param bool $is_grouping Check if its a grouping operation. * @param string $grouping Grouping value. * @param bool $is_update Is this an update operation? * * @return mixed */ private function build_aliases( $aliases, $alias, $assoc_args, $is_grouping, $grouping = '', $is_update = false ) { if ( $is_grouping ) { $valid_assoc_args = array( 'config', 'grouping' ); $invalid_args = array_diff( array_keys( $assoc_args ), $valid_assoc_args ); // Check for invalid args. if ( ! empty( $invalid_args ) ) { $args_info = implode( ',', $invalid_args ); WP_CLI::error( "--grouping argument works alone. Found invalid arg(s) '$args_info'." ); } } if ( $is_update ) { $this->validate_alias_type( $aliases, $alias, $assoc_args, $grouping ); } if ( ! $is_grouping ) { foreach ( $assoc_args as $key => $value ) { if ( strpos( $key, 'set-' ) !== false ) { $alias_key_info = explode( '-', $key ); $alias_key = empty( $alias_key_info[1] ) ? '' : $alias_key_info[1]; if ( ! empty( $alias_key ) && ! empty( $value ) ) { $aliases[ $alias ][ $alias_key ] = $value; } } } } else { if ( ! empty( $grouping ) ) { $group_alias_list = explode( ',', $grouping ); $group_alias = array_map( function ( $current_alias ) { return '@' . ltrim( $current_alias, '@' ); }, $group_alias_list ); $aliases[ $alias ] = $group_alias; } } return $aliases; } /** * Validate input of passed arguments. * * @param array $assoc_args Arguments array. * @param string $grouping Grouping argument value. * * @throws WP_CLI\ExitException */ private function validate_input( $assoc_args, $grouping ) { // Check if valid arguments were passed. $arg_match = preg_grep( '/^set-(\w+)/i', array_keys( $assoc_args ) ); // Verify passed-arguments. if ( empty( $grouping ) && empty( $arg_match ) ) { WP_CLI::error( 'No valid arguments passed.' ); } // Check whether passed arguments contain value or not. $assoc_arg_values = array_filter( array_intersect_key( $assoc_args, array_flip( $arg_match ) ) ); if ( empty( $grouping ) && empty( $assoc_arg_values ) ) { WP_CLI::error( 'No value passed to arguments.' ); } } /** * Validate alias type before update. * * @param array $aliases Existing aliases data. * @param string $alias Alias Name. * @param array $assoc_args Arguments array. * @param string $grouping Grouping argument value. * * @throws WP_CLI\ExitException */ private function validate_alias_type( $aliases, $alias, $assoc_args, $grouping ) { $alias_data = $aliases[ $alias ]; $group_aliases_match = preg_grep( '/^@(\w+)/i', $alias_data ); $arg_match = preg_grep( '/^set-(\w+)/i', array_keys( $assoc_args ) ); if ( ! empty( $group_aliases_match ) && ! empty( $arg_match ) ) { WP_CLI::error( 'Trying to update group alias with invalid arguments.' ); } elseif ( empty( $group_aliases_match ) && ! empty( $grouping ) ) { WP_CLI::error( 'Trying to update simple alias with invalid --grouping argument.' ); } } /** * Save aliases data to config file. * * @param array $aliases Current aliases data. * @param string $alias Name of alias. * @param string $config_path Path to config file. * @param string $operation Current operation string fro message. */ private function process_aliases( $aliases, $alias, $config_path, $operation = '' ) { // Convert data to YAML string. $yaml_data = Spyc::YAMLDump( $aliases ); // Add data in config file. if ( file_put_contents( $config_path, $yaml_data ) ) { WP_CLI::success( "$operation '{$alias}' alias." ); } } } is_enabled() ) { WP_CLI::error( 'Cache directory does not exist.' ); } $cache->clear(); WP_CLI::success( 'Cache cleared.' ); } /** * Prunes the internal cache. * * Removes all cached files except for the newest version of each one. * * ## EXAMPLES * * $ wp cli cache prune * Success: Cache pruned. * * @subcommand prune */ public function cache_prune() { $cache = WP_CLI::get_cache(); if ( ! $cache->is_enabled() ) { WP_CLI::error( 'Cache directory does not exist.' ); } $cache->prune(); WP_CLI::success( 'Cache pruned.' ); } } $command->get_name(), 'description' => $command->get_shortdesc(), 'longdesc' => $command->get_longdesc(), ); foreach ( $command->get_subcommands() as $subcommand ) { $dump['subcommands'][] = $this->command_to_array( $subcommand ); } if ( empty( $dump['subcommands'] ) ) { $dump['synopsis'] = (string) $command->get_synopsis(); } return $dump; } /** * Prints WP-CLI version. * * ## EXAMPLES * * # Display CLI version. * $ wp cli version * WP-CLI 0.24.1 */ public function version() { WP_CLI::line( 'WP-CLI ' . WP_CLI_VERSION ); } /** * Prints various details about the WP-CLI environment. * * Helpful for diagnostic purposes, this command shares: * * * OS information. * * Shell information. * * PHP binary used. * * PHP binary version. * * php.ini configuration file used (which is typically different than web). * * WP-CLI root dir: where WP-CLI is installed (if non-Phar install). * * WP-CLI global config: where the global config YAML file is located. * * WP-CLI project config: where the project config YAML file is located. * * WP-CLI version: currently installed version. * * See [config docs](https://wp-cli.org/config/) for more details on global * and project config YAML files. * * ## OPTIONS * * [--format=] * : Render output in a particular format. * --- * default: list * options: * - list * - json * --- * * ## EXAMPLES * * # Display various data about the CLI environment. * $ wp cli info * OS: Linux 4.10.0-42-generic #46~16.04.1-Ubuntu SMP Mon Dec 4 15:57:59 UTC 2017 x86_64 * Shell: /usr/bin/zsh * PHP binary: /usr/bin/php * PHP version: 7.1.12-1+ubuntu16.04.1+deb.sury.org+1 * php.ini used: /etc/php/7.1/cli/php.ini * WP-CLI root dir: phar://wp-cli.phar * WP-CLI packages dir: /home/person/.wp-cli/packages/ * WP-CLI global config: * WP-CLI project config: * WP-CLI version: 1.5.0 */ public function info( $_, $assoc_args ) { $php_bin = Utils\get_php_binary(); // php_uname() $mode argument was only added with PHP 7.0+. Fall back to // entire string for older versions. $system_os = PHP_MAJOR_VERSION < 7 ? php_uname() : sprintf( '%s %s %s %s', php_uname( 's' ), php_uname( 'r' ), php_uname( 'v' ), php_uname( 'm' ) ); $shell = getenv( 'SHELL' ); if ( ! $shell && Utils\is_windows() ) { $shell = getenv( 'ComSpec' ); } $runner = WP_CLI::get_runner(); $packages_dir = $runner->get_packages_dir_path(); if ( ! is_dir( $packages_dir ) ) { $packages_dir = null; } if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ) === 'json' ) { $info = array( 'php_binary_path' => $php_bin, 'global_config_path' => $runner->global_config_path, 'project_config_path' => $runner->project_config_path, 'wp_cli_dir_path' => WP_CLI_ROOT, 'wp_cli_packages_dir_path' => $packages_dir, 'wp_cli_version' => WP_CLI_VERSION, 'system_os' => $system_os, 'shell' => $shell, ); WP_CLI::line( json_encode( $info ) ); } else { WP_CLI::line( "OS:\t" . $system_os ); WP_CLI::line( "Shell:\t" . $shell ); WP_CLI::line( "PHP binary:\t" . $php_bin ); WP_CLI::line( "PHP version:\t" . PHP_VERSION ); WP_CLI::line( "php.ini used:\t" . get_cfg_var( 'cfg_file_path' ) ); WP_CLI::line( "WP-CLI root dir:\t" . WP_CLI_ROOT ); WP_CLI::line( "WP-CLI vendor dir:\t" . WP_CLI_VENDOR_DIR ); WP_CLI::line( "WP_CLI phar path:\t" . ( defined( 'WP_CLI_PHAR_PATH' ) ? WP_CLI_PHAR_PATH : '' ) ); WP_CLI::line( "WP-CLI packages dir:\t" . $packages_dir ); WP_CLI::line( "WP-CLI global config:\t" . $runner->global_config_path ); WP_CLI::line( "WP-CLI project config:\t" . $runner->project_config_path ); WP_CLI::line( "WP-CLI version:\t" . WP_CLI_VERSION ); } } /** * Checks to see if there is a newer version of WP-CLI available. * * Queries the Github releases API. Returns available versions if there are * updates available, or success message if using the latest release. * * ## OPTIONS * * [--patch] * : Only list patch updates. * * [--minor] * : Only list minor updates. * * [--major] * : Only list major updates. * * [--field=] * : Prints the value of a single field for each update. * * [--fields=] * : Limit the output to specific object fields. Defaults to version,update_type,package_url. * * [--format=] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - json * - count * - yaml * --- * * ## EXAMPLES * * # Check for update. * $ wp cli check-update * Success: WP-CLI is at the latest version. * * # Check for update and new version is available. * $ wp cli check-update * +---------+-------------+-------------------------------------------------------------------------------+ * | version | update_type | package_url | * +---------+-------------+-------------------------------------------------------------------------------+ * | 0.24.1 | patch | https://github.com/wp-cli/wp-cli/releases/download/v0.24.1/wp-cli-0.24.1.phar | * +---------+-------------+-------------------------------------------------------------------------------+ * * @subcommand check-update */ public function check_update( $_, $assoc_args ) { $updates = $this->get_updates( $assoc_args ); if ( $updates ) { $formatter = new \WP_CLI\Formatter( $assoc_args, array( 'version', 'update_type', 'package_url' ) ); $formatter->display_items( $updates ); } elseif ( empty( $assoc_args['format'] ) || 'table' === $assoc_args['format'] ) { $update_type = $this->get_update_type_str( $assoc_args ); WP_CLI::success( "WP-CLI is at the latest{$update_type}version." ); } } /** * Updates WP-CLI to the latest release. * * Default behavior is to check the releases API for the newest stable * version, and prompt if one is available. * * Use `--stable` to install or reinstall the latest stable version. * * Use `--nightly` to install the latest built version of the master branch. * While not recommended for production, nightly contains the latest and * greatest, and should be stable enough for development and staging * environments. * * Only works for the Phar installation mechanism. * * ## OPTIONS * * [--patch] * : Only perform patch updates. * * [--minor] * : Only perform minor updates. * * [--major] * : Only perform major updates. * * [--stable] * : Update to the latest stable release. Skips update check. * * [--nightly] * : Update to the latest built version of the master branch. Potentially unstable. * * [--yes] * : Do not prompt for confirmation. * * ## EXAMPLES * * # Update CLI. * $ wp cli update * You have version 0.24.0. Would you like to update to 0.24.1? [y/n] y * Downloading from https://github.com/wp-cli/wp-cli/releases/download/v0.24.1/wp-cli-0.24.1.phar... * New version works. Proceeding to replace. * Success: Updated WP-CLI to 0.24.1. */ public function update( $_, $assoc_args ) { if ( ! Utils\inside_phar() ) { WP_CLI::error( 'You can only self-update Phar files.' ); } $old_phar = realpath( $_SERVER['argv'][0] ); if ( ! is_writable( $old_phar ) ) { WP_CLI::error( sprintf( '%s is not writable by current user.', $old_phar ) ); } elseif ( ! is_writable( dirname( $old_phar ) ) ) { WP_CLI::error( sprintf( '%s is not writable by current user.', dirname( $old_phar ) ) ); } if ( Utils\get_flag_value( $assoc_args, 'nightly' ) ) { WP_CLI::confirm( sprintf( 'You have version %s. Would you like to update to the latest nightly?', WP_CLI_VERSION ), $assoc_args ); $download_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar'; $md5_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar.md5'; } elseif ( Utils\get_flag_value( $assoc_args, 'stable' ) ) { WP_CLI::confirm( sprintf( 'You have version %s. Would you like to update to the latest stable release?', WP_CLI_VERSION ), $assoc_args ); $download_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'; $md5_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar.md5'; } else { $updates = $this->get_updates( $assoc_args ); if ( empty( $updates ) ) { $update_type = $this->get_update_type_str( $assoc_args ); WP_CLI::success( "WP-CLI is at the latest{$update_type}version." ); return; } $newest = $updates[0]; WP_CLI::confirm( sprintf( 'You have version %s. Would you like to update to %s?', WP_CLI_VERSION, $newest['version'] ), $assoc_args ); $download_url = $newest['package_url']; $md5_url = str_replace( '.phar', '.phar.md5', $download_url ); } WP_CLI::log( sprintf( 'Downloading from %s...', $download_url ) ); $temp = \WP_CLI\Utils\get_temp_dir() . uniqid( 'wp_', true ) . '.phar'; $headers = array(); $options = array( 'timeout' => 600, // 10 minutes ought to be enough for everybody. 'filename' => $temp, ); Utils\http_request( 'GET', $download_url, null, $headers, $options ); $md5_response = Utils\http_request( 'GET', $md5_url ); if ( '20' !== substr( $md5_response->status_code, 0, 2 ) ) { WP_CLI::error( "Couldn't access md5 hash for release (HTTP code {$md5_response->status_code})." ); } $md5_file = md5_file( $temp ); $release_hash = trim( $md5_response->body ); if ( $md5_file === $release_hash ) { WP_CLI::log( 'md5 hash verified: ' . $release_hash ); } else { WP_CLI::error( "md5 hash for download ({$md5_file}) is different than the release hash ({$release_hash})." ); } $allow_root = WP_CLI::get_runner()->config['allow-root'] ? '--allow-root' : ''; $php_binary = Utils\get_php_binary(); $process = WP_CLI\Process::create( "{$php_binary} $temp --info {$allow_root}" ); $result = $process->run(); if ( 0 !== $result->return_code || false === stripos( $result->stdout, 'WP-CLI version' ) ) { $multi_line = explode( PHP_EOL, $result->stderr ); WP_CLI::error_multi_line( $multi_line ); WP_CLI::error( 'The downloaded PHAR is broken, try running wp cli update again.' ); } WP_CLI::log( 'New version works. Proceeding to replace.' ); $mode = fileperms( $old_phar ) & 511; if ( false === chmod( $temp, $mode ) ) { WP_CLI::error( sprintf( 'Cannot chmod %s.', $temp ) ); } class_exists( '\cli\Colors' ); // This autoloads \cli\Colors - after we move the file we no longer have access to this class. if ( false === rename( $temp, $old_phar ) ) { WP_CLI::error( sprintf( 'Cannot move %s to %s', $temp, $old_phar ) ); } if ( Utils\get_flag_value( $assoc_args, 'nightly' ) ) { $updated_version = 'the latest nightly release'; } elseif ( Utils\get_flag_value( $assoc_args, 'stable' ) ) { $updated_version = 'the latest stable release'; } else { $updated_version = $newest['version']; } WP_CLI::success( sprintf( 'Updated WP-CLI to %s.', $updated_version ) ); } /** * Returns update information. */ private function get_updates( $assoc_args ) { $url = 'https://api.github.com/repos/wp-cli/wp-cli/releases?per_page=100'; $options = array( 'timeout' => 30, ); $headers = array( 'Accept' => 'application/json', ); $github_token = getenv( 'GITHUB_TOKEN' ); if ( false !== $github_token ) { $headers['Authorization'] = 'token ' . $github_token; } $response = Utils\http_request( 'GET', $url, null, $headers, $options ); if ( ! $response->success || 200 !== $response->status_code ) { WP_CLI::error( sprintf( 'Failed to get latest version (HTTP code %d).', $response->status_code ) ); } $release_data = json_decode( $response->body ); $updates = array( 'major' => false, 'minor' => false, 'patch' => false, ); foreach ( $release_data as $release ) { // Get rid of leading "v" if there is one set. $release_version = $release->tag_name; if ( 'v' === substr( $release_version, 0, 1 ) ) { $release_version = ltrim( $release_version, 'v' ); } $update_type = Utils\get_named_sem_ver( $release_version, WP_CLI_VERSION ); if ( ! $update_type ) { continue; } if ( ! isset( $release->assets[0]->browser_download_url ) ) { continue; } if ( ! empty( $updates[ $update_type ] ) && ! Comparator::greaterThan( $release_version, $updates[ $update_type ]['version'] ) ) { continue; } $updates[ $update_type ] = array( 'version' => $release_version, 'update_type' => $update_type, 'package_url' => $release->assets[0]->browser_download_url, ); } foreach ( $updates as $type => $value ) { if ( empty( $value ) ) { unset( $updates[ $type ] ); } } foreach ( array( 'major', 'minor', 'patch' ) as $type ) { if ( true === \WP_CLI\Utils\get_flag_value( $assoc_args, $type ) ) { return ! empty( $updates[ $type ] ) ? array( $updates[ $type ] ) : false; } } if ( empty( $updates ) && preg_match( '#-alpha-(.+)$#', WP_CLI_VERSION, $matches ) ) { $version_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/NIGHTLY_VERSION'; $response = Utils\http_request( 'GET', $version_url ); if ( ! $response->success || 200 !== $response->status_code ) { WP_CLI::error( sprintf( 'Failed to get current nightly version (HTTP code %d)', $response->status_code ) ); } $nightly_version = trim( $response->body ); if ( WP_CLI_VERSION !== $nightly_version ) { $updates['nightly'] = array( 'version' => $nightly_version, 'update_type' => 'nightly', 'package_url' => 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar', ); } } return array_values( $updates ); } /** * Dumps the list of global parameters, as JSON or in var_export format. * * ## OPTIONS * * [--with-values] * : Display current values also. * * [--format=] * : Render output in a particular format. * --- * default: json * options: * - var_export * - json * --- * * ## EXAMPLES * * # Dump the list of global parameters. * $ wp cli param-dump --format=var_export * array ( * 'path' => * array ( * 'runtime' => '=', * 'file' => '', * 'synopsis' => '', * 'default' => NULL, * 'multiple' => false, * 'desc' => 'Path to the WordPress files.', * ), * 'url' => * array ( * * @subcommand param-dump */ public function param_dump( $_, $assoc_args ) { $spec = \WP_CLI::get_configurator()->get_spec(); if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'with-values' ) ) { $config = \WP_CLI::get_configurator()->to_array(); // Copy current config values to $spec foreach ( $spec as $key => $value ) { $current = null; if ( isset( $config[0][ $key ] ) ) { $current = $config[0][ $key ]; } $spec[ $key ]['current'] = $current; } } if ( 'var_export' === \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ) ) { var_export( $spec ); } else { echo json_encode( $spec ); } } /** * Dumps the list of installed commands, as JSON. * * ## EXAMPLES * * # Dump the list of installed commands. * $ wp cli cmd-dump * {"name":"wp","description":"Manage WordPress through the command-line.","longdesc":"\n\n## GLOBAL PARAMETERS\n\n --path=\n Path to the WordPress files.\n\n --ssh=\n Perform operation against a remote server over SSH (or a container using scheme of "docker" or "docker-compose").\n\n --url=\n Pretend request came from given URL. In multisite, this argument is how the target site is specified. \n\n --user=\n * * @subcommand cmd-dump */ public function cmd_dump() { echo json_encode( $this->command_to_array( WP_CLI::get_root_command() ) ); } /** * Generates tab completion strings. * * ## OPTIONS * * --line= * : The current command line to be executed. * * --point= * : The index to the current cursor position relative to the beginning of the command. * * ## EXAMPLES * * # Generate tab completion strings. * $ wp cli completions --line='wp eva' --point=100 * eval * eval-file */ public function completions( $_, $assoc_args ) { $line = substr( $assoc_args['line'], 0, $assoc_args['point'] ); $compl = new \WP_CLI\Completions( $line ); $compl->render(); } /** * Get a string representing the type of update being checked for. */ private function get_update_type_str( $assoc_args ) { $update_type = ' '; foreach ( array( 'major', 'minor', 'patch' ) as $type ) { if ( true === \WP_CLI\Utils\get_flag_value( $assoc_args, $type ) ) { $update_type = ' ' . $type . ' '; break; } } return $update_type; } /** * Detects if a command exists * * This commands checks if a command is registered with WP-CLI. * If the command is found then it returns with exit status 0. * If the command doesn't exist, then it will exit with status 1. * * ## OPTIONS * ... * : The command * * ## EXAMPLES * * # The "site delete" command is registered. * $ wp cli has-command "site delete" * $ echo $? * 0 * * # The "foo bar" command is not registered. * $ wp cli has-command "foo bar" * $ echo $? * 1 * * @subcommand has-command * * @when after_wp_load */ public function has_command( $_, $assoc_args ) { // If command is input as a string, then explode it into array. $command = explode( ' ', implode( ' ', $_ ) ); WP_CLI::halt( is_array( WP_CLI::get_runner()->find_command_to_run( $command ) ) ? 0 : 1 ); } } error ) ) { wp_die( $wpdb->error ); } // Set the database table prefix and the format specifiers for database table columns. $GLOBALS['table_prefix'] = $table_prefix; wp_set_wpdb_vars(); // Start the WordPress object cache, or an external object cache if the drop-in is present. wp_start_object_cache(); // Attach the default filters. require ABSPATH . WPINC . '/default-filters.php'; // Initialize multisite if enabled. if ( is_multisite() ) { Utils\maybe_require( '4.6-alpha-37575', ABSPATH . WPINC . '/class-wp-site-query.php' ); Utils\maybe_require( '4.6-alpha-37896', ABSPATH . WPINC . '/class-wp-network-query.php' ); require ABSPATH . WPINC . '/ms-blogs.php'; require ABSPATH . WPINC . '/ms-settings.php'; } elseif ( ! defined( 'MULTISITE' ) ) { define( 'MULTISITE', false ); } register_shutdown_function( 'shutdown_action_hook' ); // Stop most of WordPress from being loaded if we just want the basics. if ( SHORTINIT ) { return false; } // Load the L10n library. require_once ABSPATH . WPINC . '/l10n.php'; // WP-CLI: Permit Utils\wp_not_installed() to run on < WP 4.0 apply_filters( 'nocache_headers', array() ); // Run the installer if WordPress is not installed. wp_not_installed(); // Load most of WordPress. require ABSPATH . WPINC . '/class-wp-walker.php'; require ABSPATH . WPINC . '/class-wp-ajax-response.php'; require ABSPATH . WPINC . '/formatting.php'; require ABSPATH . WPINC . '/capabilities.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-roles.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-role.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-user.php' ); require ABSPATH . WPINC . '/query.php'; Utils\maybe_require( '3.7-alpha-25139', ABSPATH . WPINC . '/date.php' ); require ABSPATH . WPINC . '/theme.php'; require ABSPATH . WPINC . '/class-wp-theme.php'; require ABSPATH . WPINC . '/template.php'; require ABSPATH . WPINC . '/user.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-user-query.php' ); Utils\maybe_require( '4.0', ABSPATH . WPINC . '/session.php' ); require ABSPATH . WPINC . '/meta.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-meta-query.php' ); Utils\maybe_require( '4.5-alpha-35776', ABSPATH . WPINC . '/class-wp-metadata-lazyloader.php' ); require ABSPATH . WPINC . '/general-template.php'; require ABSPATH . WPINC . '/link-template.php'; require ABSPATH . WPINC . '/author-template.php'; require ABSPATH . WPINC . '/post.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-walker-page.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-walker-page-dropdown.php' ); Utils\maybe_require( '4.6-alpha-37890', ABSPATH . WPINC . '/class-wp-post-type.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-post.php' ); require ABSPATH . WPINC . '/post-template.php'; Utils\maybe_require( '3.6-alpha-23451', ABSPATH . WPINC . '/revision.php' ); Utils\maybe_require( '3.6-alpha-23451', ABSPATH . WPINC . '/post-formats.php' ); require ABSPATH . WPINC . '/post-thumbnail-template.php'; require ABSPATH . WPINC . '/category.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-walker-category.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-walker-category-dropdown.php' ); require ABSPATH . WPINC . '/category-template.php'; require ABSPATH . WPINC . '/comment.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-comment.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-comment-query.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-walker-comment.php' ); require ABSPATH . WPINC . '/comment-template.php'; require ABSPATH . WPINC . '/rewrite.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-rewrite.php' ); require ABSPATH . WPINC . '/feed.php'; require ABSPATH . WPINC . '/bookmark.php'; require ABSPATH . WPINC . '/bookmark-template.php'; require ABSPATH . WPINC . '/kses.php'; require ABSPATH . WPINC . '/cron.php'; require ABSPATH . WPINC . '/deprecated.php'; require ABSPATH . WPINC . '/script-loader.php'; require ABSPATH . WPINC . '/taxonomy.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-term.php' ); Utils\maybe_require( '4.6-alpha-37575', ABSPATH . WPINC . '/class-wp-term-query.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-tax-query.php' ); require ABSPATH . WPINC . '/update.php'; require ABSPATH . WPINC . '/canonical.php'; require ABSPATH . WPINC . '/shortcodes.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/embed.php' ); require ABSPATH . WPINC . '/class-wp-embed.php'; require ABSPATH . WPINC . '/media.php'; Utils\maybe_require( '4.4-alpha-34903', ABSPATH . WPINC . '/class-wp-oembed-controller.php' ); require ABSPATH . WPINC . '/http.php'; require_once ABSPATH . WPINC . '/class-http.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-streams.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-curl.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-proxy.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-cookie.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-encoding.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-http-response.php' ); Utils\maybe_require( '4.6-alpha-37438', ABSPATH . WPINC . '/class-wp-http-requests-response.php' ); require ABSPATH . WPINC . '/widgets.php'; Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-widget.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/class-wp-widget-factory.php' ); require ABSPATH . WPINC . '/nav-menu.php'; require ABSPATH . WPINC . '/nav-menu-template.php'; require ABSPATH . WPINC . '/admin-bar.php'; Utils\maybe_require( '4.4-alpha-34928', ABSPATH . WPINC . '/rest-api.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/rest-api/class-wp-rest-server.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/rest-api/class-wp-rest-response.php' ); Utils\maybe_require( '4.4-beta4-35719', ABSPATH . WPINC . '/rest-api/class-wp-rest-request.php' ); // Load multisite-specific files. if ( is_multisite() ) { require ABSPATH . WPINC . '/ms-functions.php'; require ABSPATH . WPINC . '/ms-default-filters.php'; require ABSPATH . WPINC . '/ms-deprecated.php'; } // Define constants that rely on the API to obtain the default value. // Define must-use plugin directory constants, which may be overridden in the sunrise.php drop-in. wp_plugin_directory_constants(); $symlinked_plugins_supported = function_exists( 'wp_register_plugin_realpath' ); if ( $symlinked_plugins_supported ) { $GLOBALS['wp_plugin_paths'] = array(); } // Load must-use plugins. foreach ( wp_get_mu_plugins() as $mu_plugin ) { include_once $mu_plugin; } unset( $mu_plugin ); // Load network activated plugins. if ( is_multisite() ) { foreach ( wp_get_active_network_plugins() as $network_plugin ) { if ( $symlinked_plugins_supported ) { wp_register_plugin_realpath( $network_plugin ); } include_once $network_plugin; } unset( $network_plugin ); } do_action( 'muplugins_loaded' ); if ( is_multisite() ) { ms_cookie_constants(); } // Define constants after multisite is loaded. Cookie-related constants may be overridden in ms_network_cookies(). wp_cookie_constants(); // Define and enforce our SSL constants. wp_ssl_constants(); // Create common globals. require ABSPATH . WPINC . '/vars.php'; // Make taxonomies and posts available to plugins and themes. // @plugin authors: warning: these get registered again on the init hook. create_initial_taxonomies(); create_initial_post_types(); // Register the default theme directory root register_theme_directory( get_theme_root() ); // Load active plugins. foreach ( wp_get_active_and_valid_plugins() as $plugin ) { if ( $symlinked_plugins_supported ) { wp_register_plugin_realpath( $plugin ); } include_once $plugin; } unset( $plugin, $symlinked_plugins_supported ); // Load pluggable functions. require ABSPATH . WPINC . '/pluggable.php'; require ABSPATH . WPINC . '/pluggable-deprecated.php'; // Set internal encoding. wp_set_internal_encoding(); // Run wp_cache_postload() if object cache is enabled and the function exists. if ( WP_CACHE && function_exists( 'wp_cache_postload' ) ) { wp_cache_postload(); } do_action( 'plugins_loaded' ); // Define constants which affect functionality if not already defined. wp_functionality_constants(); // Add magic quotes and set up $_REQUEST ( $_GET + $_POST ) wp_magic_quotes(); do_action( 'sanitize_comment_cookies' ); /** * WordPress Query object * @global object $wp_the_query * @since 2.0.0 */ $GLOBALS['wp_the_query'] = new WP_Query(); /** * Holds the reference to @see $wp_the_query * Use this global for WordPress queries * @global object $wp_query * @since 1.5.0 */ $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; /** * Holds the WordPress Rewrite object for creating pretty URLs * @global object $wp_rewrite * @since 1.5.0 */ $GLOBALS['wp_rewrite'] = new WP_Rewrite(); /** * WordPress Object * @global object $wp * @since 2.0.0 */ $GLOBALS['wp'] = new WP(); /** * WordPress Widget Factory Object * @global object $wp_widget_factory * @since 2.8.0 */ $GLOBALS['wp_widget_factory'] = new WP_Widget_Factory(); /** * WordPress User Roles * @global object $wp_roles * @since 2.0.0 */ $GLOBALS['wp_roles'] = new WP_Roles(); do_action( 'setup_theme' ); // Define the template related constants. wp_templating_constants(); // Load the default text localization domain. load_default_textdomain(); $locale = get_locale(); $locale_file = WP_LANG_DIR . "/$locale.php"; if ( ( 0 === validate_file( $locale ) ) && is_readable( $locale_file ) ) { require $locale_file; } unset( $locale_file ); // Pull in locale data after loading text domain. require_once ABSPATH . WPINC . '/locale.php'; /** * WordPress Locale object for loading locale domain date and various strings. * @global object $wp_locale * @since 2.1.0 */ $GLOBALS['wp_locale'] = new WP_Locale(); // Load the functions for the active theme, for both parent and child theme if applicable. // phpcs:disable WordPress.WP.DiscouragedConstants.STYLESHEETPATHUsageFound,WordPress.WP.DiscouragedConstants.TEMPLATEPATHUsageFound global $pagenow; if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) { if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) ) { include STYLESHEETPATH . '/functions.php'; } if ( file_exists( TEMPLATEPATH . '/functions.php' ) ) { include TEMPLATEPATH . '/functions.php'; } } // phpcs:enable WordPress.WP.DiscouragedConstants do_action( 'after_setup_theme' ); // Set up current user. $GLOBALS['wp']->init(); /** * Most of WP is loaded at this stage, and the user is authenticated. WP continues * to load on the init hook that follows (e.g. widgets), and many plugins instantiate * themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.). * * If you wish to plug an action once WP is loaded, use the wp_loaded hook below. */ do_action( 'init' ); // Check site status # if ( is_multisite() ) { // WP-CLI if ( is_multisite() && ! defined( 'WP_INSTALLING' ) ) { $file = ms_site_check(); if ( true !== $file ) { require $file; die(); } unset( $file ); } /** * This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated. * * AJAX requests should use wp-admin/admin-ajax.php. admin-ajax.php can handle requests for * users not logged in. * * @link http://codex.wordpress.org/AJAX_in_Plugins * * @since 3.0.0 */ do_action( 'wp_loaded' ); clean(); } ); } } return $cache; } /** * Set the context in which WP-CLI should be run */ public static function set_url( $url ) { self::debug( 'Set URL: ' . $url, 'bootstrap' ); $url_parts = Utils\parse_url( $url ); self::set_url_params( $url_parts ); } private static function set_url_params( $url_parts ) { $f = function( $key ) use ( $url_parts ) { return \WP_CLI\Utils\get_flag_value( $url_parts, $key, '' ); }; if ( isset( $url_parts['host'] ) ) { if ( isset( $url_parts['scheme'] ) && 'https' === strtolower( $url_parts['scheme'] ) ) { $_SERVER['HTTPS'] = 'on'; } $_SERVER['HTTP_HOST'] = $url_parts['host']; if ( isset( $url_parts['port'] ) ) { $_SERVER['HTTP_HOST'] .= ':' . $url_parts['port']; } $_SERVER['SERVER_NAME'] = $url_parts['host']; } $_SERVER['REQUEST_URI'] = $f( 'path' ) . ( isset( $url_parts['query'] ) ? '?' . $url_parts['query'] : '' ); $_SERVER['SERVER_PORT'] = \WP_CLI\Utils\get_flag_value( $url_parts, 'port', '80' ); $_SERVER['QUERY_STRING'] = $f( 'query' ); } /** * @return WpHttpCacheManager */ public static function get_http_cache_manager() { static $http_cacher; if ( ! $http_cacher ) { $http_cacher = new WpHttpCacheManager( self::get_cache() ); } return $http_cacher; } /** * Colorize a string for output. * * Yes, you can change the color of command line text too. For instance, * here's how `WP_CLI::success()` colorizes "Success: " * * ``` * WP_CLI::colorize( "%GSuccess:%n " ) * ``` * * Uses `\cli\Colors::colorize()` to transform color tokens to display * settings. Choose from the following tokens (and note 'reset'): * * * %y => ['color' => 'yellow'], * * %g => ['color' => 'green'], * * %b => ['color' => 'blue'], * * %r => ['color' => 'red'], * * %p => ['color' => 'magenta'], * * %m => ['color' => 'magenta'], * * %c => ['color' => 'cyan'], * * %w => ['color' => 'grey'], * * %k => ['color' => 'black'], * * %n => ['color' => 'reset'], * * %Y => ['color' => 'yellow', 'style' => 'bright'], * * %G => ['color' => 'green', 'style' => 'bright'], * * %B => ['color' => 'blue', 'style' => 'bright'], * * %R => ['color' => 'red', 'style' => 'bright'], * * %P => ['color' => 'magenta', 'style' => 'bright'], * * %M => ['color' => 'magenta', 'style' => 'bright'], * * %C => ['color' => 'cyan', 'style' => 'bright'], * * %W => ['color' => 'grey', 'style' => 'bright'], * * %K => ['color' => 'black', 'style' => 'bright'], * * %N => ['color' => 'reset', 'style' => 'bright'], * * %3 => ['background' => 'yellow'], * * %2 => ['background' => 'green'], * * %4 => ['background' => 'blue'], * * %1 => ['background' => 'red'], * * %5 => ['background' => 'magenta'], * * %6 => ['background' => 'cyan'], * * %7 => ['background' => 'grey'], * * %0 => ['background' => 'black'], * * %F => ['style' => 'blink'], * * %U => ['style' => 'underline'], * * %8 => ['style' => 'inverse'], * * %9 => ['style' => 'bright'], * * %_ => ['style' => 'bright'] * * @access public * @category Output * * @param string $string String to colorize for output, with color tokens. * @return string Colorized string. */ public static function colorize( $string ) { return \cli\Colors::colorize( $string, self::get_runner()->in_color() ); } /** * Schedule a callback to be executed at a certain point. * * Hooks conceptually are very similar to WordPress actions. WP-CLI hooks * are typically called before WordPress is loaded. * * WP-CLI hooks include: * * * `before_add_command:` - Before the command is added. * * `after_add_command:` - After the command was added. * * `before_invoke:` - Just before a command is invoked. * * `after_invoke:` - Just after a command is invoked. * * `find_command_to_run_pre` - Just before WP-CLI finds the command to run. * * `before_wp_load` - Just before the WP load process begins. * * `before_wp_config_load` - After wp-config.php has been located. * * `after_wp_config_load` - After wp-config.php has been loaded into scope. * * `after_wp_load` - Just after the WP load process has completed. * * `before_run_command` - Just before the command is executed. * * WP-CLI commands can create their own hooks with `WP_CLI::do_hook()`. * * If additional arguments are passed through the `WP_CLI::do_hook()` call, * these will be passed on to the callback provided by `WP_CLI::add_hook()`. * * ``` * # `wp network meta` confirms command is executing in multisite context. * WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array( * 'before_invoke' => function () { * if ( !is_multisite() ) { * WP_CLI::error( 'This is not a multisite installation.' ); * } * } * ) ); * ``` * * @access public * @category Registration * * @param string $when Identifier for the hook. * @param mixed $callback Callback to execute when hook is called. * @return null */ public static function add_hook( $when, $callback ) { if ( array_key_exists( $when, self::$hooks_passed ) ) { self::debug( sprintf( 'Immediately invoking on passed hook "%s": %s', $when, Utils\describe_callable( $callback ) ), 'hooks' ); call_user_func_array( $callback, (array) self::$hooks_passed[ $when ] ); } self::$hooks[ $when ][] = $callback; } /** * Execute callbacks registered to a given hook. * * See `WP_CLI::add_hook()` for details on WP-CLI's internal hook system. * Commands can provide and call their own hooks. * * @access public * @category Registration * * @param string $when Identifier for the hook. * @param mixed ... Optional. Arguments that will be passed onto the * callback provided by `WP_CLI::add_hook()`. * @return null */ public static function do_hook( $when ) { $args = func_num_args() > 1 ? array_slice( func_get_args(), 1 ) : array(); self::$hooks_passed[ $when ] = $args; if ( ! isset( self::$hooks[ $when ] ) ) { return; } self::debug( sprintf( 'Processing hook "%s" with %d callbacks', $when, count( self::$hooks[ $when ] ) ), 'hooks' ); foreach ( self::$hooks[ $when ] as $callback ) { self::debug( sprintf( 'On hook "%s": %s', $when, Utils\describe_callable( $callback ) ), 'hooks' ); call_user_func_array( $callback, $args ); } } /** * Add a callback to a WordPress action or filter. * * `add_action()` without needing access to `add_action()`. If WordPress is * already loaded though, you should use `add_action()` (and `add_filter()`) * instead. * * @access public * @category Registration * * @param string $tag Named WordPress action or filter. * @param mixed $function_to_add Callable to execute when the action or filter is evaluated. * @param integer $priority Priority to add the callback as. * @param integer $accepted_args Number of arguments to pass to callback. * @return true */ public static function add_wp_hook( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters; if ( function_exists( 'add_filter' ) ) { add_filter( $tag, $function_to_add, $priority, $accepted_args ); } else { $idx = self::wp_hook_build_unique_id( $tag, $function_to_add, $priority ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- This is intentional & the purpose of this function. $wp_filter[ $tag ][ $priority ][ $idx ] = array( 'function' => $function_to_add, 'accepted_args' => $accepted_args, ); unset( $merged_filters[ $tag ] ); } return true; } /** * Build Unique ID for storage and retrieval. * * Essentially _wp_filter_build_unique_id() without needing access to _wp_filter_build_unique_id() */ private static function wp_hook_build_unique_id( $tag, $function, $priority ) { global $wp_filter; static $filter_id_count = 0; if ( is_string( $function ) ) { return $function; } if ( is_object( $function ) ) { // Closures are currently implemented as objects $function = array( $function, '' ); } else { $function = (array) $function; } if ( is_object( $function[0] ) ) { // Object Class Calling if ( function_exists( 'spl_object_hash' ) ) { return spl_object_hash( $function[0] ) . $function[1]; } $obj_idx = get_class( $function[0] ) . $function[1]; if ( ! isset( $function[0]->wp_filter_id ) ) { if ( false === $priority ) { return false; } $obj_idx .= isset( $wp_filter[ $tag ][ $priority ] ) ? count( (array) $wp_filter[ $tag ][ $priority ] ) : $filter_id_count; $function[0]->wp_filter_id = $filter_id_count; ++$filter_id_count; } else { $obj_idx .= $function[0]->wp_filter_id; } return $obj_idx; } if ( is_string( $function[0] ) ) { // Static Calling return $function[0] . '::' . $function[1]; } } /** * Register a command to WP-CLI. * * WP-CLI supports using any callable class, function, or closure as a * command. `WP_CLI::add_command()` is used for both internal and * third-party command registration. * * Command arguments are parsed from PHPDoc by default, but also can be * supplied as an optional third argument during registration. * * ``` * # Register a custom 'foo' command to output a supplied positional param. * # * # $ wp foo bar --append=qux * # Success: bar qux * * /** * * My awesome closure command * * * * * * : An awesome message to display * * * * --append= * * : An awesome message to append to the original message. * * * * @when before_wp_load * *\/ * $foo = function( $args, $assoc_args ) { * WP_CLI::success( $args[0] . ' ' . $assoc_args['append'] ); * }; * WP_CLI::add_command( 'foo', $foo ); * ``` * * @access public * @category Registration * * @param string $name Name for the command (e.g. "post list" or "site empty"). * @param callable $callable Command implementation as a class, function or closure. * @param array $args { * Optional. An associative array with additional registration parameters. * * @type callable $before_invoke Callback to execute before invoking the command. * @type callable $after_invoke Callback to execute after invoking the command. * @type string $shortdesc Short description (80 char or less) for the command. * @type string $longdesc Description of arbitrary length for examples, etc. * @type string $synopsis The synopsis for the command (string or array). * @type string $when Execute callback on a named WP-CLI hook (e.g. before_wp_load). * @type bool $is_deferred Whether the command addition had already been deferred. * } * @return bool True on success, false if deferred, hard error if registration failed. */ public static function add_command( $name, $callable, $args = array() ) { // Bail immediately if the WP-CLI executable has not been run. if ( ! defined( 'WP_CLI' ) ) { return false; } $valid = false; if ( is_callable( $callable ) ) { $valid = true; } elseif ( is_string( $callable ) && class_exists( (string) $callable ) ) { $valid = true; } elseif ( is_object( $callable ) ) { $valid = true; } if ( ! $valid ) { if ( is_array( $callable ) ) { $callable[0] = is_object( $callable[0] ) ? get_class( $callable[0] ) : $callable[0]; $callable = array( $callable[0], $callable[1] ); } self::error( sprintf( 'Callable %s does not exist, and cannot be registered as `wp %s`.', json_encode( $callable ), $name ) ); } $addition = new Dispatcher\CommandAddition(); self::do_hook( "before_add_command:{$name}", $addition ); if ( $addition->was_aborted() ) { self::warning( "Aborting the addition of the command '{$name}' with reason: {$addition->get_reason()}." ); return false; } foreach ( array( 'before_invoke', 'after_invoke' ) as $when ) { if ( isset( $args[ $when ] ) ) { self::add_hook( "{$when}:{$name}", $args[ $when ] ); } } $path = preg_split( '/\s+/', $name ); $leaf_name = array_pop( $path ); $full_path = $path; $command = self::get_root_command(); while ( ! empty( $path ) ) { $subcommand_name = $path[0]; $parent = implode( ' ', $path ); $subcommand = $command->find_subcommand( $path ); // Parent not found. Defer addition or create an empty container as // needed. if ( ! $subcommand ) { if ( isset( $args['is_deferred'] ) && $args['is_deferred'] ) { $subcommand = new Dispatcher\CompositeCommand( $command, $subcommand_name, new \WP_CLI\DocParser( '' ) ); self::debug( "Adding empty container for deferred command: {$name}", 'commands' ); $command->add_subcommand( $subcommand_name, $subcommand ); } else { self::debug( "Deferring command: {$name}", 'commands' ); self::defer_command_addition( $name, $parent, $callable, $args ); return false; } } $command = $subcommand; } $leaf_command = Dispatcher\CommandFactory::create( $leaf_name, $callable, $command ); // Only add a command namespace if the command itself does not exist yet. if ( $leaf_command instanceof Dispatcher\CommandNamespace && array_key_exists( $leaf_name, $command->get_subcommands() ) ) { return false; } // Reattach commands attached to namespace to real command. $subcommand_name = (array) $leaf_name; $existing_command = $command->find_subcommand( $subcommand_name ); if ( false !== $existing_command ) { $subcommands = $existing_command->get_subcommands(); if ( ! empty( $subcommands ) && ( $leaf_command instanceof Dispatcher\CompositeCommand || $leaf_command->can_have_subcommands ) ) { foreach ( $subcommands as $subname => $subcommand ) { $leaf_command->add_subcommand( $subname, $subcommand ); } } } /** @var $leaf_command Dispatcher\Subcommand|Dispatcher\CompositeCommand|Dispatcher\CommandNamespace */ if ( ! $command->can_have_subcommands() ) { throw new Exception( sprintf( "'%s' can't have subcommands.", implode( ' ', Dispatcher\get_path( $command ) ) ) ); } if ( isset( $args['shortdesc'] ) ) { $leaf_command->set_shortdesc( $args['shortdesc'] ); } if ( isset( $args['longdesc'] ) ) { $leaf_command->set_longdesc( $args['longdesc'] ); } if ( isset( $args['synopsis'] ) ) { if ( is_string( $args['synopsis'] ) ) { $leaf_command->set_synopsis( $args['synopsis'] ); } elseif ( is_array( $args['synopsis'] ) ) { $synopsis = \WP_CLI\SynopsisParser::render( $args['synopsis'] ); $leaf_command->set_synopsis( $synopsis ); $long_desc = ''; $bits = explode( ' ', $synopsis ); foreach ( $args['synopsis'] as $key => $arg ) { $long_desc .= $bits[ $key ] . "\n"; if ( ! empty( $arg['description'] ) ) { $long_desc .= ': ' . $arg['description'] . "\n"; } $yamlify = array(); foreach ( array( 'default', 'options' ) as $key ) { if ( isset( $arg[ $key ] ) ) { $yamlify[ $key ] = $arg[ $key ]; } } if ( ! empty( $yamlify ) ) { $long_desc .= Spyc::YAMLDump( $yamlify ); $long_desc .= '---' . "\n"; } $long_desc .= "\n"; } if ( ! empty( $long_desc ) ) { $long_desc = rtrim( $long_desc, "\r\n" ); $long_desc = '## OPTIONS' . "\n\n" . $long_desc; if ( ! empty( $args['longdesc'] ) ) { $long_desc .= "\n\n" . ltrim( $args['longdesc'], "\r\n" ); } $leaf_command->set_longdesc( $long_desc ); } } } if ( isset( $args['when'] ) ) { self::get_runner()->register_early_invoke( $args['when'], $leaf_command ); } if ( ! empty( $parent ) ) { $sub_command = trim( str_replace( $parent, '', $name ) ); self::debug( "Adding command: {$sub_command} in {$parent} Namespace", 'commands' ); } else { self::debug( "Adding command: {$name}", 'commands' ); } $command->add_subcommand( $leaf_name, $leaf_command ); self::do_hook( "after_add_command:{$name}" ); return true; } /** * Defer command addition for a sub-command if the parent command is not yet * registered. * * @param string $name Name for the sub-command. * @param string $parent Name for the parent command. * @param string $callable Command implementation as a class, function or closure. * @param array $args Optional. See `WP_CLI::add_command()` for details. */ private static function defer_command_addition( $name, $parent, $callable, $args = array() ) { $args['is_deferred'] = true; self::$deferred_additions[ $name ] = array( 'parent' => $parent, 'callable' => $callable, 'args' => $args, ); self::add_hook( "after_add_command:$parent", function () use ( $name ) { $deferred_additions = WP_CLI::get_deferred_additions(); if ( ! array_key_exists( $name, $deferred_additions ) ) { return; } $callable = $deferred_additions[ $name ]['callable']; $args = $deferred_additions[ $name ]['args']; WP_CLI::remove_deferred_addition( $name ); WP_CLI::add_command( $name, $callable, $args ); } ); } /** * Get the list of outstanding deferred command additions. * * @return array Array of outstanding command additions. */ public static function get_deferred_additions() { return self::$deferred_additions; } /** * Remove a command addition from the list of outstanding deferred additions. */ public static function remove_deferred_addition( $name ) { if ( ! array_key_exists( $name, self::$deferred_additions ) ) { self::warning( "Trying to remove a non-existent command addition '{$name}'." ); } unset( self::$deferred_additions[ $name ] ); } /** * Display informational message without prefix, and ignore `--quiet`. * * Message is written to STDOUT. `WP_CLI::log()` is typically recommended; * `WP_CLI::line()` is included for historical compat. * * @access public * @category Output * * @param string $message Message to display to the end user. * @return null */ public static function line( $message = '' ) { echo $message . "\n"; } /** * Display informational message without prefix. * * Message is written to STDOUT, or discarded when `--quiet` flag is supplied. * * ``` * # `wp cli update` lets user know of each step in the update process. * WP_CLI::log( sprintf( 'Downloading from %s...', $download_url ) ); * ``` * * @access public * @category Output * * @param string $message Message to write to STDOUT. */ public static function log( $message ) { self::$logger->info( $message ); } /** * Display success message prefixed with "Success: ". * * Success message is written to STDOUT. * * Typically recommended to inform user of successful script conclusion. * * ``` * # wp rewrite flush expects 'rewrite_rules' option to be set after flush. * flush_rewrite_rules( \WP_CLI\Utils\get_flag_value( $assoc_args, 'hard' ) ); * if ( ! get_option( 'rewrite_rules' ) ) { * WP_CLI::warning( "Rewrite rules are empty." ); * } else { * WP_CLI::success( 'Rewrite rules flushed.' ); * } * ``` * * @access public * @category Output * * @param string $message Message to write to STDOUT. * @return null */ public static function success( $message ) { self::$logger->success( $message ); } /** * Display debug message prefixed with "Debug: " when `--debug` is used. * * Debug message is written to STDERR, and includes script execution time. * * Helpful for optionally showing greater detail when needed. Used throughout * WP-CLI bootstrap process for easier debugging and profiling. * * ``` * # Called in `WP_CLI\Runner::set_wp_root()`. * private static function set_wp_root( $path ) { * define( 'ABSPATH', Utils\trailingslashit( $path ) ); * WP_CLI::debug( 'ABSPATH defined: ' . ABSPATH ); * $_SERVER['DOCUMENT_ROOT'] = realpath( $path ); * } * * # Debug details only appear when `--debug` is used. * # $ wp --debug * # [...] * # Debug: ABSPATH defined: /srv/www/wordpress-develop.dev/src/ (0.225s) * ``` * * @access public * @category Output * * @param string $message Message to write to STDERR. * @param string|bool $group Organize debug message to a specific group. * Use `false` to not group the message. * @return null */ public static function debug( $message, $group = false ) { static $storage = array(); if ( ! self::$logger ) { $storage[] = array( $message, $group ); return; } if ( ! empty( $storage ) && self::$logger ) { foreach ( $storage as $entry ) { list( $stored_message, $stored_group ) = $entry; self::$logger->debug( self::error_to_string( $stored_message ), $stored_group ); } $storage = array(); } self::$logger->debug( self::error_to_string( $message ), $group ); } /** * Display warning message prefixed with "Warning: ". * * Warning message is written to STDERR. * * Use instead of `WP_CLI::debug()` when script execution should be permitted * to continue. * * ``` * # `wp plugin activate` skips activation when plugin is network active. * $status = $this->get_status( $plugin->file ); * // Network-active is the highest level of activation status * if ( 'active-network' === $status ) { * WP_CLI::warning( "Plugin '{$plugin->name}' is already network active." ); * continue; * } * ``` * * @access public * @category Output * * @param string $message Message to write to STDERR. * @return null */ public static function warning( $message ) { self::$logger->warning( self::error_to_string( $message ) ); } /** * Display error message prefixed with "Error: " and exit script. * * Error message is written to STDERR. Defaults to halting script execution * with return code 1. * * Use `WP_CLI::warning()` instead when script execution should be permitted * to continue. * * ``` * # `wp cache flush` considers flush failure to be a fatal error. * if ( false === wp_cache_flush() ) { * WP_CLI::error( 'The object cache could not be flushed.' ); * } * ``` * * @access public * @category Output * * @param string|WP_Error $message Message to write to STDERR. * @param boolean|integer $exit True defaults to exit(1). * @return null */ public static function error( $message, $exit = true ) { if ( ! isset( self::get_runner()->assoc_args['completions'] ) ) { self::$logger->error( self::error_to_string( $message ) ); } $return_code = false; if ( true === $exit ) { $return_code = 1; } elseif ( is_int( $exit ) && $exit >= 1 ) { $return_code = $exit; } if ( $return_code ) { if ( self::$capture_exit ) { throw new ExitException( null, $return_code ); } exit( $return_code ); } } /** * Halt script execution with a specific return code. * * Permits script execution to be overloaded by `WP_CLI::runcommand()` * * @access public * @category Output * * @param integer $return_code */ public static function halt( $return_code ) { if ( self::$capture_exit ) { throw new ExitException( null, $return_code ); } exit( $return_code ); } /** * Display a multi-line error message in a red box. Doesn't exit script. * * Error message is written to STDERR. * * @access public * @category Output * * @param array $message Multi-line error message to be displayed. */ public static function error_multi_line( $message_lines ) { if ( ! isset( self::get_runner()->assoc_args['completions'] ) && is_array( $message_lines ) ) { self::$logger->error_multi_line( array_map( array( __CLASS__, 'error_to_string' ), $message_lines ) ); } } /** * Ask for confirmation before running a destructive operation. * * If 'y' is provided to the question, the script execution continues. If * 'n' or any other response is provided to the question, script exits. * * ``` * # `wp db drop` asks for confirmation before dropping the database. * * WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args ); * ``` * * @access public * @category Input * * @param string $question Question to display before the prompt. * @param array $assoc_args Skips prompt if 'yes' is provided. */ public static function confirm( $question, $assoc_args = array() ) { if ( ! \WP_CLI\Utils\get_flag_value( $assoc_args, 'yes' ) ) { fwrite( STDOUT, $question . ' [y/n] ' ); $answer = strtolower( trim( fgets( STDIN ) ) ); if ( 'y' !== $answer ) { exit; } } } /** * Read value from a positional argument or from STDIN. * * @param array $args The list of positional arguments. * @param int $index At which position to check for the value. * * @return string */ public static function get_value_from_arg_or_stdin( $args, $index ) { if ( isset( $args[ $index ] ) ) { $raw_value = $args[ $index ]; } else { // We don't use file_get_contents() here because it doesn't handle // Ctrl-D properly, when typing in the value interactively. $raw_value = ''; while ( false !== ( $line = fgets( STDIN ) ) ) { $raw_value .= $line; } } return $raw_value; } /** * Read a value, from various formats. * * @access public * @category Input * * @param mixed $value * @param array $assoc_args */ public static function read_value( $raw_value, $assoc_args = array() ) { if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ) === 'json' ) { $value = json_decode( $raw_value, true ); if ( null === $value ) { self::error( sprintf( 'Invalid JSON: %s', $raw_value ) ); } } else { $value = $raw_value; } return $value; } /** * Display a value, in various formats * * @param mixed $value Value to display. * @param array $assoc_args Arguments passed to the command, determining format. */ public static function print_value( $value, $assoc_args = array() ) { if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ) === 'json' ) { $value = json_encode( $value ); } elseif ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ) === 'yaml' ) { $value = Spyc::YAMLDump( $value, 2, 0 ); } elseif ( is_array( $value ) || is_object( $value ) ) { $value = var_export( $value, true ); } echo $value . "\n"; } /** * Convert a wp_error into a string * * @param mixed $errors * @return string */ public static function error_to_string( $errors ) { if ( is_string( $errors ) ) { return $errors; } // Only json_encode() the data when it needs it $render_data = function( $data ) { if ( is_array( $data ) || is_object( $data ) ) { return json_encode( $data ); } return '"' . $data . '"'; }; if ( $errors instanceof \WP_Error ) { foreach ( $errors->get_error_messages() as $message ) { if ( $errors->get_error_data() ) { return $message . ' ' . $render_data( $errors->get_error_data() ); } return $message; } } } /** * Launch an arbitrary external process that takes over I/O. * * ``` * # `wp core download` falls back to the `tar` binary when PharData isn't available * if ( ! class_exists( 'PharData' ) ) { * $cmd = "tar xz --strip-components=1 --directory=%s -f $tarball"; * WP_CLI::launch( Utils\esc_cmd( $cmd, $dest ) ); * return; * } * ``` * * @access public * @category Execution * * @param string $command External process to launch. * @param boolean $exit_on_error Whether to exit if the command returns an elevated return code. * @param boolean $return_detailed Whether to return an exit status (default) or detailed execution results. * @return int|\WP_CLI\ProcessRun The command exit status, or a ProcessRun object for full details. */ public static function launch( $command, $exit_on_error = true, $return_detailed = false ) { Utils\check_proc_available( 'launch' ); $proc = Process::create( $command ); $results = $proc->run(); if ( -1 === $results->return_code ) { self::warning( "Spawned process returned exit code {$results->return_code}, which could be caused by a custom compiled version of PHP that uses the --enable-sigchild option." ); } if ( $results->return_code && $exit_on_error ) { exit( $results->return_code ); } if ( $return_detailed ) { return $results; } return $results->return_code; } /** * Run a WP-CLI command in a new process reusing the current runtime arguments. * * Use `WP_CLI::runcommand()` instead, which is easier to use and works better. * * Note: While this command does persist a limited set of runtime arguments, * it *does not* persist environment variables. Practically speaking, WP-CLI * packages won't be loaded when using WP_CLI::launch_self() because the * launched process doesn't have access to the current process $HOME. * * @access public * @category Execution * * @param string $command WP-CLI command to call. * @param array $args Positional arguments to include when calling the command. * @param array $assoc_args Associative arguments to include when calling the command. * @param bool $exit_on_error Whether to exit if the command returns an elevated return code. * @param bool $return_detailed Whether to return an exit status (default) or detailed execution results. * @param array $runtime_args Override one or more global args (path,url,user,allow-root) * @return int|\WP_CLI\ProcessRun The command exit status, or a ProcessRun instance */ public static function launch_self( $command, $args = array(), $assoc_args = array(), $exit_on_error = true, $return_detailed = false, $runtime_args = array() ) { $reused_runtime_args = array( 'path', 'url', 'user', 'allow-root', ); foreach ( $reused_runtime_args as $key ) { if ( isset( $runtime_args[ $key ] ) ) { $assoc_args[ $key ] = $runtime_args[ $key ]; continue; } $value = self::get_runner()->config[ $key ]; if ( $value ) { $assoc_args[ $key ] = $value; } } $php_bin = escapeshellarg( Utils\get_php_binary() ); $script_path = $GLOBALS['argv'][0]; if ( getenv( 'WP_CLI_CONFIG_PATH' ) ) { $config_path = getenv( 'WP_CLI_CONFIG_PATH' ); } else { $config_path = Utils\get_home_dir() . '/.wp-cli/config.yml'; } $config_path = escapeshellarg( $config_path ); $args = implode( ' ', array_map( 'escapeshellarg', $args ) ); $assoc_args = \WP_CLI\Utils\assoc_args_to_str( $assoc_args ); $full_command = "WP_CLI_CONFIG_PATH={$config_path} {$php_bin} {$script_path} {$command} {$args} {$assoc_args}"; return self::launch( $full_command, $exit_on_error, $return_detailed ); } /** * Get the path to the PHP binary used when executing WP-CLI. * * Environment values permit specific binaries to be indicated. * * Note: moved to Utils, left for BC. * * @access public * @category System * * @return string */ public static function get_php_binary() { return Utils\get_php_binary(); } /** * Confirm that a global configuration parameter does exist. * * @access public * @category Input * * @param string $key Config parameter key to check. * * @return bool */ public static function has_config( $key ) { return array_key_exists( $key, self::get_runner()->config ); } /** * Get values of global configuration parameters. * * Provides access to `--path=`, `--url=`, and other values of * the [global configuration parameters](https://wp-cli.org/config/). * * ``` * WP_CLI::log( 'The --url= value is: ' . WP_CLI::get_config( 'url' ) ); * ``` * * @access public * @category Input * * @param string $key Get value for a specific global configuration parameter. * @return mixed */ public static function get_config( $key = null ) { if ( null === $key ) { return self::get_runner()->config; } if ( ! isset( self::get_runner()->config[ $key ] ) ) { self::warning( "Unknown config option '$key'." ); return null; } return self::get_runner()->config[ $key ]; } /** * Run a WP-CLI command. * * Launches a new child process to run a specified WP-CLI command. * Optionally: * * * Run the command in an existing process. * * Prevent halting script execution on error. * * Capture and return STDOUT, or full details about command execution. * * Parse JSON output if the command rendered it. * * ``` * $options = array( * 'return' => true, // Return 'STDOUT'; use 'all' for full object. * 'parse' => 'json', // Parse captured STDOUT to JSON array. * 'launch' => false, // Reuse the current process. * 'exit_error' => true, // Halt script execution on error. * ); * $plugins = WP_CLI::runcommand( 'plugin list --format=json', $options ); * ``` * * @access public * @category Execution * * @param string $command WP-CLI command to run, including arguments. * @param array $options Configuration options for command execution. * @return mixed */ public static function runcommand( $command, $options = array() ) { $defaults = array( 'launch' => true, // Launch a new process, or reuse the existing. 'exit_error' => true, // Exit on error by default. 'return' => false, // Capture and return output, or render in realtime. 'parse' => false, // Parse returned output as a particular format. ); $options = array_merge( $defaults, $options ); $launch = $options['launch']; $exit_error = $options['exit_error']; $return = $options['return']; $parse = $options['parse']; $retval = null; if ( $launch ) { Utils\check_proc_available( 'launch option' ); $descriptors = array( 0 => STDIN, 1 => STDOUT, 2 => STDERR, ); if ( $return ) { $descriptors = array( 0 => STDIN, 1 => array( 'pipe', 'w' ), 2 => array( 'pipe', 'w' ), ); } $php_bin = escapeshellarg( Utils\get_php_binary() ); $script_path = $GLOBALS['argv'][0]; // Persist runtime arguments unless they've been specified otherwise. $configurator = self::get_configurator(); $argv = array_slice( $GLOBALS['argv'], 1 ); list( $ignore1, $ignore2, $runtime_config ) = $configurator->parse_args( $argv ); foreach ( $runtime_config as $k => $v ) { if ( preg_match( "|^--{$k}=?$|", $command ) ) { unset( $runtime_config[ $k ] ); } } $runtime_config = Utils\assoc_args_to_str( $runtime_config ); $runcommand = "{$php_bin} {$script_path} {$runtime_config} {$command}"; $proc = Utils\proc_open_compat( $runcommand, $descriptors, $pipes, getcwd() ); if ( $return ) { $stdout = stream_get_contents( $pipes[1] ); fclose( $pipes[1] ); $stderr = stream_get_contents( $pipes[2] ); fclose( $pipes[2] ); } $return_code = proc_close( $proc ); if ( -1 === $return_code ) { self::warning( 'Spawned process returned exit code -1, which could be caused by a custom compiled version of PHP that uses the --enable-sigchild option.' ); } elseif ( $return_code && $exit_error ) { exit( $return_code ); } if ( true === $return || 'stdout' === $return ) { $retval = trim( $stdout ); } elseif ( 'stderr' === $return ) { $retval = trim( $stderr ); } elseif ( 'return_code' === $return ) { $retval = $return_code; } elseif ( 'all' === $return ) { $retval = (object) array( 'stdout' => trim( $stdout ), 'stderr' => trim( $stderr ), 'return_code' => $return_code, ); } } else { $configurator = self::get_configurator(); $argv = Utils\parse_str_to_argv( $command ); list( $args, $assoc_args, $runtime_config ) = $configurator->parse_args( $argv ); if ( $return ) { $existing_logger = self::$logger; self::$logger = new WP_CLI\Loggers\Execution(); self::$logger->ob_start(); } if ( ! $exit_error ) { self::$capture_exit = true; } try { self::get_runner()->run_command( $args, $assoc_args, array( 'back_compat_conversions' => true, ) ); $return_code = 0; } catch ( ExitException $e ) { $return_code = $e->getCode(); } if ( $return ) { $execution_logger = self::$logger; $execution_logger->ob_end(); self::$logger = $existing_logger; $stdout = $execution_logger->stdout; $stderr = $execution_logger->stderr; if ( true === $return || 'stdout' === $return ) { $retval = trim( $stdout ); } elseif ( 'stderr' === $return ) { $retval = trim( $stderr ); } elseif ( 'return_code' === $return ) { $retval = $return_code; } elseif ( 'all' === $return ) { $retval = (object) array( 'stdout' => trim( $stdout ), 'stderr' => trim( $stderr ), 'return_code' => $return_code, ); } } if ( ! $exit_error ) { self::$capture_exit = false; } } if ( ( true === $return || 'stdout' === $return ) && 'json' === $parse ) { $retval = json_decode( $retval, true ); } return $retval; } /** * Run a given command within the current process using the same global * parameters. * * Use `WP_CLI::runcommand()` instead, which is easier to use and works better. * * To run a command using a new process with the same global parameters, * use WP_CLI::launch_self(). To run a command using a new process with * different global parameters, use WP_CLI::launch(). * * ``` * ob_start(); * WP_CLI::run_command( array( 'cli', 'cmd-dump' ) ); * $ret = ob_get_clean(); * ``` * * @access public * @category Execution * * @param array $args Positional arguments including command name. * @param array $assoc_args */ public static function run_command( $args, $assoc_args = array() ) { self::get_runner()->run_command( $args, $assoc_args ); } // DEPRECATED STUFF public static function add_man_dir() { trigger_error( 'WP_CLI::add_man_dir() is deprecated. Add docs inline.', E_USER_WARNING ); } // back-compat public static function out( $str ) { fwrite( STDOUT, $str ); } // back-compat // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Deprecated method. public static function addCommand( $name, $class ) { trigger_error( sprintf( 'wp %s: %s is deprecated. use WP_CLI::add_command() instead.', $name, __FUNCTION__ ), E_USER_WARNING ); self::add_command( $name, $class ); } } get_col( "SHOW TABLES LIKE '%_options'" ); $found_prefixes = array(); if ( count( $tables ) ) { foreach ( $tables as $table ) { $maybe_prefix = substr( $table, 0, - strlen( 'options' ) ); if ( $maybe_prefix !== $table_prefix ) { $found_prefixes[] = $maybe_prefix; } } } if ( count( $found_prefixes ) ) { $prefix_list = implode( ', ', $found_prefixes ); $install_label = count( $found_prefixes ) > 1 ? 'installations' : 'installation'; \WP_CLI::error( "The site you have requested is not installed.\n" . "Your table prefix is '{$table_prefix}'. Found {$install_label} with table prefix: {$prefix_list}.\n" . 'Or, run `wp core install` to create database tables.' ); } else { \WP_CLI::error( "The site you have requested is not installed.\n" . 'Run `wp core install` to create database tables.' ); } } } // phpcs:disable WordPress.PHP.IniSet -- Intentional & correct usage. function wp_debug_mode() { if ( \WP_CLI::get_config( 'debug' ) ) { if ( ! defined( 'WP_DEBUG' ) ) { define( 'WP_DEBUG', true ); } error_reporting( E_ALL & ~E_DEPRECATED & ~E_STRICT ); } else { if ( WP_DEBUG ) { error_reporting( E_ALL ); if ( WP_DEBUG_DISPLAY ) { ini_set( 'display_errors', 1 ); } elseif ( null !== WP_DEBUG_DISPLAY ) { ini_set( 'display_errors', 0 ); } if ( WP_DEBUG_LOG ) { ini_set( 'log_errors', 1 ); ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' ); } } else { error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); } if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { ini_set( 'display_errors', 0 ); } } // XDebug already sends errors to STDERR. ini_set( 'display_errors', function_exists( 'xdebug_debug_zval' ) ? false : 'STDERR' ); } // phpcs:enable function replace_wp_die_handler() { \remove_filter( 'wp_die_handler', '_default_wp_die_handler' ); \add_filter( 'wp_die_handler', function() { return __NAMESPACE__ . '\\wp_die_handler'; } ); } function wp_die_handler( $message ) { if ( $message instanceof \WP_Error ) { $message = $message->get_error_message(); } $message = wp_clean_error_message( $message ); \WP_CLI::error( $message ); } /** * Clean HTML error message so suitable for text display. */ function wp_clean_error_message( $message ) { $original_message = trim( $message ); $message = $original_message; if ( preg_match( '|^\

(.+?)

|', $original_message, $matches ) ) { $message = $matches[1] . '.'; } if ( preg_match( '|\

(.+?)

|', $original_message, $matches ) ) { $message .= ' ' . $matches[1]; } $search_replace = array( '' => '`', '' => '`', ); $message = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $message ); $message = namespace\strip_tags( $message ); $message = html_entity_decode( $message, ENT_COMPAT, 'UTF-8' ); return $message; } function wp_redirect_handler( $url ) { \WP_CLI::warning( 'Some code is trying to do a URL redirect. Backtrace:' ); ob_start(); debug_print_backtrace(); fwrite( STDERR, ob_get_clean() ); return $url; } function maybe_require( $since, $path ) { if ( wp_version_compare( $since, '>=' ) ) { require $path; } } function get_upgrader( $class ) { if ( ! class_exists( '\WP_Upgrader' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } return new $class( new \WP_CLI\UpgraderSkin() ); } /** * Converts a plugin basename back into a friendly slug. */ function get_plugin_name( $basename ) { if ( false === strpos( $basename, '/' ) ) { $name = basename( $basename, '.php' ); } else { $name = dirname( $basename ); } return $name; } function is_plugin_skipped( $file ) { $name = get_plugin_name( str_replace( WP_PLUGIN_DIR . '/', '', $file ) ); $skipped_plugins = \WP_CLI::get_runner()->config['skip-plugins']; if ( true === $skipped_plugins ) { return true; } if ( ! is_array( $skipped_plugins ) ) { $skipped_plugins = explode( ',', $skipped_plugins ); } return in_array( $name, array_filter( $skipped_plugins ), true ); } function get_theme_name( $path ) { return basename( $path ); } function is_theme_skipped( $path ) { $name = get_theme_name( $path ); $skipped_themes = \WP_CLI::get_runner()->config['skip-themes']; if ( true === $skipped_themes ) { return true; } if ( ! is_array( $skipped_themes ) ) { $skipped_themes = explode( ',', $skipped_themes ); } return in_array( $name, array_filter( $skipped_themes ), true ); } /** * Register the sidebar for unused widgets. * Core does this in /wp-admin/widgets.php, which isn't helpful. */ function wp_register_unused_sidebar() { register_sidebar( array( 'name' => __( 'Inactive Widgets' ), 'id' => 'wp_inactive_widgets', 'class' => 'inactive-sidebar', 'description' => __( 'Drag widgets here to remove them from the sidebar but keep their settings.' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); } /** * Attempts to determine which object cache is being used. * * Note that the guesses made by this function are based on the WP_Object_Cache classes * that define the 3rd party object cache extension. Changes to those classes could render * problems with this function's ability to determine which object cache is being used. * * @return string */ function wp_get_cache_type() { global $_wp_using_ext_object_cache, $wp_object_cache; if ( ! empty( $_wp_using_ext_object_cache ) ) { // Test for Memcached PECL extension memcached object cache (https://github.com/tollmanz/wordpress-memcached-backend) if ( isset( $wp_object_cache->m ) && $wp_object_cache->m instanceof \Memcached ) { $message = 'Memcached'; // Test for Memcache PECL extension memcached object cache (http://wordpress.org/extend/plugins/memcached/) } elseif ( isset( $wp_object_cache->mc ) ) { $is_memcache = true; foreach ( $wp_object_cache->mc as $bucket ) { if ( ! $bucket instanceof \Memcache && ! $bucket instanceof \Memcached ) { $is_memcache = false; } } if ( $is_memcache ) { $message = 'Memcache'; } // Test for Xcache object cache (http://plugins.svn.wordpress.org/xcache/trunk/object-cache.php) } elseif ( $wp_object_cache instanceof \XCache_Object_Cache ) { $message = 'Xcache'; // Test for WinCache object cache (http://wordpress.org/extend/plugins/wincache-object-cache-backend/) } elseif ( class_exists( 'WinCache_Object_Cache' ) ) { $message = 'WinCache'; // Test for APC object cache (http://wordpress.org/extend/plugins/apc/) } elseif ( class_exists( 'APC_Object_Cache' ) ) { $message = 'APC'; // Test for Redis Object Cache (https://github.com/alleyinteractive/wp-redis) } elseif ( isset( $wp_object_cache->redis ) && $wp_object_cache->redis instanceof \Redis ) { $message = 'Redis'; // Test for WP LCache Object cache (https://github.com/lcache/wp-lcache) } elseif ( isset( $wp_object_cache->lcache ) && $wp_object_cache->lcache instanceof \LCache\Integrated ) { $message = 'WP LCache'; } elseif ( function_exists( 'w3_instance' ) ) { $config = w3_instance( 'W3_Config' ); $message = 'Unknown'; if ( $config->get_boolean( 'objectcache.enabled' ) ) { $message = 'W3TC ' . $config->get_string( 'objectcache.engine' ); } } else { $message = 'Unknown'; } } else { $message = 'Default'; } return $message; } /** * Clear WordPress internal object caches. * * In long-running scripts, the internal caches on `$wp_object_cache` and `$wpdb` * can grow to consume gigabytes of memory. Periodically calling this utility * can help with memory management. * * @access public * @category System * @deprecated 1.5.0 */ function wp_clear_object_cache() { global $wpdb, $wp_object_cache; $wpdb->queries = array(); if ( ! is_object( $wp_object_cache ) ) { return; } // The following are Memcached (Redux) plugin specific (see https://core.trac.wordpress.org/ticket/31463). if ( isset( $wp_object_cache->group_ops ) ) { $wp_object_cache->group_ops = array(); } if ( isset( $wp_object_cache->stats ) ) { $wp_object_cache->stats = array(); } if ( isset( $wp_object_cache->memcache_debug ) ) { $wp_object_cache->memcache_debug = array(); } // Used by `WP_Object_Cache` also. if ( isset( $wp_object_cache->cache ) ) { $wp_object_cache->cache = array(); } } /** * Get a set of tables in the database. * * Interprets common command-line options into a resolved set of table names. * * @param array $args Provided table names, or tables with wildcards. * @param array $assoc_args Optional flags for groups of tables (e.g. --network) * @return array $tables */ function wp_get_table_names( $args, $assoc_args = array() ) { global $wpdb; $tables = array(); // Abort if incompatible args supplied. if ( get_flag_value( $assoc_args, 'base-tables-only' ) && get_flag_value( $assoc_args, 'views-only' ) ) { \WP_CLI::error( 'You cannot supply --base-tables-only and --views-only at the same time.' ); } // Pre-load tables SQL query with Views restriction if needed. if ( get_flag_value( $assoc_args, 'base-tables-only' ) ) { $tables_sql = 'SHOW FULL TABLES WHERE Table_Type = "BASE TABLE"'; } elseif ( get_flag_value( $assoc_args, 'views-only' ) ) { $tables_sql = 'SHOW FULL TABLES WHERE Table_Type = "VIEW"'; } if ( get_flag_value( $assoc_args, 'all-tables' ) ) { if ( empty( $tables_sql ) ) { $tables_sql = 'SHOW TABLES'; } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is safe, see above. $tables = $wpdb->get_col( $tables_sql, 0 ); } elseif ( get_flag_value( $assoc_args, 'all-tables-with-prefix' ) ) { if ( empty( $tables_sql ) ) { $tables_sql = $wpdb->prepare( 'SHOW TABLES LIKE %s', esc_like( $wpdb->get_blog_prefix() ) . '%' ); } else { $tables_sql .= sprintf( " AND %s LIKE '%s'", esc_sql_ident( 'Tables_in_' . $wpdb->dbname ), esc_like( $wpdb->get_blog_prefix() ) . '%' ); } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared, see above. $tables = $wpdb->get_col( $tables_sql, 0 ); } else { $scope = get_flag_value( $assoc_args, 'scope', 'all' ); // Note: BC change 1.5.0, taking scope into consideration for network also. if ( get_flag_value( $assoc_args, 'network' ) && is_multisite() ) { $network_global_scope = in_array( $scope, array( 'all', 'global', 'ms_global' ), true ) ? ( 'all' === $scope ? 'global' : $scope ) : ''; $wp_tables = array_values( $wpdb->tables( $network_global_scope ) ); if ( in_array( $scope, array( 'all', 'blog' ), true ) ) { // Do directly for compat with old WP versions. Note: private, deleted, archived sites are not excluded. $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs WHERE site_id = $wpdb->siteid" ); foreach ( $blog_ids as $blog_id ) { $wp_tables = array_merge( $wp_tables, array_values( $wpdb->tables( 'blog', true /*prefix*/, $blog_id ) ) ); } } } else { $wp_tables = array_values( $wpdb->tables( $scope ) ); } if ( ! global_terms_enabled() ) { // Only include sitecategories when it's actually enabled. $wp_tables = array_values( array_diff( $wp_tables, array( $wpdb->sitecategories ) ) ); } // Note: BC change 1.5.0, tables are sorted (via TABLES view). // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- uses esc_sql_ident() and $wpdb->_escape(). $tables = $wpdb->get_col( sprintf( "SHOW TABLES WHERE %s IN ('%s')", esc_sql_ident( 'Tables_in_' . $wpdb->dbname ), implode( "', '", $wpdb->_escape( $wp_tables ) ) ) ); if ( get_flag_value( $assoc_args, 'base-tables-only' ) || get_flag_value( $assoc_args, 'views-only' ) ) { // Apply Views restriction args if needed. // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared, see above. $views_query_tables = $wpdb->get_col( $tables_sql, 0 ); $tables = array_intersect( $tables, $views_query_tables ); } } // Filter by `$args`. if ( $args ) { $args_tables = array(); foreach ( $args as $arg ) { if ( false !== strpos( $arg, '*' ) || false !== strpos( $arg, '?' ) ) { $args_tables = array_merge( $args_tables, array_filter( $tables, function ( $v ) use ( $arg ) { return fnmatch( $arg, $v ); } ) ); } else { $args_tables[] = $arg; } } $args_tables = array_values( array_unique( $args_tables ) ); $tables = array_values( array_intersect( $tables, $args_tables ) ); if ( empty( $tables ) ) { \WP_CLI::error( sprintf( "Couldn't find any tables matching: %s", implode( ' ', $args ) ) ); } } return $tables; } /** * Failsafe use of the WordPress wp_strip_all_tags() function. * * Automatically falls back to strip_tags() function if the WP function is not * available. * * @param string $string String to strip the tags from. * @return string String devoid of tags. */ function strip_tags( $string ) { if ( function_exists( 'wp_strip_all_tags' ) ) { return \wp_strip_all_tags( $string ); } $string = preg_replace( '@<(script|style)[^>]*?>.*?@si', '', $string ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Fallback. $string = \strip_tags( $string ); return trim( $string ); } */ class SymfonyClassCollectionLoader { private static $loaded; const HEADER = <<<'EOS' \s*$/'), '', file_get_contents($r->getFileName())); } $cache = $cacheDir . '/' . $name . $extension; $header = sprintf(self::HEADER, strftime('%Y')); self::writeCacheFile($cache, $header . substr(self::stripComments(''; const T_PARENT = '<'; const T_DELIM_CHANGE = '='; const T_ESCAPED = '_v'; const T_UNESCAPED = '{'; const T_UNESCAPED_2 = '&'; const T_TEXT = '_t'; const T_PRAGMA = '%'; const T_BLOCK_VAR = '$'; const T_BLOCK_ARG = '$arg'; // Valid token types private static $tagTypes = array( self::T_SECTION => true, self::T_INVERTED => true, self::T_END_SECTION => true, self::T_COMMENT => true, self::T_PARTIAL => true, self::T_PARENT => true, self::T_DELIM_CHANGE => true, self::T_ESCAPED => true, self::T_UNESCAPED => true, self::T_UNESCAPED_2 => true, self::T_PRAGMA => true, self::T_BLOCK_VAR => true, ); // Token properties const TYPE = 'type'; const NAME = 'name'; const OTAG = 'otag'; const CTAG = 'ctag'; const LINE = 'line'; const INDEX = 'index'; const END = 'end'; const INDENT = 'indent'; const NODES = 'nodes'; const VALUE = 'value'; const FILTERS = 'filters'; private $state; private $tagType; private $buffer; private $tokens; private $seenTag; private $line; private $otag; private $ctag; private $otagLen; private $ctagLen; /** * Scan and tokenize template source. * * @throws Mustache_Exception_SyntaxException when mismatched section tags are encountered * * @param string $text Mustache template source to tokenize * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null) * * @return array Set of Mustache tokens */ public function scan($text, $delimiters = null) { // Setting mbstring.func_overload makes things *really* slow. // Let's do everyone a favor and scan this string as ASCII instead. // // @codeCoverageIgnoreStart $encoding = null; if (function_exists('mb_internal_encoding') && ini_get('mbstring.func_overload') & 2) { $encoding = mb_internal_encoding(); mb_internal_encoding('ASCII'); } // @codeCoverageIgnoreEnd $this->reset(); if ($delimiters = trim($delimiters)) { $this->setDelimiters($delimiters); } $len = strlen($text); for ($i = 0; $i < $len; $i++) { switch ($this->state) { case self::IN_TEXT: if ($this->tagChange($this->otag, $this->otagLen, $text, $i)) { $i--; $this->flushBuffer(); $this->state = self::IN_TAG_TYPE; } else { $char = $text[$i]; $this->buffer .= $char; if ($char === "\n") { $this->flushBuffer(); $this->line++; } } break; case self::IN_TAG_TYPE: $i += $this->otagLen - 1; $char = $text[$i + 1]; if (isset(self::$tagTypes[$char])) { $tag = $char; $this->tagType = $tag; } else { $tag = null; $this->tagType = self::T_ESCAPED; } if ($this->tagType === self::T_DELIM_CHANGE) { $i = $this->changeDelimiters($text, $i); $this->state = self::IN_TEXT; } elseif ($this->tagType === self::T_PRAGMA) { $i = $this->addPragma($text, $i); $this->state = self::IN_TEXT; } else { if ($tag !== null) { $i++; } $this->state = self::IN_TAG; } $this->seenTag = $i; break; default: if ($this->tagChange($this->ctag, $this->ctagLen, $text, $i)) { $token = array( self::TYPE => $this->tagType, self::NAME => trim($this->buffer), self::OTAG => $this->otag, self::CTAG => $this->ctag, self::LINE => $this->line, self::INDEX => ($this->tagType === self::T_END_SECTION) ? $this->seenTag - $this->otagLen : $i + $this->ctagLen, ); if ($this->tagType === self::T_UNESCAPED) { // Clean up `{{{ tripleStache }}}` style tokens. if ($this->ctag === '}}') { if (($i + 2 < $len) && $text[$i + 2] === '}') { $i++; } else { $msg = sprintf( 'Mismatched tag delimiters: %s on line %d', $token[self::NAME], $token[self::LINE] ); throw new Mustache_Exception_SyntaxException($msg, $token); } } else { $lastName = $token[self::NAME]; if (substr($lastName, -1) === '}') { $token[self::NAME] = trim(substr($lastName, 0, -1)); } else { $msg = sprintf( 'Mismatched tag delimiters: %s on line %d', $token[self::NAME], $token[self::LINE] ); throw new Mustache_Exception_SyntaxException($msg, $token); } } } $this->buffer = ''; $i += $this->ctagLen - 1; $this->state = self::IN_TEXT; $this->tokens[] = $token; } else { $this->buffer .= $text[$i]; } break; } } $this->flushBuffer(); // Restore the user's encoding... // @codeCoverageIgnoreStart if ($encoding) { mb_internal_encoding($encoding); } // @codeCoverageIgnoreEnd return $this->tokens; } /** * Helper function to reset tokenizer internal state. */ private function reset() { $this->state = self::IN_TEXT; $this->tagType = null; $this->buffer = ''; $this->tokens = array(); $this->seenTag = false; $this->line = 0; $this->otag = '{{'; $this->ctag = '}}'; $this->otagLen = 2; $this->ctagLen = 2; } /** * Flush the current buffer to a token. */ private function flushBuffer() { if (strlen($this->buffer) > 0) { $this->tokens[] = array( self::TYPE => self::T_TEXT, self::LINE => $this->line, self::VALUE => $this->buffer, ); $this->buffer = ''; } } /** * Change the current Mustache delimiters. Set new `otag` and `ctag` values. * * @param string $text Mustache template source * @param int $index Current tokenizer index * * @return int New index value */ private function changeDelimiters($text, $index) { $startIndex = strpos($text, '=', $index) + 1; $close = '=' . $this->ctag; $closeIndex = strpos($text, $close, $index); $this->setDelimiters(trim(substr($text, $startIndex, $closeIndex - $startIndex))); $this->tokens[] = array( self::TYPE => self::T_DELIM_CHANGE, self::LINE => $this->line, ); return $closeIndex + strlen($close) - 1; } /** * Set the current Mustache `otag` and `ctag` delimiters. * * @param string $delimiters */ private function setDelimiters($delimiters) { list($otag, $ctag) = explode(' ', $delimiters); $this->otag = $otag; $this->ctag = $ctag; $this->otagLen = strlen($otag); $this->ctagLen = strlen($ctag); } /** * Add pragma token. * * Pragmas are hoisted to the front of the template, so all pragma tokens * will appear at the front of the token list. * * @param string $text * @param int $index * * @return int New index value */ private function addPragma($text, $index) { $end = strpos($text, $this->ctag, $index); $pragma = trim(substr($text, $index + 2, $end - $index - 2)); // Pragmas are hoisted to the front of the template. array_unshift($this->tokens, array( self::TYPE => self::T_PRAGMA, self::NAME => $pragma, self::LINE => 0, )); return $end + $this->ctagLen - 1; } /** * Test whether it's time to change tags. * * @param string $tag Current tag name * @param int $tagLen Current tag name length * @param string $text Mustache template source * @param int $index Current tokenizer index * * @return bool True if this is a closing section tag */ private function tagChange($tag, $tagLen, $text, $index) { return substr($text, $index, $tagLen) === $tag; } } 100, self::INFO => 200, self::NOTICE => 250, self::WARNING => 300, self::ERROR => 400, self::CRITICAL => 500, self::ALERT => 550, self::EMERGENCY => 600, ); protected $level; protected $stream = null; protected $url = null; /** * @throws InvalidArgumentException if the logging level is unknown * * @param resource|string $stream Resource instance or URL * @param int $level The minimum logging level at which this handler will be triggered */ public function __construct($stream, $level = Mustache_Logger::ERROR) { $this->setLevel($level); if (is_resource($stream)) { $this->stream = $stream; } else { $this->url = $stream; } } /** * Close stream resources. */ public function __destruct() { if (is_resource($this->stream)) { fclose($this->stream); } } /** * Set the minimum logging level. * * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown * * @param int $level The minimum logging level which will be written */ public function setLevel($level) { if (!array_key_exists($level, self::$levels)) { throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level)); } $this->level = $level; } /** * Get the current minimum logging level. * * @return int */ public function getLevel() { return $this->level; } /** * Logs with an arbitrary level. * * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown * * @param mixed $level * @param string $message * @param array $context */ public function log($level, $message, array $context = array()) { if (!array_key_exists($level, self::$levels)) { throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level)); } if (self::$levels[$level] >= self::$levels[$this->level]) { $this->writeLog($level, $message, $context); } } /** * Write a record to the log. * * @throws Mustache_Exception_LogicException If neither a stream resource nor url is present * @throws Mustache_Exception_RuntimeException If the stream url cannot be opened * * @param int $level The logging level * @param string $message The log message * @param array $context The log context */ protected function writeLog($level, $message, array $context = array()) { if (!is_resource($this->stream)) { if (!isset($this->url)) { throw new Mustache_Exception_LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); } $this->stream = fopen($this->url, 'a'); if (!is_resource($this->stream)) { // @codeCoverageIgnoreStart throw new Mustache_Exception_RuntimeException(sprintf('The stream or file "%s" could not be opened.', $this->url)); // @codeCoverageIgnoreEnd } } fwrite($this->stream, self::formatLine($level, $message, $context)); } /** * Gets the name of the logging level. * * @throws InvalidArgumentException if the logging level is unknown * * @param int $level * * @return string */ protected static function getLevelName($level) { return strtoupper($level); } /** * Format a log line for output. * * @param int $level The logging level * @param string $message The log message * @param array $context The log context * * @return string */ protected static function formatLine($level, $message, array $context = array()) { return sprintf( "%s: %s\n", self::getLevelName($level), self::interpolateMessage($message, $context) ); } /** * Interpolate context values into the message placeholders. * * @param string $message * @param array $context * * @return string */ protected static function interpolateMessage($message, array $context = array()) { if (strpos($message, '{') === false) { return $message; } // build a replacement array with braces around the context keys $replace = array(); foreach ($context as $key => $val) { $replace['{' . $key . '}'] = $val; } // interpolate replacement values into the the message and return return strtr($message, $replace); } } log(Mustache_Logger::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 */ public function alert($message, array $context = array()) { $this->log(Mustache_Logger::ALERT, $message, $context); } /** * Critical conditions. * * Example: Application component unavailable, unexpected exception. * * @param string $message * @param array $context */ public function critical($message, array $context = array()) { $this->log(Mustache_Logger::CRITICAL, $message, $context); } /** * Runtime errors that do not require immediate action but should typically * be logged and monitored. * * @param string $message * @param array $context */ public function error($message, array $context = array()) { $this->log(Mustache_Logger::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 */ public function warning($message, array $context = array()) { $this->log(Mustache_Logger::WARNING, $message, $context); } /** * Normal but significant events. * * @param string $message * @param array $context */ public function notice($message, array $context = array()) { $this->log(Mustache_Logger::NOTICE, $message, $context); } /** * Interesting events. * * Example: User logs in, SQL logs. * * @param string $message * @param array $context */ public function info($message, array $context = array()) { $this->log(Mustache_Logger::INFO, $message, $context); } /** * Detailed debug information. * * @param string $message * @param array $context */ public function debug($message, array $context = array()) { $this->log(Mustache_Logger::DEBUG, $message, $context); } } =}}`. (default: null) */ public function __construct(Mustache_Engine $mustache, Mustache_Context $context, $delims = null) { $this->mustache = $mustache; $this->context = $context; $this->delims = $delims; } /** * Render a string as a Mustache template with the current rendering context. * * @param string $string * * @return string Rendered template */ public function render($string) { return $this->mustache ->loadLambda((string) $string, $this->delims) ->renderInternal($this->context); } /** * Render a string as a Mustache template with the current rendering context. * * @param string $string * * @return string Rendered template */ public function __invoke($string) { return $this->render($string); } /** * Get a Lambda Helper with custom delimiters. * * @param string $delims Custom delimiters, in the format `{{= <% %> =}}` * * @return Mustache_LambdaHelper */ public function withDelimiters($delims) { return new self($this->mustache, $this->context, $delims); } } lineNum = -1; $this->lineTokens = 0; $this->pragmas = $this->defaultPragmas; $this->pragmaFilters = isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS]); $this->pragmaBlocks = isset($this->pragmas[Mustache_Engine::PRAGMA_BLOCKS]); return $this->buildTree($tokens); } /** * Enable pragmas across all templates, regardless of the presence of pragma * tags in the individual templates. * * @internal Users should set global pragmas in Mustache_Engine, not here :) * * @param string[] $pragmas */ public function setPragmas(array $pragmas) { $this->pragmas = array(); foreach ($pragmas as $pragma) { $this->enablePragma($pragma); } $this->defaultPragmas = $this->pragmas; } /** * Helper method for recursively building a parse tree. * * @throws Mustache_Exception_SyntaxException when nesting errors or mismatched section tags are encountered * * @param array &$tokens Set of Mustache tokens * @param array $parent Parent token (default: null) * * @return array Mustache Token parse tree */ private function buildTree(array &$tokens, array $parent = null) { $nodes = array(); while (!empty($tokens)) { $token = array_shift($tokens); if ($token[Mustache_Tokenizer::LINE] === $this->lineNum) { $this->lineTokens++; } else { $this->lineNum = $token[Mustache_Tokenizer::LINE]; $this->lineTokens = 0; } if ($this->pragmaFilters && isset($token[Mustache_Tokenizer::NAME])) { list($name, $filters) = $this->getNameAndFilters($token[Mustache_Tokenizer::NAME]); if (!empty($filters)) { $token[Mustache_Tokenizer::NAME] = $name; $token[Mustache_Tokenizer::FILTERS] = $filters; } } switch ($token[Mustache_Tokenizer::TYPE]) { case Mustache_Tokenizer::T_DELIM_CHANGE: $this->checkIfTokenIsAllowedInParent($parent, $token); $this->clearStandaloneLines($nodes, $tokens); break; case Mustache_Tokenizer::T_SECTION: case Mustache_Tokenizer::T_INVERTED: $this->checkIfTokenIsAllowedInParent($parent, $token); $this->clearStandaloneLines($nodes, $tokens); $nodes[] = $this->buildTree($tokens, $token); break; case Mustache_Tokenizer::T_END_SECTION: if (!isset($parent)) { $msg = sprintf( 'Unexpected closing tag: /%s on line %d', $token[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::LINE] ); throw new Mustache_Exception_SyntaxException($msg, $token); } if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { $msg = sprintf( 'Nesting error: %s (on line %d) vs. %s (on line %d)', $parent[Mustache_Tokenizer::NAME], $parent[Mustache_Tokenizer::LINE], $token[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::LINE] ); throw new Mustache_Exception_SyntaxException($msg, $token); } $this->clearStandaloneLines($nodes, $tokens); $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; $parent[Mustache_Tokenizer::NODES] = $nodes; return $parent; case Mustache_Tokenizer::T_PARTIAL: $this->checkIfTokenIsAllowedInParent($parent, $token); //store the whitespace prefix for laters! if ($indent = $this->clearStandaloneLines($nodes, $tokens)) { $token[Mustache_Tokenizer::INDENT] = $indent[Mustache_Tokenizer::VALUE]; } $nodes[] = $token; break; case Mustache_Tokenizer::T_PARENT: $this->checkIfTokenIsAllowedInParent($parent, $token); $nodes[] = $this->buildTree($tokens, $token); break; case Mustache_Tokenizer::T_BLOCK_VAR: if ($this->pragmaBlocks) { // BLOCKS pragma is enabled, let's do this! if ($parent[Mustache_Tokenizer::TYPE] === Mustache_Tokenizer::T_PARENT) { $token[Mustache_Tokenizer::TYPE] = Mustache_Tokenizer::T_BLOCK_ARG; } $this->clearStandaloneLines($nodes, $tokens); $nodes[] = $this->buildTree($tokens, $token); } else { // pretend this was just a normal "escaped" token... $token[Mustache_Tokenizer::TYPE] = Mustache_Tokenizer::T_ESCAPED; // TODO: figure out how to figure out if there was a space after this dollar: $token[Mustache_Tokenizer::NAME] = '$' . $token[Mustache_Tokenizer::NAME]; $nodes[] = $token; } break; case Mustache_Tokenizer::T_PRAGMA: $this->enablePragma($token[Mustache_Tokenizer::NAME]); // no break case Mustache_Tokenizer::T_COMMENT: $this->clearStandaloneLines($nodes, $tokens); $nodes[] = $token; break; default: $nodes[] = $token; break; } } if (isset($parent)) { $msg = sprintf( 'Missing closing tag: %s opened on line %d', $parent[Mustache_Tokenizer::NAME], $parent[Mustache_Tokenizer::LINE] ); throw new Mustache_Exception_SyntaxException($msg, $parent); } return $nodes; } /** * Clear standalone line tokens. * * Returns a whitespace token for indenting partials, if applicable. * * @param array $nodes Parsed nodes * @param array $tokens Tokens to be parsed * * @return array|null Resulting indent token, if any */ private function clearStandaloneLines(array &$nodes, array &$tokens) { if ($this->lineTokens > 1) { // this is the third or later node on this line, so it can't be standalone return; } $prev = null; if ($this->lineTokens === 1) { // this is the second node on this line, so it can't be standalone // unless the previous node is whitespace. if ($prev = end($nodes)) { if (!$this->tokenIsWhitespace($prev)) { return; } } } if ($next = reset($tokens)) { // If we're on a new line, bail. if ($next[Mustache_Tokenizer::LINE] !== $this->lineNum) { return; } // If the next token isn't whitespace, bail. if (!$this->tokenIsWhitespace($next)) { return; } if (count($tokens) !== 1) { // Unless it's the last token in the template, the next token // must end in newline for this to be standalone. if (substr($next[Mustache_Tokenizer::VALUE], -1) !== "\n") { return; } } // Discard the whitespace suffix array_shift($tokens); } if ($prev) { // Return the whitespace prefix, if any return array_pop($nodes); } } /** * Check whether token is a whitespace token. * * True if token type is T_TEXT and value is all whitespace characters. * * @param array $token * * @return bool True if token is a whitespace token */ private function tokenIsWhitespace(array $token) { if ($token[Mustache_Tokenizer::TYPE] === Mustache_Tokenizer::T_TEXT) { return preg_match('/^\s*$/', $token[Mustache_Tokenizer::VALUE]); } return false; } /** * Check whether a token is allowed inside a parent tag. * * @throws Mustache_Exception_SyntaxException if an invalid token is found inside a parent tag * * @param array|null $parent * @param array $token */ private function checkIfTokenIsAllowedInParent($parent, array $token) { if (empty($parent[Mustache_Tokenizer::TYPE])) { return; } if ($parent[Mustache_Tokenizer::TYPE] === Mustache_Tokenizer::T_PARENT) { throw new Mustache_Exception_SyntaxException('Illegal content in < parent tag', $token); } } /** * Split a tag name into name and filters. * * @param string $name * * @return array [Tag name, Array of filters] */ private function getNameAndFilters($name) { $filters = array_map('trim', explode('|', $name)); $name = array_shift($filters); return array($name, $filters); } /** * Enable a pragma. * * @param string $name */ private function enablePragma($name) { $this->pragmas[$name] = true; switch ($name) { case Mustache_Engine::PRAGMA_BLOCKS: $this->pragmaBlocks = true; break; case Mustache_Engine::PRAGMA_FILTERS: $this->pragmaFilters = true; break; } } } baseDir = $realDir; } else { $this->baseDir = $baseDir; } } /** * Register a new instance as an SPL autoloader. * * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') * * @return Mustache_Autoloader Registered Autoloader instance */ public static function register($baseDir = null) { $key = $baseDir ? $baseDir : 0; if (!isset(self::$instances[$key])) { self::$instances[$key] = new self($baseDir); } $loader = self::$instances[$key]; spl_autoload_register(array($loader, 'autoload')); return $loader; } /** * Autoload Mustache classes. * * @param string $class */ public function autoload($class) { if ($class[0] === '\\') { $class = substr($class, 1); } if (strpos($class, 'Mustache') !== 0) { return; } $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class)); if (is_file($file)) { require $file; } } } loaders = array(); foreach ($loaders as $loader) { $this->addLoader($loader); } } /** * Add a Loader instance. * * @param Mustache_Loader $loader */ public function addLoader(Mustache_Loader $loader) { $this->loaders[] = $loader; } /** * Load a Template by name. * * @throws Mustache_Exception_UnknownTemplateException If a template file is not found * * @param string $name * * @return string Mustache Template source */ public function load($name) { foreach ($this->loaders as $loader) { try { return $loader->load($name); } catch (Mustache_Exception_UnknownTemplateException $e) { // do nothing, check the next loader. } } throw new Mustache_Exception_UnknownTemplateException($name); } } load('hello'); * $goodbye = $loader->load('goodbye'); * * __halt_compiler(); * * @@ hello * Hello, {{ planet }}! * * @@ goodbye * Goodbye, cruel {{ planet }} * * Templates are deliniated by lines containing only `@@ name`. * * The InlineLoader is well-suited to micro-frameworks such as Silex: * * $app->register(new MustacheServiceProvider, array( * 'mustache.loader' => new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__) * )); * * $app->get('/{name}', function ($name) use ($app) { * return $app['mustache']->render('hello', compact('name')); * }) * ->value('name', 'world'); * * // ... * * __halt_compiler(); * * @@ hello * Hello, {{ name }}! */ class Mustache_Loader_InlineLoader implements Mustache_Loader { protected $fileName; protected $offset; protected $templates; /** * The InlineLoader requires a filename and offset to process templates. * * The magic constants `__FILE__` and `__COMPILER_HALT_OFFSET__` are usually * perfectly suited to the job: * * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__); * * Note that this only works if the loader is instantiated inside the same * file as the inline templates. If the templates are located in another * file, it would be necessary to manually specify the filename and offset. * * @param string $fileName The file to parse for inline templates * @param int $offset A string offset for the start of the templates. * This usually coincides with the `__halt_compiler` * call, and the `__COMPILER_HALT_OFFSET__` */ public function __construct($fileName, $offset) { if (!is_file($fileName)) { throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid filename.'); } if (!is_int($offset) || $offset < 0) { throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid file offset.'); } $this->fileName = $fileName; $this->offset = $offset; } /** * Load a Template by name. * * @throws Mustache_Exception_UnknownTemplateException If a template file is not found * * @param string $name * * @return string Mustache Template source */ public function load($name) { $this->loadTemplates(); if (!array_key_exists($name, $this->templates)) { throw new Mustache_Exception_UnknownTemplateException($name); } return $this->templates[$name]; } /** * Parse and load templates from the end of a source file. */ protected function loadTemplates() { if ($this->templates === null) { $this->templates = array(); $data = file_get_contents($this->fileName, false, null, $this->offset); foreach (preg_split("/^@@(?= [\w\d\.]+$)/m", $data, -1) as $chunk) { if (trim($chunk)) { list($name, $content) = explode("\n", $chunk, 2); $this->templates[trim($name)] = trim($content); } } } } } load('{{ foo }}'); // '{{ foo }}' * * This is the default Template Loader instance used by Mustache: * * $m = new Mustache; * $tpl = $m->loadTemplate('{{ foo }}'); * echo $tpl->render(array('foo' => 'bar')); // "bar" */ class Mustache_Loader_StringLoader implements Mustache_Loader { /** * Load a Template by source. * * @param string $name Mustache Template source * * @return string Mustache Template source */ public function load($name) { return $name; } } load('foo'); // equivalent to `file_get_contents(dirname(__FILE__).'/views/foo.mustache'); * * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates: * * $m = new Mustache(array( * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), * )); */ class Mustache_Loader_FilesystemLoader implements Mustache_Loader { private $baseDir; private $extension = '.mustache'; private $templates = array(); /** * Mustache filesystem Loader constructor. * * Passing an $options array allows overriding certain Loader options during instantiation: * * $options = array( * // The filename extension used for Mustache templates. Defaults to '.mustache' * 'extension' => '.ms', * ); * * @throws Mustache_Exception_RuntimeException if $baseDir does not exist * * @param string $baseDir Base directory containing Mustache template files * @param array $options Array of Loader options (default: array()) */ public function __construct($baseDir, array $options = array()) { $this->baseDir = $baseDir; if (strpos($this->baseDir, '://') === false) { $this->baseDir = realpath($this->baseDir); } if ($this->shouldCheckPath() && !is_dir($this->baseDir)) { throw new Mustache_Exception_RuntimeException(sprintf('FilesystemLoader baseDir must be a directory: %s', $baseDir)); } if (array_key_exists('extension', $options)) { if (empty($options['extension'])) { $this->extension = ''; } else { $this->extension = '.' . ltrim($options['extension'], '.'); } } } /** * Load a Template by name. * * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'); * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; * * @param string $name * * @return string Mustache Template source */ public function load($name) { if (!isset($this->templates[$name])) { $this->templates[$name] = $this->loadFile($name); } return $this->templates[$name]; } /** * Helper function for loading a Mustache file by name. * * @throws Mustache_Exception_UnknownTemplateException If a template file is not found * * @param string $name * * @return string Mustache Template source */ protected function loadFile($name) { $fileName = $this->getFileName($name); if ($this->shouldCheckPath() && !file_exists($fileName)) { throw new Mustache_Exception_UnknownTemplateException($name); } return file_get_contents($fileName); } /** * Helper function for getting a Mustache template file name. * * @param string $name * * @return string Template file name */ protected function getFileName($name) { $fileName = $this->baseDir . '/' . $name; if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) { $fileName .= $this->extension; } return $fileName; } /** * Only check if baseDir is a directory and requested templates are files if * baseDir is using the filesystem stream wrapper. * * @return bool Whether to check `is_dir` and `file_exists` */ protected function shouldCheckPath() { return strpos($this->baseDir, '://') === false || strpos($this->baseDir, 'file://') === 0; } } '.ms', * 'stat_props' => array('size', 'mtime'), * ); * * Specifying 'stat_props' overrides the stat properties used to invalidate the template cache. By default, this * uses 'mtime' and 'size', but this can be set to any of the properties supported by stat(): * * http://php.net/manual/en/function.stat.php * * You can also disable filesystem stat entirely: * * $options = array('stat_props' => null); * * But with great power comes great responsibility. Namely, if you disable stat-based cache invalidation, * YOU MUST CLEAR THE TEMPLATE CACHE YOURSELF when your templates change. Make it part of your build or deploy * process so you don't forget! * * @throws Mustache_Exception_RuntimeException if $baseDir does not exist. * * @param string $baseDir Base directory containing Mustache template files. * @param array $options Array of Loader options (default: array()) */ public function __construct($baseDir, array $options = array()) { parent::__construct($baseDir, $options); if (array_key_exists('stat_props', $options)) { if (empty($options['stat_props'])) { $this->statProps = array(); } else { $this->statProps = $options['stat_props']; } } else { $this->statProps = array('size', 'mtime'); } } /** * Helper function for loading a Mustache file by name. * * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. * * @param string $name * * @return Mustache_Source Mustache Template source */ protected function loadFile($name) { $fileName = $this->getFileName($name); if (!file_exists($fileName)) { throw new Mustache_Exception_UnknownTemplateException($name); } return new Mustache_Source_FilesystemSource($fileName, $this->statProps); } } '{{ bar }}', * 'baz' => 'Hey {{ qux }}!' * ); * * $tpl = $loader->load('foo'); // '{{ bar }}' * * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials * is set. It can also be used as a quick-and-dirty Template loader. */ class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader { private $templates; /** * ArrayLoader constructor. * * @param array $templates Associative array of Template source (default: array()) */ public function __construct(array $templates = array()) { $this->templates = $templates; } /** * Load a Template. * * @throws Mustache_Exception_UnknownTemplateException If a template file is not found * * @param string $name * * @return string Mustache Template source */ public function load($name) { if (!isset($this->templates[$name])) { throw new Mustache_Exception_UnknownTemplateException($name); } return $this->templates[$name]; } /** * Set an associative array of Template sources for this loader. * * @param array $templates */ public function setTemplates(array $templates) { $this->templates = $templates; } /** * Set a Template source by name. * * @param string $name * @param string $template Mustache Template source */ public function setTemplate($name, $template) { $this->templates[$name] = $template; } } cache($className, $compiledSource); * * The FilesystemCache benefits from any opcode caching that may be setup in your environment. So do that, k? */ class Mustache_Cache_FilesystemCache extends Mustache_Cache_AbstractCache { private $baseDir; private $fileMode; /** * Filesystem cache constructor. * * @param string $baseDir Directory for compiled templates * @param int $fileMode Override default permissions for cache files. Defaults to using the system-defined umask */ public function __construct($baseDir, $fileMode = null) { $this->baseDir = $baseDir; $this->fileMode = $fileMode; } /** * Load the class from cache using `require_once`. * * @param string $key * * @return bool */ public function load($key) { $fileName = $this->getCacheFilename($key); if (!is_file($fileName)) { return false; } require_once $fileName; return true; } /** * Cache and load the compiled class. * * @param string $key * @param string $value */ public function cache($key, $value) { $fileName = $this->getCacheFilename($key); $this->log( Mustache_Logger::DEBUG, 'Writing to template cache: "{fileName}"', array('fileName' => $fileName) ); $this->writeFile($fileName, $value); $this->load($key); } /** * Build the cache filename. * Subclasses should override for custom cache directory structures. * * @param string $name * * @return string */ protected function getCacheFilename($name) { return sprintf('%s/%s.php', $this->baseDir, $name); } /** * Create cache directory. * * @throws Mustache_Exception_RuntimeException If unable to create directory * * @param string $fileName * * @return string */ private function buildDirectoryForFilename($fileName) { $dirName = dirname($fileName); if (!is_dir($dirName)) { $this->log( Mustache_Logger::INFO, 'Creating Mustache template cache directory: "{dirName}"', array('dirName' => $dirName) ); @mkdir($dirName, 0777, true); // @codeCoverageIgnoreStart if (!is_dir($dirName)) { throw new Mustache_Exception_RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName)); } // @codeCoverageIgnoreEnd } return $dirName; } /** * Write cache file. * * @throws Mustache_Exception_RuntimeException If unable to write file * * @param string $fileName * @param string $value */ private function writeFile($fileName, $value) { $dirName = $this->buildDirectoryForFilename($fileName); $this->log( Mustache_Logger::DEBUG, 'Caching compiled template to "{fileName}"', array('fileName' => $fileName) ); $tempFile = tempnam($dirName, basename($fileName)); if (false !== @file_put_contents($tempFile, $value)) { if (@rename($tempFile, $fileName)) { $mode = isset($this->fileMode) ? $this->fileMode : (0666 & ~umask()); @chmod($fileName, $mode); return; } // @codeCoverageIgnoreStart $this->log( Mustache_Logger::ERROR, 'Unable to rename Mustache temp cache file: "{tempName}" -> "{fileName}"', array('tempName' => $tempFile, 'fileName' => $fileName) ); // @codeCoverageIgnoreEnd } // @codeCoverageIgnoreStart throw new Mustache_Exception_RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); // @codeCoverageIgnoreEnd } } log( Mustache_Logger::WARNING, 'Template cache disabled, evaluating "{className}" class at runtime', array('className' => $key) ); eval('?>' . $value); } } logger; } /** * Set a logger instance. * * @param Mustache_Logger|Psr\Log\LoggerInterface $logger */ public function setLogger($logger = null) { if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) { throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.'); } $this->logger = $logger; } /** * Add a log record if logging is enabled. * * @param int $level The logging level * @param string $message The log message * @param array $context The log context */ protected function log($level, $message, array $context = array()) { if (isset($this->logger)) { $this->logger->log($level, $message, $context); } } } stack = array($context); } } /** * Push a new Context frame onto the stack. * * @param mixed $value Object or array to use for context */ public function push($value) { array_push($this->stack, $value); } /** * Push a new Context frame onto the block context stack. * * @param mixed $value Object or array to use for block context */ public function pushBlockContext($value) { array_push($this->blockStack, $value); } /** * Pop the last Context frame from the stack. * * @return mixed Last Context frame (object or array) */ public function pop() { return array_pop($this->stack); } /** * Pop the last block Context frame from the stack. * * @return mixed Last block Context frame (object or array) */ public function popBlockContext() { return array_pop($this->blockStack); } /** * Get the last Context frame. * * @return mixed Last Context frame (object or array) */ public function last() { return end($this->stack); } /** * Find a variable in the Context stack. * * Starting with the last Context frame (the context of the innermost section), and working back to the top-level * rendering context, look for a variable with the given name: * * * If the Context frame is an associative array which contains the key $id, returns the value of that element. * * If the Context frame is an object, this will check first for a public method, then a public property named * $id. Failing both of these, it will try `__isset` and `__get` magic methods. * * If a value named $id is not found in any Context frame, returns an empty string. * * @param string $id Variable name * * @return mixed Variable value, or '' if not found */ public function find($id) { return $this->findVariableInStack($id, $this->stack); } /** * Find a 'dot notation' variable in the Context stack. * * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous * result. For example, given the following context stack: * * $data = array( * 'name' => 'Fred', * 'child' => array( * 'name' => 'Bob' * ), * ); * * ... and the Mustache following template: * * {{ child.name }} * * ... the `name` value is only searched for within the `child` value of the global Context, not within parent * Context frames. * * @param string $id Dotted variable selector * * @return mixed Variable value, or '' if not found */ public function findDot($id) { $chunks = explode('.', $id); $first = array_shift($chunks); $value = $this->findVariableInStack($first, $this->stack); foreach ($chunks as $chunk) { if ($value === '') { return $value; } $value = $this->findVariableInStack($chunk, array($value)); } return $value; } /** * Find an 'anchored dot notation' variable in the Context stack. * * This is the same as findDot(), except it looks in the top of the context * stack for the first value, rather than searching the whole context stack * and starting from there. * * @see Mustache_Context::findDot * * @throws Mustache_Exception_InvalidArgumentException if given an invalid anchored dot $id * * @param string $id Dotted variable selector * * @return mixed Variable value, or '' if not found */ public function findAnchoredDot($id) { $chunks = explode('.', $id); $first = array_shift($chunks); if ($first !== '') { throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected id for findAnchoredDot: %s', $id)); } $value = $this->last(); foreach ($chunks as $chunk) { if ($value === '') { return $value; } $value = $this->findVariableInStack($chunk, array($value)); } return $value; } /** * Find an argument in the block context stack. * * @param string $id * * @return mixed Variable value, or '' if not found */ public function findInBlock($id) { foreach ($this->blockStack as $context) { if (array_key_exists($id, $context)) { return $context[$id]; } } return ''; } /** * Helper function to find a variable in the Context stack. * * @see Mustache_Context::find * * @param string $id Variable name * @param array $stack Context stack * * @return mixed Variable value, or '' if not found */ private function findVariableInStack($id, array $stack) { for ($i = count($stack) - 1; $i >= 0; $i--) { $frame = &$stack[$i]; switch (gettype($frame)) { case 'object': if (!($frame instanceof Closure)) { // Note that is_callable() *will not work here* // See https://github.com/bobthecow/mustache.php/wiki/Magic-Methods if (method_exists($frame, $id)) { return $frame->$id(); } if (isset($frame->$id)) { return $frame->$id; } if ($frame instanceof ArrayAccess && isset($frame[$id])) { return $frame[$id]; } } break; case 'array': if (array_key_exists($id, $frame)) { return $frame[$id]; } break; } } return ''; } } mustache = $mustache; } /** * Mustache Template instances can be treated as a function and rendered by simply calling them. * * $m = new Mustache_Engine; * $tpl = $m->loadTemplate('Hello, {{ name }}!'); * echo $tpl(array('name' => 'World')); // "Hello, World!" * * @see Mustache_Template::render * * @param mixed $context Array or object rendering context (default: array()) * * @return string Rendered template */ public function __invoke($context = array()) { return $this->render($context); } /** * Render this template given the rendering context. * * @param mixed $context Array or object rendering context (default: array()) * * @return string Rendered template */ public function render($context = array()) { return $this->renderInternal( $this->prepareContextStack($context) ); } /** * Internal rendering method implemented by Mustache Template concrete subclasses. * * This is where the magic happens :) * * NOTE: This method is not part of the Mustache.php public API. * * @param Mustache_Context $context * @param string $indent (default: '') * * @return string Rendered template */ abstract public function renderInternal(Mustache_Context $context, $indent = ''); /** * Tests whether a value should be iterated over (e.g. in a section context). * * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, * Java, Python, etc. * * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish * between between a list of things (numeric, normalized array) and a set of variables to be used as section context * (associative array). In other words, this will be iterated over: * * $items = array( * array('name' => 'foo'), * array('name' => 'bar'), * array('name' => 'baz'), * ); * * ... but this will be used as a section context block: * * $items = array( * 1 => array('name' => 'foo'), * 'banana' => array('name' => 'bar'), * 42 => array('name' => 'baz'), * ); * * @param mixed $value * * @return bool True if the value is 'iterable' */ protected function isIterable($value) { switch (gettype($value)) { case 'object': return $value instanceof Traversable; case 'array': $i = 0; foreach ($value as $k => $v) { if ($k !== $i++) { return false; } } return true; default: return false; } } /** * Helper method to prepare the Context stack. * * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present. * * @param mixed $context Optional first context frame (default: null) * * @return Mustache_Context */ protected function prepareContextStack($context = null) { $stack = new Mustache_Context(); $helpers = $this->mustache->getHelpers(); if (!$helpers->isEmpty()) { $stack->push($helpers); } if (!empty($context)) { $stack->push($context); } return $stack; } /** * Resolve a context value. * * Invoke the value if it is callable, otherwise return the value. * * @param mixed $value * @param Mustache_Context $context * * @return string */ protected function resolveValue($value, Mustache_Context $context) { if (($this->strictCallables ? is_object($value) : !is_string($value)) && is_callable($value)) { return $this->mustache ->loadLambda((string) call_user_func($value)) ->renderInternal($context); } return $value; } } true, self::PRAGMA_BLOCKS => true, self::PRAGMA_ANCHORED_DOT => true, ); // Template cache private $templates = array(); // Environment private $templateClassPrefix = '__Mustache_'; private $cache; private $lambdaCache; private $cacheLambdaTemplates = false; private $loader; private $partialsLoader; private $helpers; private $escape; private $entityFlags = ENT_COMPAT; private $charset = 'UTF-8'; private $logger; private $strictCallables = false; private $pragmas = array(); private $delimiters; // Services private $tokenizer; private $parser; private $compiler; /** * Mustache class constructor. * * Passing an $options array allows overriding certain Mustache options during instantiation: * * $options = array( * // The class prefix for compiled templates. Defaults to '__Mustache_'. * 'template_class_prefix' => '__MyTemplates_', * * // A Mustache cache instance or a cache directory string for compiled templates. * // Mustache will not cache templates unless this is set. * 'cache' => dirname(__FILE__).'/tmp/cache/mustache', * * // Override default permissions for cache files. Defaults to using the system-defined umask. It is * // *strongly* recommended that you configure your umask properly rather than overriding permissions here. * 'cache_file_mode' => 0666, * * // Optionally, enable caching for lambda section templates. This is generally not recommended, as lambda * // sections are often too dynamic to benefit from caching. * 'cache_lambda_templates' => true, * * // Customize the tag delimiters used by this engine instance. Note that overriding here changes the * // delimiters used to parse all templates and partials loaded by this instance. To override just for a * // single template, use an inline "change delimiters" tag at the start of the template file: * // * // {{=<% %>=}} * // * 'delimiters' => '<% %>', * * // A Mustache template loader instance. Uses a StringLoader if not specified. * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), * * // A Mustache loader instance for partials. * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), * * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as * // efficient or lazy as a Filesystem (or database) loader. * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')), * * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order * // sections), or any other valid Mustache context value. They will be prepended to the context stack, * // so they will be available in any template loaded by this Mustache instance. * 'helpers' => array('i18n' => function ($text) { * // do something translatey here... * }), * * // An 'escape' callback, responsible for escaping double-mustache variables. * 'escape' => function ($value) { * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8'); * }, * * // Type argument for `htmlspecialchars`. Defaults to ENT_COMPAT. You may prefer ENT_QUOTES. * 'entity_flags' => ENT_QUOTES, * * // Character set for `htmlspecialchars`. Defaults to 'UTF-8'. Use 'UTF-8'. * 'charset' => 'ISO-8859-1', * * // A Mustache Logger instance. No logging will occur unless this is set. Using a PSR-3 compatible * // logging library -- such as Monolog -- is highly recommended. A simple stream logger implementation is * // available as well: * 'logger' => new Mustache_Logger_StreamLogger('php://stderr'), * * // Only treat Closure instances and invokable classes as callable. If true, values like * // `array('ClassName', 'methodName')` and `array($classInstance, 'methodName')`, which are traditionally * // "callable" in PHP, are not called to resolve variables for interpolation or section contexts. This * // helps protect against arbitrary code execution when user input is passed directly into the template. * // This currently defaults to false, but will default to true in v3.0. * 'strict_callables' => true, * * // Enable pragmas across all templates, regardless of the presence of pragma tags in the individual * // templates. * 'pragmas' => [Mustache_Engine::PRAGMA_FILTERS], * ); * * @throws Mustache_Exception_InvalidArgumentException If `escape` option is not callable * * @param array $options (default: array()) */ public function __construct(array $options = array()) { if (isset($options['template_class_prefix'])) { if ((string) $options['template_class_prefix'] === '') { throw new Mustache_Exception_InvalidArgumentException('Mustache Constructor "template_class_prefix" must not be empty'); } $this->templateClassPrefix = $options['template_class_prefix']; } if (isset($options['cache'])) { $cache = $options['cache']; if (is_string($cache)) { $mode = isset($options['cache_file_mode']) ? $options['cache_file_mode'] : null; $cache = new Mustache_Cache_FilesystemCache($cache, $mode); } $this->setCache($cache); } if (isset($options['cache_lambda_templates'])) { $this->cacheLambdaTemplates = (bool) $options['cache_lambda_templates']; } if (isset($options['loader'])) { $this->setLoader($options['loader']); } if (isset($options['partials_loader'])) { $this->setPartialsLoader($options['partials_loader']); } if (isset($options['partials'])) { $this->setPartials($options['partials']); } if (isset($options['helpers'])) { $this->setHelpers($options['helpers']); } if (isset($options['escape'])) { if (!is_callable($options['escape'])) { throw new Mustache_Exception_InvalidArgumentException('Mustache Constructor "escape" option must be callable'); } $this->escape = $options['escape']; } if (isset($options['entity_flags'])) { $this->entityFlags = $options['entity_flags']; } if (isset($options['charset'])) { $this->charset = $options['charset']; } if (isset($options['logger'])) { $this->setLogger($options['logger']); } if (isset($options['strict_callables'])) { $this->strictCallables = $options['strict_callables']; } if (isset($options['delimiters'])) { $this->delimiters = $options['delimiters']; } if (isset($options['pragmas'])) { foreach ($options['pragmas'] as $pragma) { if (!isset(self::$knownPragmas[$pragma])) { throw new Mustache_Exception_InvalidArgumentException(sprintf('Unknown pragma: "%s".', $pragma)); } $this->pragmas[$pragma] = true; } } } /** * Shortcut 'render' invocation. * * Equivalent to calling `$mustache->loadTemplate($template)->render($context);` * * @see Mustache_Engine::loadTemplate * @see Mustache_Template::render * * @param string $template * @param mixed $context (default: array()) * * @return string Rendered template */ public function render($template, $context = array()) { return $this->loadTemplate($template)->render($context); } /** * Get the current Mustache escape callback. * * @return callable|null */ public function getEscape() { return $this->escape; } /** * Get the current Mustache entitity type to escape. * * @return int */ public function getEntityFlags() { return $this->entityFlags; } /** * Get the current Mustache character set. * * @return string */ public function getCharset() { return $this->charset; } /** * Get the current globally enabled pragmas. * * @return array */ public function getPragmas() { return array_keys($this->pragmas); } /** * Set the Mustache template Loader instance. * * @param Mustache_Loader $loader */ public function setLoader(Mustache_Loader $loader) { $this->loader = $loader; } /** * Get the current Mustache template Loader instance. * * If no Loader instance has been explicitly specified, this method will instantiate and return * a StringLoader instance. * * @return Mustache_Loader */ public function getLoader() { if (!isset($this->loader)) { $this->loader = new Mustache_Loader_StringLoader(); } return $this->loader; } /** * Set the Mustache partials Loader instance. * * @param Mustache_Loader $partialsLoader */ public function setPartialsLoader(Mustache_Loader $partialsLoader) { $this->partialsLoader = $partialsLoader; } /** * Get the current Mustache partials Loader instance. * * If no Loader instance has been explicitly specified, this method will instantiate and return * an ArrayLoader instance. * * @return Mustache_Loader */ public function getPartialsLoader() { if (!isset($this->partialsLoader)) { $this->partialsLoader = new Mustache_Loader_ArrayLoader(); } return $this->partialsLoader; } /** * Set partials for the current partials Loader instance. * * @throws Mustache_Exception_RuntimeException If the current Loader instance is immutable * * @param array $partials (default: array()) */ public function setPartials(array $partials = array()) { if (!isset($this->partialsLoader)) { $this->partialsLoader = new Mustache_Loader_ArrayLoader(); } if (!$this->partialsLoader instanceof Mustache_Loader_MutableLoader) { throw new Mustache_Exception_RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); } $this->partialsLoader->setTemplates($partials); } /** * Set an array of Mustache helpers. * * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in * any template loaded by this Mustache instance. * * @throws Mustache_Exception_InvalidArgumentException if $helpers is not an array or Traversable * * @param array|Traversable $helpers */ public function setHelpers($helpers) { if (!is_array($helpers) && !$helpers instanceof Traversable) { throw new Mustache_Exception_InvalidArgumentException('setHelpers expects an array of helpers'); } $this->getHelpers()->clear(); foreach ($helpers as $name => $helper) { $this->addHelper($name, $helper); } } /** * Get the current set of Mustache helpers. * * @see Mustache_Engine::setHelpers * * @return Mustache_HelperCollection */ public function getHelpers() { if (!isset($this->helpers)) { $this->helpers = new Mustache_HelperCollection(); } return $this->helpers; } /** * Add a new Mustache helper. * * @see Mustache_Engine::setHelpers * * @param string $name * @param mixed $helper */ public function addHelper($name, $helper) { $this->getHelpers()->add($name, $helper); } /** * Get a Mustache helper by name. * * @see Mustache_Engine::setHelpers * * @param string $name * * @return mixed Helper */ public function getHelper($name) { return $this->getHelpers()->get($name); } /** * Check whether this Mustache instance has a helper. * * @see Mustache_Engine::setHelpers * * @param string $name * * @return bool True if the helper is present */ public function hasHelper($name) { return $this->getHelpers()->has($name); } /** * Remove a helper by name. * * @see Mustache_Engine::setHelpers * * @param string $name */ public function removeHelper($name) { $this->getHelpers()->remove($name); } /** * Set the Mustache Logger instance. * * @throws Mustache_Exception_InvalidArgumentException If logger is not an instance of Mustache_Logger or Psr\Log\LoggerInterface * * @param Mustache_Logger|Psr\Log\LoggerInterface $logger */ public function setLogger($logger = null) { if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) { throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.'); } if ($this->getCache()->getLogger() === null) { $this->getCache()->setLogger($logger); } $this->logger = $logger; } /** * Get the current Mustache Logger instance. * * @return Mustache_Logger|Psr\Log\LoggerInterface */ public function getLogger() { return $this->logger; } /** * Set the Mustache Tokenizer instance. * * @param Mustache_Tokenizer $tokenizer */ public function setTokenizer(Mustache_Tokenizer $tokenizer) { $this->tokenizer = $tokenizer; } /** * Get the current Mustache Tokenizer instance. * * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. * * @return Mustache_Tokenizer */ public function getTokenizer() { if (!isset($this->tokenizer)) { $this->tokenizer = new Mustache_Tokenizer(); } return $this->tokenizer; } /** * Set the Mustache Parser instance. * * @param Mustache_Parser $parser */ public function setParser(Mustache_Parser $parser) { $this->parser = $parser; } /** * Get the current Mustache Parser instance. * * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. * * @return Mustache_Parser */ public function getParser() { if (!isset($this->parser)) { $this->parser = new Mustache_Parser(); } return $this->parser; } /** * Set the Mustache Compiler instance. * * @param Mustache_Compiler $compiler */ public function setCompiler(Mustache_Compiler $compiler) { $this->compiler = $compiler; } /** * Get the current Mustache Compiler instance. * * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. * * @return Mustache_Compiler */ public function getCompiler() { if (!isset($this->compiler)) { $this->compiler = new Mustache_Compiler(); } return $this->compiler; } /** * Set the Mustache Cache instance. * * @param Mustache_Cache $cache */ public function setCache(Mustache_Cache $cache) { if (isset($this->logger) && $cache->getLogger() === null) { $cache->setLogger($this->getLogger()); } $this->cache = $cache; } /** * Get the current Mustache Cache instance. * * If no Cache instance has been explicitly specified, this method will instantiate and return a new one. * * @return Mustache_Cache */ public function getCache() { if (!isset($this->cache)) { $this->setCache(new Mustache_Cache_NoopCache()); } return $this->cache; } /** * Get the current Lambda Cache instance. * * If 'cache_lambda_templates' is enabled, this is the default cache instance. Otherwise, it is a NoopCache. * * @see Mustache_Engine::getCache * * @return Mustache_Cache */ protected function getLambdaCache() { if ($this->cacheLambdaTemplates) { return $this->getCache(); } if (!isset($this->lambdaCache)) { $this->lambdaCache = new Mustache_Cache_NoopCache(); } return $this->lambdaCache; } /** * Helper method to generate a Mustache template class. * * This method must be updated any time options are added which make it so * the same template could be parsed and compiled multiple different ways. * * @param string|Mustache_Source $source * * @return string Mustache Template class name */ public function getTemplateClassName($source) { // For the most part, adding a new option here should do the trick. // // Pick a value here which is unique for each possible way the template // could be compiled... but not necessarily unique per option value. See // escape below, which only needs to differentiate between 'custom' and // 'default' escapes. // // Keep this list in alphabetical order :) $chunks = array( 'charset' => $this->charset, 'delimiters' => $this->delimiters ? $this->delimiters : '{{ }}', 'entityFlags' => $this->entityFlags, 'escape' => isset($this->escape) ? 'custom' : 'default', 'key' => ($source instanceof Mustache_Source) ? $source->getKey() : 'source', 'pragmas' => $this->getPragmas(), 'strictCallables' => $this->strictCallables, 'version' => self::VERSION, ); $key = json_encode($chunks); // Template Source instances have already provided their own source key. For strings, just include the whole // source string in the md5 hash. if (!$source instanceof Mustache_Source) { $key .= "\n" . $source; } return $this->templateClassPrefix . md5($key); } /** * Load a Mustache Template by name. * * @param string $name * * @return Mustache_Template */ public function loadTemplate($name) { return $this->loadSource($this->getLoader()->load($name)); } /** * Load a Mustache partial Template by name. * * This is a helper method used internally by Template instances for loading partial templates. You can most likely * ignore it completely. * * @param string $name * * @return Mustache_Template */ public function loadPartial($name) { try { if (isset($this->partialsLoader)) { $loader = $this->partialsLoader; } elseif (isset($this->loader) && !$this->loader instanceof Mustache_Loader_StringLoader) { $loader = $this->loader; } else { throw new Mustache_Exception_UnknownTemplateException($name); } return $this->loadSource($loader->load($name)); } catch (Mustache_Exception_UnknownTemplateException $e) { // If the named partial cannot be found, log then return null. $this->log( Mustache_Logger::WARNING, 'Partial not found: "{name}"', array('name' => $e->getTemplateName()) ); } } /** * Load a Mustache lambda Template by source. * * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most * likely ignore it completely. * * @param string $source * @param string $delims (default: null) * * @return Mustache_Template */ public function loadLambda($source, $delims = null) { if ($delims !== null) { $source = $delims . "\n" . $source; } return $this->loadSource($source, $this->getLambdaCache()); } /** * Instantiate and return a Mustache Template instance by source. * * Optionally provide a Mustache_Cache instance. This is used internally by Mustache_Engine::loadLambda to respect * the 'cache_lambda_templates' configuration option. * * @see Mustache_Engine::loadTemplate * @see Mustache_Engine::loadPartial * @see Mustache_Engine::loadLambda * * @param string|Mustache_Source $source * @param Mustache_Cache $cache (default: null) * * @return Mustache_Template */ private function loadSource($source, Mustache_Cache $cache = null) { $className = $this->getTemplateClassName($source); if (!isset($this->templates[$className])) { if ($cache === null) { $cache = $this->getCache(); } if (!class_exists($className, false)) { if (!$cache->load($className)) { $compiled = $this->compile($source); $cache->cache($className, $compiled); } } $this->log( Mustache_Logger::DEBUG, 'Instantiating template: "{className}"', array('className' => $className) ); $this->templates[$className] = new $className($this); } return $this->templates[$className]; } /** * Helper method to tokenize a Mustache template. * * @see Mustache_Tokenizer::scan * * @param string $source * * @return array Tokens */ private function tokenize($source) { return $this->getTokenizer()->scan($source, $this->delimiters); } /** * Helper method to parse a Mustache template. * * @see Mustache_Parser::parse * * @param string $source * * @return array Token tree */ private function parse($source) { $parser = $this->getParser(); $parser->setPragmas($this->getPragmas()); return $parser->parse($this->tokenize($source)); } /** * Helper method to compile a Mustache template. * * @see Mustache_Compiler::compile * * @param string|Mustache_Source $source * * @return string generated Mustache template class code */ private function compile($source) { $name = $this->getTemplateClassName($source); $this->log( Mustache_Logger::INFO, 'Compiling template to "{className}" class', array('className' => $name) ); if ($source instanceof Mustache_Source) { $source = $source->getSource(); } $tree = $this->parse($source); $compiler = $this->getCompiler(); $compiler->setPragmas($this->getPragmas()); return $compiler->compile($source, $tree, $name, isset($this->escape), $this->charset, $this->strictCallables, $this->entityFlags); } /** * Add a log record if logging is enabled. * * @param int $level The logging level * @param string $message The log message * @param array $context The log context */ private function log($level, $message, array $context = array()) { if (isset($this->logger)) { $this->logger->log($level, $message, $context); } } } pragmas = $this->defaultPragmas; $this->sections = array(); $this->blocks = array(); $this->source = $source; $this->indentNextLine = true; $this->customEscape = $customEscape; $this->entityFlags = $entityFlags; $this->charset = $charset; $this->strictCallables = $strictCallables; return $this->writeCode($tree, $name); } /** * Enable pragmas across all templates, regardless of the presence of pragma * tags in the individual templates. * * @internal Users should set global pragmas in Mustache_Engine, not here :) * * @param string[] $pragmas */ public function setPragmas(array $pragmas) { $this->pragmas = array(); foreach ($pragmas as $pragma) { $this->pragmas[$pragma] = true; } $this->defaultPragmas = $this->pragmas; } /** * Helper function for walking the Mustache token parse tree. * * @throws Mustache_Exception_SyntaxException upon encountering unknown token types * * @param array $tree Parse tree of Mustache tokens * @param int $level (default: 0) * * @return string Generated PHP source code */ private function walk(array $tree, $level = 0) { $code = ''; $level++; foreach ($tree as $node) { switch ($node[Mustache_Tokenizer::TYPE]) { case Mustache_Tokenizer::T_PRAGMA: $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true; break; case Mustache_Tokenizer::T_SECTION: $code .= $this->section( $node[Mustache_Tokenizer::NODES], $node[Mustache_Tokenizer::NAME], isset($node[Mustache_Tokenizer::FILTERS]) ? $node[Mustache_Tokenizer::FILTERS] : array(), $node[Mustache_Tokenizer::INDEX], $node[Mustache_Tokenizer::END], $node[Mustache_Tokenizer::OTAG], $node[Mustache_Tokenizer::CTAG], $level ); break; case Mustache_Tokenizer::T_INVERTED: $code .= $this->invertedSection( $node[Mustache_Tokenizer::NODES], $node[Mustache_Tokenizer::NAME], isset($node[Mustache_Tokenizer::FILTERS]) ? $node[Mustache_Tokenizer::FILTERS] : array(), $level ); break; case Mustache_Tokenizer::T_PARTIAL: $code .= $this->partial( $node[Mustache_Tokenizer::NAME], isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', $level ); break; case Mustache_Tokenizer::T_PARENT: $code .= $this->parent( $node[Mustache_Tokenizer::NAME], isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', $node[Mustache_Tokenizer::NODES], $level ); break; case Mustache_Tokenizer::T_BLOCK_ARG: $code .= $this->blockArg( $node[Mustache_Tokenizer::NODES], $node[Mustache_Tokenizer::NAME], $node[Mustache_Tokenizer::INDEX], $node[Mustache_Tokenizer::END], $node[Mustache_Tokenizer::OTAG], $node[Mustache_Tokenizer::CTAG], $level ); break; case Mustache_Tokenizer::T_BLOCK_VAR: $code .= $this->blockVar( $node[Mustache_Tokenizer::NODES], $node[Mustache_Tokenizer::NAME], $node[Mustache_Tokenizer::INDEX], $node[Mustache_Tokenizer::END], $node[Mustache_Tokenizer::OTAG], $node[Mustache_Tokenizer::CTAG], $level ); break; case Mustache_Tokenizer::T_COMMENT: break; case Mustache_Tokenizer::T_ESCAPED: case Mustache_Tokenizer::T_UNESCAPED: case Mustache_Tokenizer::T_UNESCAPED_2: $code .= $this->variable( $node[Mustache_Tokenizer::NAME], isset($node[Mustache_Tokenizer::FILTERS]) ? $node[Mustache_Tokenizer::FILTERS] : array(), $node[Mustache_Tokenizer::TYPE] === Mustache_Tokenizer::T_ESCAPED, $level ); break; case Mustache_Tokenizer::T_TEXT: $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); break; default: throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node); } } return $code; } const KLASS = 'lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context); $buffer = \'\'; %s return $buffer; } %s %s }'; const KLASS_NO_LAMBDAS = 'walk($tree); $sections = implode("\n", $this->sections); $blocks = implode("\n", $this->blocks); $klass = empty($this->sections) && empty($this->blocks) ? self::KLASS_NO_LAMBDAS : self::KLASS; $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : ''; return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections, $blocks); } const BLOCK_VAR = ' $blockFunction = $context->findInBlock(%s); if (is_callable($blockFunction)) { $buffer .= call_user_func($blockFunction, $context); %s} '; const BLOCK_VAR_ELSE = '} else {%s'; /** * Generate Mustache Template inheritance block variable PHP source. * * @param array $nodes Array of child tokens * @param string $id Section name * @param int $start Section start offset * @param int $end Section end offset * @param string $otag Current Mustache opening tag * @param string $ctag Current Mustache closing tag * @param int $level * * @return string Generated PHP source code */ private function blockVar($nodes, $id, $start, $end, $otag, $ctag, $level) { $id = var_export($id, true); $else = $this->walk($nodes, $level); if ($else !== '') { $else = sprintf($this->prepare(self::BLOCK_VAR_ELSE, $level + 1, false, true), $else); } return sprintf($this->prepare(self::BLOCK_VAR, $level), $id, $else); } const BLOCK_ARG = '%s => array($this, \'block%s\'),'; /** * Generate Mustache Template inheritance block argument PHP source. * * @param array $nodes Array of child tokens * @param string $id Section name * @param int $start Section start offset * @param int $end Section end offset * @param string $otag Current Mustache opening tag * @param string $ctag Current Mustache closing tag * @param int $level * * @return string Generated PHP source code */ private function blockArg($nodes, $id, $start, $end, $otag, $ctag, $level) { $key = $this->block($nodes); $keystr = var_export($key, true); $id = var_export($id, true); return sprintf($this->prepare(self::BLOCK_ARG, $level), $id, $key); } const BLOCK_FUNCTION = ' public function block%s($context) { $indent = $buffer = \'\';%s return $buffer; } '; /** * Generate Mustache Template inheritance block function PHP source. * * @param array $nodes Array of child tokens * * @return string key of new block function */ private function block($nodes) { $code = $this->walk($nodes, 0); $key = ucfirst(md5($code)); if (!isset($this->blocks[$key])) { $this->blocks[$key] = sprintf($this->prepare(self::BLOCK_FUNCTION, 0), $key, $code); } return $key; } const SECTION_CALL = ' // %s section $value = $context->%s(%s);%s $buffer .= $this->section%s($context, $indent, $value); '; const SECTION = ' private function section%s(Mustache_Context $context, $indent, $value) { $buffer = \'\'; if (%s) { $source = %s; $result = call_user_func($value, $source, %s); if (strpos($result, \'{{\') === false) { $buffer .= $result; } else { $buffer .= $this->mustache ->loadLambda((string) $result%s) ->renderInternal($context); } } elseif (!empty($value)) { $values = $this->isIterable($value) ? $value : array($value); foreach ($values as $value) { $context->push($value); %s $context->pop(); } } return $buffer; } '; /** * Generate Mustache Template section PHP source. * * @param array $nodes Array of child tokens * @param string $id Section name * @param string[] $filters Array of filters * @param int $start Section start offset * @param int $end Section end offset * @param string $otag Current Mustache opening tag * @param string $ctag Current Mustache closing tag * @param int $level * * @return string Generated section PHP source code */ private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level) { $source = var_export(substr($this->source, $start, $end - $start), true); $callable = $this->getCallable(); if ($otag !== '{{' || $ctag !== '}}') { $delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true); $helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag); $delims = ', ' . $delimTag; } else { $helper = '$this->lambdaHelper'; $delims = ''; } $key = ucfirst(md5($delims . "\n" . $source)); if (!isset($this->sections[$key])) { $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2)); } $method = $this->getFindMethod($id); $id = var_export($id, true); $filters = $this->getFilters($filters, $level); return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key); } const INVERTED_SECTION = ' // %s inverted section $value = $context->%s(%s);%s if (empty($value)) { %s } '; /** * Generate Mustache Template inverted section PHP source. * * @param array $nodes Array of child tokens * @param string $id Section name * @param string[] $filters Array of filters * @param int $level * * @return string Generated inverted section PHP source code */ private function invertedSection($nodes, $id, $filters, $level) { $method = $this->getFindMethod($id); $id = var_export($id, true); $filters = $this->getFilters($filters, $level); return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $filters, $this->walk($nodes, $level)); } const PARTIAL_INDENT = ', $indent . %s'; const PARTIAL = ' if ($partial = $this->mustache->loadPartial(%s)) { $buffer .= $partial->renderInternal($context%s); } '; /** * Generate Mustache Template partial call PHP source. * * @param string $id Partial name * @param string $indent Whitespace indent to apply to partial * @param int $level * * @return string Generated partial call PHP source code */ private function partial($id, $indent, $level) { if ($indent !== '') { $indentParam = sprintf(self::PARTIAL_INDENT, var_export($indent, true)); } else { $indentParam = ''; } return sprintf( $this->prepare(self::PARTIAL, $level), var_export($id, true), $indentParam ); } const PARENT = ' if ($parent = $this->mustache->loadPartial(%s)) { $context->pushBlockContext(array(%s )); $buffer .= $parent->renderInternal($context, $indent); $context->popBlockContext(); } '; const PARENT_NO_CONTEXT = ' if ($parent = $this->mustache->loadPartial(%s)) { $buffer .= $parent->renderInternal($context, $indent); } '; /** * Generate Mustache Template inheritance parent call PHP source. * * @param string $id Parent tag name * @param string $indent Whitespace indent to apply to parent * @param array $children Child nodes * @param int $level * * @return string Generated PHP source code */ private function parent($id, $indent, array $children, $level) { $realChildren = array_filter($children, array(__CLASS__, 'onlyBlockArgs')); if (empty($realChildren)) { return sprintf($this->prepare(self::PARENT_NO_CONTEXT, $level), var_export($id, true)); } return sprintf( $this->prepare(self::PARENT, $level), var_export($id, true), $this->walk($realChildren, $level + 1) ); } /** * Helper method for filtering out non-block-arg tokens. * * @param array $node * * @return bool True if $node is a block arg token */ private static function onlyBlockArgs(array $node) { return $node[Mustache_Tokenizer::TYPE] === Mustache_Tokenizer::T_BLOCK_ARG; } const VARIABLE = ' $value = $this->resolveValue($context->%s(%s), $context);%s $buffer .= %s%s; '; /** * Generate Mustache Template variable interpolation PHP source. * * @param string $id Variable name * @param string[] $filters Array of filters * @param bool $escape Escape the variable value for output? * @param int $level * * @return string Generated variable interpolation PHP source */ private function variable($id, $filters, $escape, $level) { $method = $this->getFindMethod($id); $id = ($method !== 'last') ? var_export($id, true) : ''; $filters = $this->getFilters($filters, $level); $value = $escape ? $this->getEscape() : '$value'; return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value); } const FILTER = ' $filter = $context->%s(%s); if (!(%s)) { throw new Mustache_Exception_UnknownFilterException(%s); } $value = call_user_func($filter, $value);%s '; /** * Generate Mustache Template variable filtering PHP source. * * @param string[] $filters Array of filters * @param int $level * * @return string Generated filter PHP source */ private function getFilters(array $filters, $level) { if (empty($filters)) { return ''; } $name = array_shift($filters); $method = $this->getFindMethod($name); $filter = ($method !== 'last') ? var_export($name, true) : ''; $callable = $this->getCallable('$filter'); $msg = var_export($name, true); return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilters($filters, $level)); } const LINE = '$buffer .= "\n";'; const TEXT = '$buffer .= %s%s;'; /** * Generate Mustache Template output Buffer call PHP source. * * @param string $text * @param int $level * * @return string Generated output Buffer call PHP source */ private function text($text, $level) { $indentNextLine = (substr($text, -1) === "\n"); $code = sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true)); $this->indentNextLine = $indentNextLine; return $code; } /** * Prepare PHP source code snippet for output. * * @param string $text * @param int $bonus Additional indent level (default: 0) * @param bool $prependNewline Prepend a newline to the snippet? (default: true) * @param bool $appendNewline Append a newline to the snippet? (default: false) * * @return string PHP source code snippet */ private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false) { $text = ($prependNewline ? "\n" : '') . trim($text); if ($prependNewline) { $bonus++; } if ($appendNewline) { $text .= "\n"; } return preg_replace("/\n( {8})?/", "\n" . str_repeat(' ', $bonus * 4), $text); } const DEFAULT_ESCAPE = 'htmlspecialchars(%s, %s, %s)'; const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)'; /** * Get the current escaper. * * @param string $value (default: '$value') * * @return string Either a custom callback, or an inline call to `htmlspecialchars` */ private function getEscape($value = '$value') { if ($this->customEscape) { return sprintf(self::CUSTOM_ESCAPE, $value); } return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->entityFlags, true), var_export($this->charset, true)); } /** * Select the appropriate Context `find` method for a given $id. * * The return value will be one of `find`, `findDot`, `findAnchoredDot` or `last`. * * @see Mustache_Context::find * @see Mustache_Context::findDot * @see Mustache_Context::last * * @param string $id Variable name * * @return string `find` method name */ private function getFindMethod($id) { if ($id === '.') { return 'last'; } if (isset($this->pragmas[Mustache_Engine::PRAGMA_ANCHORED_DOT]) && $this->pragmas[Mustache_Engine::PRAGMA_ANCHORED_DOT]) { if (substr($id, 0, 1) === '.') { return 'findAnchoredDot'; } } if (strpos($id, '.') === false) { return 'find'; } return 'findDot'; } const IS_CALLABLE = '!is_string(%s) && is_callable(%s)'; const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)'; /** * Helper function to compile strict vs lax "is callable" logic. * * @param string $variable (default: '$value') * * @return string "is callable" logic */ private function getCallable($variable = '$value') { $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE; return sprintf($tpl, $variable, $variable); } const LINE_INDENT = '$indent . '; /** * Get the current $indent prefix to write to the buffer. * * @return string "$indent . " or "" */ private function flushIndent() { if (!$this->indentNextLine) { return ''; } $this->indentNextLine = false; return self::LINE_INDENT; } } $helper` pairs. * * @throws Mustache_Exception_InvalidArgumentException if the $helpers argument isn't an array or Traversable * * @param array|Traversable $helpers (default: null) */ public function __construct($helpers = null) { if ($helpers === null) { return; } if (!is_array($helpers) && !$helpers instanceof Traversable) { throw new Mustache_Exception_InvalidArgumentException('HelperCollection constructor expects an array of helpers'); } foreach ($helpers as $name => $helper) { $this->add($name, $helper); } } /** * Magic mutator. * * @see Mustache_HelperCollection::add * * @param string $name * @param mixed $helper */ public function __set($name, $helper) { $this->add($name, $helper); } /** * Add a helper to this collection. * * @param string $name * @param mixed $helper */ public function add($name, $helper) { $this->helpers[$name] = $helper; } /** * Magic accessor. * * @see Mustache_HelperCollection::get * * @param string $name * * @return mixed Helper */ public function __get($name) { return $this->get($name); } /** * Get a helper by name. * * @throws Mustache_Exception_UnknownHelperException If helper does not exist * * @param string $name * * @return mixed Helper */ public function get($name) { if (!$this->has($name)) { throw new Mustache_Exception_UnknownHelperException($name); } return $this->helpers[$name]; } /** * Magic isset(). * * @see Mustache_HelperCollection::has * * @param string $name * * @return bool True if helper is present */ public function __isset($name) { return $this->has($name); } /** * Check whether a given helper is present in the collection. * * @param string $name * * @return bool True if helper is present */ public function has($name) { return array_key_exists($name, $this->helpers); } /** * Magic unset(). * * @see Mustache_HelperCollection::remove * * @param string $name */ public function __unset($name) { $this->remove($name); } /** * Check whether a given helper is present in the collection. * * @throws Mustache_Exception_UnknownHelperException if the requested helper is not present * * @param string $name */ public function remove($name) { if (!$this->has($name)) { throw new Mustache_Exception_UnknownHelperException($name); } unset($this->helpers[$name]); } /** * Clear the helper collection. * * Removes all helpers from this collection */ public function clear() { $this->helpers = array(); } /** * Check whether the helper collection is empty. * * @return bool True if the collection is empty */ public function isEmpty() { return empty($this->helpers); } } fileName = $fileName; $this->statProps = $statProps; } /** * Get the Source key (used to generate the compiled class name). * * @throws RuntimeException when a source file cannot be read * * @return string */ public function getKey() { $chunks = array( 'fileName' => $this->fileName, ); if (!empty($this->statProps)) { if (!isset($this->stat)) { $this->stat = @stat($this->fileName); } if ($this->stat === false) { throw new RuntimeException(sprintf('Failed to read source file "%s".', $this->fileName)); } foreach ($this->statProps as $prop) { $chunks[$prop] = $this->stat[$prop]; } } return json_encode($chunks); } /** * Get the template Source. * * @return string */ public function getSource() { return file_get_contents($this->fileName); } } helperName = $helperName; $message = sprintf('Unknown helper: %s', $helperName); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { parent::__construct($message, 0, $previous); } else { parent::__construct($message); // @codeCoverageIgnore } } public function getHelperName() { return $this->helperName; } } token = $token; if (version_compare(PHP_VERSION, '5.3.0', '>=')) { parent::__construct($msg, 0, $previous); } else { parent::__construct($msg); // @codeCoverageIgnore } } /** * @return array */ public function getToken() { return $this->token; } } filterName = $filterName; $message = sprintf('Unknown filter: %s', $filterName); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { parent::__construct($message, 0, $previous); } else { parent::__construct($message); // @codeCoverageIgnore } } public function getFilterName() { return $this->filterName; } } templateName = $templateName; $message = sprintf('Unknown template: %s', $templateName); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { parent::__construct($message, 0, $previous); } else { parent::__construct($message); // @codeCoverageIgnore } } public function getTemplateName() { return $this->templateName; } } ' . PHP_EOL; echo PHP_EOL; echo ' version:' . PHP_EOL; echo ' Version of the package, in the form of major.minor.bug' . PHP_EOL; echo PHP_EOL; echo ' stability:' . PHP_EOL; echo ' One of alpha, beta, stable' . PHP_EOL; die(); } if (!isset($argv[2])) { die('You must provide the stability (alpha, beta, or stable)'); } $context = array( 'date' => gmdate('Y-m-d'), 'time' => gmdate('H:m:00'), 'version' => $argv[1], 'api_version' => $argv[1], 'stability' => $argv[2], 'api_stability' => $argv[2], ); $context['files'] = ''; $path = realpath(dirname(__FILE__).'/../library/Requests'); foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { if (preg_match('/\.php$/', $file)) { $name = str_replace($path . DIRECTORY_SEPARATOR, '', $file); $name = str_replace(DIRECTORY_SEPARATOR, '/', $name); $context['files'][] = "\t\t\t\t\t" . ''; } } $context['files'] = implode("\n", $context['files']); $template = file_get_contents(dirname(__FILE__).'/../package.xml.tpl'); $content = preg_replace_callback('/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/', 'replace_parameters', $template); file_put_contents(dirname(__FILE__).'/../package.xml', $content); function replace_parameters($matches) { global $context; return isset($context[$matches[1]]) ? $context[$matches[1]] : null; } 0) { if ($position + $length > $strlen) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } for ($position++; $remaining > 0; $position++) { $value = ord($input[$position]); // If it is invalid, count the sequence as invalid and reprocess the current byte: if (($value & 0xC0) !== 0x80) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $character |= ($value & 0x3F) << (--$remaining * 6); } $position--; } if ( // Non-shortest form sequences are invalid $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of ucschar codepoints // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF || ( // Everything else not in ucschar $character > 0xD7FF && $character < 0xF900 || $character < 0x20 || $character > 0x7E && $character < 0xA0 || $character > 0xEFFFD ) ) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $codepoints[] = $character; } return $codepoints; } /** * RFC3492-compliant encoder * * @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code * @throws Requests_Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`) * * @param string $input UTF-8 encoded string to encode * @return string Punycode-encoded string */ public static function punycode_encode($input) { $output = ''; # let n = initial_n $n = self::BOOTSTRAP_INITIAL_N; # let delta = 0 $delta = 0; # let bias = initial_bias $bias = self::BOOTSTRAP_INITIAL_BIAS; # let h = b = the number of basic code points in the input $h = $b = 0; // see loop # copy them to the output in order $codepoints = self::utf8_to_codepoints($input); $extended = array(); foreach ($codepoints as $char) { if ($char < 128) { // Character is valid ASCII // TODO: this should also check if it's valid for a URL $output .= chr($char); $h++; } // Check if the character is non-ASCII, but below initial n // This never occurs for Punycode, so ignore in coverage // @codeCoverageIgnoreStart elseif ($char < $n) { throw new Requests_Exception('Invalid character', 'idna.character_outside_domain', $char); } // @codeCoverageIgnoreEnd else { $extended[$char] = true; } } $extended = array_keys($extended); sort($extended); $b = $h; # [copy them] followed by a delimiter if b > 0 if (strlen($output) > 0) { $output .= '-'; } # {if the input contains a non-basic code point < n then fail} # while h < length(input) do begin while ($h < count($codepoints)) { # let m = the minimum code point >= n in the input $m = array_shift($extended); //printf('next code point to insert is %s' . PHP_EOL, dechex($m)); # let delta = delta + (m - n) * (h + 1), fail on overflow $delta += ($m - $n) * ($h + 1); # let n = m $n = $m; # for each code point c in the input (in order) do begin for ($num = 0; $num < count($codepoints); $num++) { $c = $codepoints[$num]; # if c < n then increment delta, fail on overflow if ($c < $n) { $delta++; } # if c == n then begin elseif ($c === $n) { # let q = delta $q = $delta; # for k = base to infinity in steps of base do begin for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) { # let t = tmin if k <= bias {+ tmin}, or # tmax if k >= bias + tmax, or k - bias otherwise if ($k <= ($bias + self::BOOTSTRAP_TMIN)) { $t = self::BOOTSTRAP_TMIN; } elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) { $t = self::BOOTSTRAP_TMAX; } else { $t = $k - $bias; } # if q < t then break if ($q < $t) { break; } # output the code point for digit t + ((q - t) mod (base - t)) $digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t)); $output .= self::digit_to_char($digit); # let q = (q - t) div (base - t) $q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t)); # end } # output the code point for digit q $output .= self::digit_to_char($q); # let bias = adapt(delta, h + 1, test h equals b?) $bias = self::adapt($delta, $h + 1, $h === $b); # let delta = 0 $delta = 0; # increment h $h++; # end } # end } # increment delta and n $delta++; $n++; # end } return $output; } /** * Convert a digit to its respective character * * @see https://tools.ietf.org/html/rfc3492#section-5 * @throws Requests_Exception On invalid digit (`idna.invalid_digit`) * * @param int $digit Digit in the range 0-35 * @return string Single character corresponding to digit */ protected static function digit_to_char($digit) { // @codeCoverageIgnoreStart // As far as I know, this never happens, but still good to be sure. if ($digit < 0 || $digit > 35) { throw new Requests_Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit); } // @codeCoverageIgnoreEnd $digits = 'abcdefghijklmnopqrstuvwxyz0123456789'; return substr($digits, $digit, 1); } /** * Adapt the bias * * @see https://tools.ietf.org/html/rfc3492#section-6.1 * @param int $delta * @param int $numpoints * @param bool $firsttime * @return int New bias */ protected static function adapt($delta, $numpoints, $firsttime) { # function adapt(delta,numpoints,firsttime): # if firsttime then let delta = delta div damp if ($firsttime) { $delta = floor($delta / self::BOOTSTRAP_DAMP); } # else let delta = delta div 2 else { $delta = floor($delta / 2); } # let delta = delta + (delta div numpoints) $delta += floor($delta / $numpoints); # let k = 0 $k = 0; # while delta > ((base - tmin) * tmax) div 2 do begin $max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2); while ($delta > $max) { # let delta = delta div (base - tmin) $delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN)); # let k = k + base $k += self::BOOTSTRAP_BASE; # end } # return k + (((base - tmin + 1) * delta) div (delta + skew)) return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW)); } }headers = new Requests_Response_Headers(); $this->cookies = new Requests_Cookie_Jar(); } /** * Response body * * @var string */ public $body = ''; /** * Raw HTTP data from the transport * * @var string */ public $raw = ''; /** * Headers, as an associative array * * @var Requests_Response_Headers Array-like object representing headers */ public $headers = array(); /** * Status code, false if non-blocking * * @var integer|boolean */ public $status_code = false; /** * Protocol version, false if non-blocking * @var float|boolean */ public $protocol_version = false; /** * Whether the request succeeded or not * * @var boolean */ public $success = false; /** * Number of redirects the request used * * @var integer */ public $redirects = 0; /** * URL requested * * @var string */ public $url = ''; /** * Previous requests (from redirects) * * @var array Array of Requests_Response objects */ public $history = array(); /** * Cookies from the request * * @var Requests_Cookie_Jar Array-like object representing a cookie jar */ public $cookies = array(); /** * Is the response a redirect? * * @return boolean True if redirect (3xx status), false if not. */ public function is_redirect() { $code = $this->status_code; return in_array($code, array(300, 301, 302, 303, 307)) || $code > 307 && $code < 400; } /** * Throws an exception if the request was not successful * * @throws Requests_Exception If `$allow_redirects` is false, and code is 3xx (`response.no_redirects`) * @throws Requests_Exception_HTTP On non-successful status code. Exception class corresponds to code (e.g. {@see Requests_Exception_HTTP_404}) * @param boolean $allow_redirects Set to false to throw on a 3xx as well */ public function throw_for_status($allow_redirects = true) { if ($this->is_redirect()) { if (!$allow_redirects) { throw new Requests_Exception('Redirection not allowed', 'response.no_redirects', $this); } } elseif (!$this->success) { $exception = Requests_Exception_HTTP::get_class($this->status_code); throw new $exception(null, $this); } } } FF01:0:0:0:0:0:0:101 * ::1 -> 0:0:0:0:0:0:0:1 * * @author Alexander Merz * @author elfrink at introweb dot nl * @author Josh Peck * @copyright 2003-2005 The PHP Group * @license http://www.opensource.org/licenses/bsd-license.php * @param string $ip An IPv6 address * @return string The uncompressed IPv6 address */ public static function uncompress($ip) { if (substr_count($ip, '::') !== 1) { return $ip; } list($ip1, $ip2) = explode('::', $ip); $c1 = ($ip1 === '') ? -1 : substr_count($ip1, ':'); $c2 = ($ip2 === '') ? -1 : substr_count($ip2, ':'); if (strpos($ip2, '.') !== false) { $c2++; } // :: if ($c1 === -1 && $c2 === -1) { $ip = '0:0:0:0:0:0:0:0'; } // ::xxx else if ($c1 === -1) { $fill = str_repeat('0:', 7 - $c2); $ip = str_replace('::', $fill, $ip); } // xxx:: else if ($c2 === -1) { $fill = str_repeat(':0', 7 - $c1); $ip = str_replace('::', $fill, $ip); } // xxx::xxx else { $fill = ':' . str_repeat('0:', 6 - $c2 - $c1); $ip = str_replace('::', $fill, $ip); } return $ip; } /** * Compresses an IPv6 address * * RFC 4291 allows you to compress consecutive zero pieces in an address to * '::'. This method expects a valid IPv6 address and compresses consecutive * zero pieces to '::'. * * Example: FF01:0:0:0:0:0:0:101 -> FF01::101 * 0:0:0:0:0:0:0:1 -> ::1 * * @see uncompress() * @param string $ip An IPv6 address * @return string The compressed IPv6 address */ public static function compress($ip) { // Prepare the IP to be compressed $ip = self::uncompress($ip); $ip_parts = self::split_v6_v4($ip); // Replace all leading zeros $ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]); // Find bunches of zeros if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) { $max = 0; $pos = null; foreach ($matches[0] as $match) { if (strlen($match[0]) > $max) { $max = strlen($match[0]); $pos = $match[1]; } } $ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max); } if ($ip_parts[1] !== '') { return implode(':', $ip_parts); } else { return $ip_parts[0]; } } /** * Splits an IPv6 address into the IPv6 and IPv4 representation parts * * RFC 4291 allows you to represent the last two parts of an IPv6 address * using the standard IPv4 representation * * Example: 0:0:0:0:0:0:13.1.68.3 * 0:0:0:0:0:FFFF:129.144.52.38 * * @param string $ip An IPv6 address * @return string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part */ protected static function split_v6_v4($ip) { if (strpos($ip, '.') !== false) { $pos = strrpos($ip, ':'); $ipv6_part = substr($ip, 0, $pos); $ipv4_part = substr($ip, $pos + 1); return array($ipv6_part, $ipv4_part); } else { return array($ip, ''); } } /** * Checks an IPv6 address * * Checks if the given IP is a valid IPv6 address * * @param string $ip An IPv6 address * @return bool true if $ip is a valid IPv6 address */ public static function check_ipv6($ip) { $ip = self::uncompress($ip); list($ipv6, $ipv4) = self::split_v6_v4($ip); $ipv6 = explode(':', $ipv6); $ipv4 = explode('.', $ipv4); if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) { foreach ($ipv6 as $ipv6_part) { // The section can't be empty if ($ipv6_part === '') { return false; } // Nor can it be over four characters if (strlen($ipv6_part) > 4) { return false; } // Remove leading zeros (this is safe because of the above) $ipv6_part = ltrim($ipv6_part, '0'); if ($ipv6_part === '') { $ipv6_part = '0'; } // Check the value is valid $value = hexdec($ipv6_part); if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) { return false; } } if (count($ipv4) === 4) { foreach ($ipv4 as $ipv4_part) { $value = (int) $ipv4_part; if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) { return false; } } } return true; } else { return false; } } } user, $this->pass) = $args; } } /** * Register the necessary callbacks * * @see curl_before_send * @see fsockopen_header * @param Requests_Hooks $hooks Hook system */ public function register(Requests_Hooks &$hooks) { $hooks->register('curl.before_send', array(&$this, 'curl_before_send')); $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header')); } /** * Set cURL parameters before the data is sent * * @param resource $handle cURL resource */ public function curl_before_send(&$handle) { curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString()); } /** * Add extra headers to the request before sending * * @param string $out HTTP header string */ public function fsockopen_header(&$out) { $out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString())); } /** * Get the authentication string (user:pass) * * @return string */ public function getAuthString() { return $this->user . ':' . $this->pass; } }cookies = $cookies; } /** * Normalise cookie data into a Requests_Cookie * * @param string|Requests_Cookie $cookie * @return Requests_Cookie */ public function normalize_cookie($cookie, $key = null) { if ($cookie instanceof Requests_Cookie) { return $cookie; } return Requests_Cookie::parse($cookie, $key); } /** * Normalise cookie data into a Requests_Cookie * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie_Jar::normalize_cookie} * @return Requests_Cookie */ public function normalizeCookie($cookie, $key = null) { return $this->normalize_cookie($cookie, $key); } /** * Check if the given item exists * * @param string $key Item key * @return boolean Does the item exist? */ public function offsetExists($key) { return isset($this->cookies[$key]); } /** * Get the value for the item * * @param string $key Item key * @return string Item value */ public function offsetGet($key) { if (!isset($this->cookies[$key])) { return null; } return $this->cookies[$key]; } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ public function offsetSet($key, $value) { if ($key === null) { throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset'); } $this->cookies[$key] = $value; } /** * Unset the given header * * @param string $key */ public function offsetUnset($key) { unset($this->cookies[$key]); } /** * Get an iterator for the data * * @return ArrayIterator */ public function getIterator() { return new ArrayIterator($this->cookies); } /** * Register the cookie handler with the request's hooking system * * @param Requests_Hooker $hooks Hooking system */ public function register(Requests_Hooker $hooks) { $hooks->register('requests.before_request', array($this, 'before_request')); $hooks->register('requests.before_redirect_check', array($this, 'before_redirect_check')); } /** * Add Cookie header to a request if we have any * * As per RFC 6265, cookies are separated by '; ' * * @param string $url * @param array $headers * @param array $data * @param string $type * @param array $options */ public function before_request($url, &$headers, &$data, &$type, &$options) { if (!$url instanceof Requests_IRI) { $url = new Requests_IRI($url); } if (!empty($this->cookies)) { $cookies = array(); foreach ($this->cookies as $key => $cookie) { $cookie = $this->normalize_cookie($cookie, $key); // Skip expired cookies if ($cookie->is_expired()) { continue; } if ($cookie->domain_matches($url->host)) { $cookies[] = $cookie->format_for_header(); } } $headers['Cookie'] = implode('; ', $cookies); } } /** * Parse all cookies from a response and attach them to the response * * @var Requests_Response $response */ public function before_redirect_check(Requests_Response &$return) { $url = $return->url; if (!$url instanceof Requests_IRI) { $url = new Requests_IRI($url); } $cookies = Requests_Cookie::parse_from_headers($return->headers, $url); $this->cookies = array_merge($this->cookies, $cookies); $return->cookies = $this; } }dispatch('fsockopen.before_request'); $url_parts = parse_url($url); if (empty($url_parts)) { throw new Requests_Exception('Invalid URL.', 'invalidurl', $url); } $host = $url_parts['host']; $context = stream_context_create(); $verifyname = false; $case_insensitive_headers = new Requests_Utility_CaseInsensitiveDictionary($headers); // HTTPS support if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') { $remote_socket = 'ssl://' . $host; if (!isset($url_parts['port'])) { $url_parts['port'] = 443; } $context_options = array( 'verify_peer' => true, // 'CN_match' => $host, 'capture_peer_cert' => true ); $verifyname = true; // SNI, if enabled (OpenSSL >=0.9.8j) if (defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME) { $context_options['SNI_enabled'] = true; if (isset($options['verifyname']) && $options['verifyname'] === false) { $context_options['SNI_enabled'] = false; } } if (isset($options['verify'])) { if ($options['verify'] === false) { $context_options['verify_peer'] = false; } elseif (is_string($options['verify'])) { $context_options['cafile'] = $options['verify']; } } if (isset($options['verifyname']) && $options['verifyname'] === false) { $context_options['verify_peer_name'] = false; $verifyname = false; } stream_context_set_option($context, array('ssl' => $context_options)); } else { $remote_socket = 'tcp://' . $host; } $this->max_bytes = $options['max_bytes']; if (!isset($url_parts['port'])) { $url_parts['port'] = 80; } $remote_socket .= ':' . $url_parts['port']; set_error_handler(array($this, 'connect_error_handler'), E_WARNING | E_NOTICE); $options['hooks']->dispatch('fsockopen.remote_socket', array(&$remote_socket)); $socket = stream_socket_client($remote_socket, $errno, $errstr, ceil($options['connect_timeout']), STREAM_CLIENT_CONNECT, $context); restore_error_handler(); if ($verifyname && !$this->verify_certificate_from_context($host, $context)) { throw new Requests_Exception('SSL certificate did not match the requested domain name', 'ssl.no_match'); } if (!$socket) { if ($errno === 0) { // Connection issue throw new Requests_Exception(rtrim($this->connect_error), 'fsockopen.connect_error'); } throw new Requests_Exception($errstr, 'fsockopenerror', null, $errno); } $data_format = $options['data_format']; if ($data_format === 'query') { $path = self::format_get($url_parts, $data); $data = ''; } else { $path = self::format_get($url_parts, array()); } $options['hooks']->dispatch('fsockopen.remote_host_path', array(&$path, $url)); $request_body = ''; $out = sprintf("%s %s HTTP/%.1f\r\n", $options['type'], $path, $options['protocol_version']); if ($options['type'] !== Requests::TRACE) { if (is_array($data)) { $request_body = http_build_query($data, null, '&'); } else { $request_body = $data; } if (!empty($data)) { if (!isset($case_insensitive_headers['Content-Length'])) { $headers['Content-Length'] = strlen($request_body); } if (!isset($case_insensitive_headers['Content-Type'])) { $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; } } } if (!isset($case_insensitive_headers['Host'])) { $out .= sprintf('Host: %s', $url_parts['host']); if (( 'http' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 80 ) || ( 'https' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 443 )) { $out .= ':' . $url_parts['port']; } $out .= "\r\n"; } if (!isset($case_insensitive_headers['User-Agent'])) { $out .= sprintf("User-Agent: %s\r\n", $options['useragent']); } $accept_encoding = $this->accept_encoding(); if (!isset($case_insensitive_headers['Accept-Encoding']) && !empty($accept_encoding)) { $out .= sprintf("Accept-Encoding: %s\r\n", $accept_encoding); } $headers = Requests::flatten($headers); if (!empty($headers)) { $out .= implode($headers, "\r\n") . "\r\n"; } $options['hooks']->dispatch('fsockopen.after_headers', array(&$out)); if (substr($out, -2) !== "\r\n") { $out .= "\r\n"; } if (!isset($case_insensitive_headers['Connection'])) { $out .= "Connection: Close\r\n"; } $out .= "\r\n" . $request_body; $options['hooks']->dispatch('fsockopen.before_send', array(&$out)); fwrite($socket, $out); $options['hooks']->dispatch('fsockopen.after_send', array($out)); if (!$options['blocking']) { fclose($socket); $fake_headers = ''; $options['hooks']->dispatch('fsockopen.after_request', array(&$fake_headers)); return ''; } $timeout_sec = (int) floor($options['timeout']); if ($timeout_sec == $options['timeout']) { $timeout_msec = 0; } else { $timeout_msec = self::SECOND_IN_MICROSECONDS * $options['timeout'] % self::SECOND_IN_MICROSECONDS; } stream_set_timeout($socket, $timeout_sec, $timeout_msec); $response = $body = $headers = ''; $this->info = stream_get_meta_data($socket); $size = 0; $doingbody = false; $download = false; if ($options['filename']) { $download = fopen($options['filename'], 'wb'); } while (!feof($socket)) { $this->info = stream_get_meta_data($socket); if ($this->info['timed_out']) { throw new Requests_Exception('fsocket timed out', 'timeout'); } $block = fread($socket, Requests::BUFFER_SIZE); if (!$doingbody) { $response .= $block; if (strpos($response, "\r\n\r\n")) { list($headers, $block) = explode("\r\n\r\n", $response, 2); $doingbody = true; } } // Are we in body mode now? if ($doingbody) { $options['hooks']->dispatch('request.progress', array($block, $size, $this->max_bytes)); $data_length = strlen($block); if ($this->max_bytes) { // Have we already hit a limit? if ($size === $this->max_bytes) { continue; } if (($size + $data_length) > $this->max_bytes) { // Limit the length $limited_length = ($this->max_bytes - $size); $block = substr($block, 0, $limited_length); } } $size += strlen($block); if ($download) { fwrite($download, $block); } else { $body .= $block; } } } $this->headers = $headers; if ($download) { fclose($download); } else { $this->headers .= "\r\n\r\n" . $body; } fclose($socket); $options['hooks']->dispatch('fsockopen.after_request', array(&$this->headers, &$this->info)); return $this->headers; } /** * Send multiple requests simultaneously * * @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request} * @param array $options Global options, see {@see Requests::response()} for documentation * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well) */ public function request_multiple($requests, $options) { $responses = array(); $class = get_class($this); foreach ($requests as $id => $request) { try { $handler = new $class(); $responses[$id] = $handler->request($request['url'], $request['headers'], $request['data'], $request['options']); $request['options']['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$id], $request)); } catch (Requests_Exception $e) { $responses[$id] = $e; } if (!is_string($responses[$id])) { $request['options']['hooks']->dispatch('multiple.request.complete', array(&$responses[$id], $id)); } } return $responses; } /** * Retrieve the encodings we can accept * * @return string Accept-Encoding header value */ protected static function accept_encoding() { $type = array(); if (function_exists('gzinflate')) { $type[] = 'deflate;q=1.0'; } if (function_exists('gzuncompress')) { $type[] = 'compress;q=0.5'; } $type[] = 'gzip;q=0.5'; return implode(', ', $type); } /** * Format a URL given GET data * * @param array $url_parts * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query} * @return string URL with data */ protected static function format_get($url_parts, $data) { if (!empty($data)) { if (empty($url_parts['query'])) { $url_parts['query'] = ''; } $url_parts['query'] .= '&' . http_build_query($data, null, '&'); $url_parts['query'] = trim($url_parts['query'], '&'); } if (isset($url_parts['path'])) { if (isset($url_parts['query'])) { $get = $url_parts['path'] . '?' . $url_parts['query']; } else { $get = $url_parts['path']; } } else { $get = '/'; } return $get; } /** * Error handler for stream_socket_client() * * @param int $errno Error number (e.g. E_WARNING) * @param string $errstr Error message */ public function connect_error_handler($errno, $errstr) { // Double-check we can handle it if (($errno & E_WARNING) === 0 && ($errno & E_NOTICE) === 0) { // Return false to indicate the default error handler should engage return false; } $this->connect_error .= $errstr . "\n"; return true; } /** * Verify the certificate against common name and subject alternative names * * Unfortunately, PHP doesn't check the certificate against the alternative * names, leading things like 'https://www.github.com/' to be invalid. * Instead * * @see https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1 * * @throws Requests_Exception On failure to connect via TLS (`fsockopen.ssl.connect_error`) * @throws Requests_Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`) * @param string $host Host name to verify against * @param resource $context Stream context * @return bool */ public function verify_certificate_from_context($host, $context) { $meta = stream_context_get_options($context); // If we don't have SSL options, then we couldn't make the connection at // all if (empty($meta) || empty($meta['ssl']) || empty($meta['ssl']['peer_certificate'])) { throw new Requests_Exception(rtrim($this->connect_error), 'ssl.connect_error'); } $cert = openssl_x509_parse($meta['ssl']['peer_certificate']); return Requests_SSL::verify_certificate($host, $cert); } /** * Whether this transport is valid * * @codeCoverageIgnore * @return boolean True if the transport is valid, false otherwise. */ public static function test($capabilities = array()) { if (!function_exists('fsockopen')) { return false; } // If needed, check that streams support SSL if (isset($capabilities['ssl']) && $capabilities['ssl']) { if (!extension_loaded('openssl') || !function_exists('openssl_x509_parse')) { return false; } // Currently broken, thanks to https://github.com/facebook/hhvm/issues/2156 if (defined('HHVM_VERSION')) { return false; } } return true; } } version = $curl['version_number']; $this->handle = curl_init(); curl_setopt($this->handle, CURLOPT_HEADER, false); curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1); if ($this->version >= self::CURL_7_10_5) { curl_setopt($this->handle, CURLOPT_ENCODING, ''); } if (defined('CURLOPT_PROTOCOLS')) { curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); } if (defined('CURLOPT_REDIR_PROTOCOLS')) { curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); } } /** * Destructor */ public function __destruct() { if (is_resource($this->handle)) { curl_close($this->handle); } } /** * Perform a request * * @throws Requests_Exception On a cURL error (`curlerror`) * * @param string $url URL to request * @param array $headers Associative array of request headers * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD * @param array $options Request options, see {@see Requests::response()} for documentation * @return string Raw HTTP result */ public function request($url, $headers = array(), $data = array(), $options = array()) { $this->hooks = $options['hooks']; $this->setup_handle($url, $headers, $data, $options); $options['hooks']->dispatch('curl.before_send', array(&$this->handle)); if ($options['filename'] !== false) { $this->stream_handle = fopen($options['filename'], 'wb'); } $this->response_data = ''; $this->response_bytes = 0; $this->response_byte_limit = false; if ($options['max_bytes'] !== false) { $this->response_byte_limit = $options['max_bytes']; } if (isset($options['verify'])) { if ($options['verify'] === false) { curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0); } elseif (is_string($options['verify'])) { curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']); } } if (isset($options['verifyname']) && $options['verifyname'] === false) { curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0); } curl_exec($this->handle); $response = $this->response_data; $options['hooks']->dispatch('curl.after_send', array()); if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) { // Reset encoding and try again curl_setopt($this->handle, CURLOPT_ENCODING, 'none'); $this->response_data = ''; $this->response_bytes = 0; curl_exec($this->handle); $response = $this->response_data; } $this->process_response($response, $options); // Need to remove the $this reference from the curl handle. // Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called. curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null); curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null); return $this->headers; } /** * Send multiple requests simultaneously * * @param array $requests Request data * @param array $options Global options * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well) */ public function request_multiple($requests, $options) { // If you're not requesting, we can't get any responses ¯\_(ツ)_/¯ if (empty($requests)) { return array(); } $multihandle = curl_multi_init(); $subrequests = array(); $subhandles = array(); $class = get_class($this); foreach ($requests as $id => $request) { $subrequests[$id] = new $class(); $subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']); $request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id])); curl_multi_add_handle($multihandle, $subhandles[$id]); } $completed = 0; $responses = array(); $request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle)); do { $active = false; do { $status = curl_multi_exec($multihandle, $active); } while ($status === CURLM_CALL_MULTI_PERFORM); $to_process = array(); // Read the information as needed while ($done = curl_multi_info_read($multihandle)) { $key = array_search($done['handle'], $subhandles, true); if (!isset($to_process[$key])) { $to_process[$key] = $done; } } // Parse the finished requests before we start getting the new ones foreach ($to_process as $key => $done) { $options = $requests[$key]['options']; if (CURLE_OK !== $done['result']) { //get error string for handle. $reason = curl_error($done['handle']); $exception = new Requests_Exception_Transport_cURL( $reason, Requests_Exception_Transport_cURL::EASY, $done['handle'], $done['result'] ); $responses[$key] = $exception; $options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key])); } else { $responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options); $options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key])); } curl_multi_remove_handle($multihandle, $done['handle']); curl_close($done['handle']); if (!is_string($responses[$key])) { $options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key)); } $completed++; } } while ($active || $completed < count($subrequests)); $request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle)); curl_multi_close($multihandle); return $responses; } /** * Get the cURL handle for use in a multi-request * * @param string $url URL to request * @param array $headers Associative array of request headers * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD * @param array $options Request options, see {@see Requests::response()} for documentation * @return resource Subrequest's cURL handle */ public function &get_subrequest_handle($url, $headers, $data, $options) { $this->setup_handle($url, $headers, $data, $options); if ($options['filename'] !== false) { $this->stream_handle = fopen($options['filename'], 'wb'); } $this->response_data = ''; $this->response_bytes = 0; $this->response_byte_limit = false; if ($options['max_bytes'] !== false) { $this->response_byte_limit = $options['max_bytes']; } $this->hooks = $options['hooks']; return $this->handle; } /** * Setup the cURL handle for the given data * * @param string $url URL to request * @param array $headers Associative array of request headers * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD * @param array $options Request options, see {@see Requests::response()} for documentation */ protected function setup_handle($url, $headers, $data, $options) { $options['hooks']->dispatch('curl.before_request', array(&$this->handle)); // Force closing the connection for old versions of cURL (<7.22). if ( ! isset( $headers['Connection'] ) ) { $headers['Connection'] = 'close'; } $headers = Requests::flatten($headers); if (!empty($data)) { $data_format = $options['data_format']; if ($data_format === 'query') { $url = self::format_get($url, $data); $data = ''; } elseif (!is_string($data)) { $data = http_build_query($data, null, '&'); } } switch ($options['type']) { case Requests::POST: curl_setopt($this->handle, CURLOPT_POST, true); curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data); break; case Requests::HEAD: curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); curl_setopt($this->handle, CURLOPT_NOBODY, true); break; case Requests::TRACE: curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); break; case Requests::PATCH: case Requests::PUT: case Requests::DELETE: case Requests::OPTIONS: default: curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); if (!empty($data)) { curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data); } } // cURL requires a minimum timeout of 1 second when using the system // DNS resolver, as it uses `alarm()`, which is second resolution only. // There's no way to detect which DNS resolver is being used from our // end, so we need to round up regardless of the supplied timeout. // // https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609 $timeout = max($options['timeout'], 1); if (is_int($timeout) || $this->version < self::CURL_7_16_2) { curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout)); } else { curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000)); } if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) { curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout'])); } else { curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000)); } curl_setopt($this->handle, CURLOPT_URL, $url); curl_setopt($this->handle, CURLOPT_REFERER, $url); curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']); if (!empty($headers)) { curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers); } if ($options['protocol_version'] === 1.1) { curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); } else { curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); } if (true === $options['blocking']) { curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array(&$this, 'stream_headers')); curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array(&$this, 'stream_body')); curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE); } } /** * Process a response * * @param string $response Response data from the body * @param array $options Request options * @return string HTTP response data including headers */ public function process_response($response, $options) { if ($options['blocking'] === false) { $fake_headers = ''; $options['hooks']->dispatch('curl.after_request', array(&$fake_headers)); return false; } if ($options['filename'] !== false) { fclose($this->stream_handle); $this->headers = trim($this->headers); } else { $this->headers .= $response; } if (curl_errno($this->handle)) { $error = sprintf( 'cURL error %s: %s', curl_errno($this->handle), curl_error($this->handle) ); throw new Requests_Exception($error, 'curlerror', $this->handle); } $this->info = curl_getinfo($this->handle); $options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info)); return $this->headers; } /** * Collect the headers as they are received * * @param resource $handle cURL resource * @param string $headers Header string * @return integer Length of provided header */ public function stream_headers($handle, $headers) { // Why do we do this? cURL will send both the final response and any // interim responses, such as a 100 Continue. We don't need that. // (We may want to keep this somewhere just in case) if ($this->done_headers) { $this->headers = ''; $this->done_headers = false; } $this->headers .= $headers; if ($headers === "\r\n") { $this->done_headers = true; } return strlen($headers); } /** * Collect data as it's received * * @since 1.6.1 * * @param resource $handle cURL resource * @param string $data Body data * @return integer Length of provided data */ public function stream_body($handle, $data) { $this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit)); $data_length = strlen($data); // Are we limiting the response size? if ($this->response_byte_limit) { if ($this->response_bytes === $this->response_byte_limit) { // Already at maximum, move on return $data_length; } if (($this->response_bytes + $data_length) > $this->response_byte_limit) { // Limit the length $limited_length = ($this->response_byte_limit - $this->response_bytes); $data = substr($data, 0, $limited_length); } } if ($this->stream_handle) { fwrite($this->stream_handle, $data); } else { $this->response_data .= $data; } $this->response_bytes += strlen($data); return $data_length; } /** * Format a URL given GET data * * @param string $url * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query} * @return string URL with data */ protected static function format_get($url, $data) { if (!empty($data)) { $url_parts = parse_url($url); if (empty($url_parts['query'])) { $query = $url_parts['query'] = ''; } else { $query = $url_parts['query']; } $query .= '&' . http_build_query($data, null, '&'); $query = trim($query, '&'); if (empty($url_parts['query'])) { $url .= '?' . $query; } else { $url = str_replace($url_parts['query'], $query, $url); } } return $url; } /** * Whether this transport is valid * * @codeCoverageIgnore * @return boolean True if the transport is valid, false otherwise. */ public static function test($capabilities = array()) { if (!function_exists('curl_init') || !function_exists('curl_exec')) { return false; } // If needed, check that our installed curl version supports SSL if (isset($capabilities['ssl']) && $capabilities['ssl']) { $curl_version = curl_version(); if (!(CURL_VERSION_SSL & $curl_version['features'])) { return false; } } return true; } } 0 is executed later */ public function register($hook, $callback, $priority = 0) { if (!isset($this->hooks[$hook])) { $this->hooks[$hook] = array(); } if (!isset($this->hooks[$hook][$priority])) { $this->hooks[$hook][$priority] = array(); } $this->hooks[$hook][$priority][] = $callback; } /** * Dispatch a message * * @param string $hook Hook name * @param array $parameters Parameters to pass to callbacks * @return boolean Successfulness */ public function dispatch($hook, $parameters = array()) { if (empty($this->hooks[$hook])) { return false; } foreach ($this->hooks[$hook] as $priority => $hooked) { foreach ($hooked as $callback) { call_user_func_array($callback, $parameters); } } return true; } } array( 'port' => 674 ), 'dict' => array( 'port' => 2628 ), 'file' => array( 'ihost' => 'localhost' ), 'http' => array( 'port' => 80, ), 'https' => array( 'port' => 443, ), ); /** * Return the entire IRI when you try and read the object as a string * * @return string */ public function __toString() { return $this->get_iri(); } /** * Overload __set() to provide access via properties * * @param string $name Property name * @param mixed $value Property value */ public function __set($name, $value) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), $value); } elseif ( $name === 'iauthority' || $name === 'iuserinfo' || $name === 'ihost' || $name === 'ipath' || $name === 'iquery' || $name === 'ifragment' ) { call_user_func(array($this, 'set_' . substr($name, 1)), $value); } } /** * Overload __get() to provide access via properties * * @param string $name Property name * @return mixed */ public function __get($name) { // isset() returns false for null, we don't want to do that // Also why we use array_key_exists below instead of isset() $props = get_object_vars($this); if ( $name === 'iri' || $name === 'uri' || $name === 'iauthority' || $name === 'authority' ) { $method = 'get_' . $name; $return = $this->$method(); } elseif (array_key_exists($name, $props)) { $return = $this->$name; } // host -> ihost elseif (($prop = 'i' . $name) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } // ischeme -> scheme elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } else { trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE); $return = null; } if ($return === null && isset($this->normalization[$this->scheme][$name])) { return $this->normalization[$this->scheme][$name]; } else { return $return; } } /** * Overload __isset() to provide access via properties * * @param string $name Property name * @return bool */ public function __isset($name) { return (method_exists($this, 'get_' . $name) || isset($this->$name)); } /** * Overload __unset() to provide access via properties * * @param string $name Property name */ public function __unset($name) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), ''); } } /** * Create a new IRI object, from a specified string * * @param string|null $iri */ public function __construct($iri = null) { $this->set_iri($iri); } /** * Create a new IRI object by resolving a relative IRI * * Returns false if $base is not absolute, otherwise an IRI. * * @param IRI|string $base (Absolute) Base IRI * @param IRI|string $relative Relative IRI * @return IRI|false */ public static function absolutize($base, $relative) { if (!($relative instanceof Requests_IRI)) { $relative = new Requests_IRI($relative); } if (!$relative->is_valid()) { return false; } elseif ($relative->scheme !== null) { return clone $relative; } if (!($base instanceof Requests_IRI)) { $base = new Requests_IRI($base); } if ($base->scheme === null || !$base->is_valid()) { return false; } if ($relative->get_iri() !== '') { if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null) { $target = clone $relative; $target->scheme = $base->scheme; } else { $target = new Requests_IRI; $target->scheme = $base->scheme; $target->iuserinfo = $base->iuserinfo; $target->ihost = $base->ihost; $target->port = $base->port; if ($relative->ipath !== '') { if ($relative->ipath[0] === '/') { $target->ipath = $relative->ipath; } elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '') { $target->ipath = '/' . $relative->ipath; } elseif (($last_segment = strrpos($base->ipath, '/')) !== false) { $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath; } else { $target->ipath = $relative->ipath; } $target->ipath = $target->remove_dot_segments($target->ipath); $target->iquery = $relative->iquery; } else { $target->ipath = $base->ipath; if ($relative->iquery !== null) { $target->iquery = $relative->iquery; } elseif ($base->iquery !== null) { $target->iquery = $base->iquery; } } $target->ifragment = $relative->ifragment; } } else { $target = clone $base; $target->ifragment = null; } $target->scheme_normalization(); return $target; } /** * Parse an IRI into scheme/authority/path/query/fragment segments * * @param string $iri * @return array */ protected function parse_iri($iri) { $iri = trim($iri, "\x20\x09\x0A\x0C\x0D"); $has_match = preg_match('/^((?P[^:\/?#]+):)?(\/\/(?P[^\/?#]*))?(?P[^?#]*)(\?(?P[^#]*))?(#(?P.*))?$/', $iri, $match); if (!$has_match) { throw new Requests_Exception('Cannot parse supplied IRI', 'iri.cannot_parse', $iri); } if ($match[1] === '') { $match['scheme'] = null; } if (!isset($match[3]) || $match[3] === '') { $match['authority'] = null; } if (!isset($match[5])) { $match['path'] = ''; } if (!isset($match[6]) || $match[6] === '') { $match['query'] = null; } if (!isset($match[8]) || $match[8] === '') { $match['fragment'] = null; } return $match; } /** * Remove dot segments from a path * * @param string $input * @return string */ protected function remove_dot_segments($input) { $output = ''; while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') { // A: If the input buffer begins with a prefix of "../" or "./", // then remove that prefix from the input buffer; otherwise, if (strpos($input, '../') === 0) { $input = substr($input, 3); } elseif (strpos($input, './') === 0) { $input = substr($input, 2); } // B: if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that prefix // with "/" in the input buffer; otherwise, elseif (strpos($input, '/./') === 0) { $input = substr($input, 2); } elseif ($input === '/.') { $input = '/'; } // C: if the input buffer begins with a prefix of "/../" or "/..", // where ".." is a complete path segment, then replace that prefix // with "/" in the input buffer and remove the last segment and its // preceding "/" (if any) from the output buffer; otherwise, elseif (strpos($input, '/../') === 0) { $input = substr($input, 3); $output = substr_replace($output, '', strrpos($output, '/')); } elseif ($input === '/..') { $input = '/'; $output = substr_replace($output, '', strrpos($output, '/')); } // D: if the input buffer consists only of "." or "..", then remove // that from the input buffer; otherwise, elseif ($input === '.' || $input === '..') { $input = ''; } // E: move the first path segment in the input buffer to the end of // the output buffer, including the initial "/" character (if any) // and any subsequent characters up to, but not including, the next // "/" character or the end of the input buffer elseif (($pos = strpos($input, '/', 1)) !== false) { $output .= substr($input, 0, $pos); $input = substr_replace($input, '', 0, $pos); } else { $output .= $input; $input = ''; } } return $output . $input; } /** * Replace invalid character with percent encoding * * @param string $string Input string * @param string $extra_chars Valid characters not in iunreserved or * iprivate (this is ASCII-only) * @param bool $iprivate Allow iprivate * @return string */ protected function replace_invalid_with_pct_encoding($string, $extra_chars, $iprivate = false) { // Normalize as many pct-encoded sections as possible $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array(&$this, 'remove_iunreserved_percent_encoded'), $string); // Replace invalid percent characters $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string); // Add unreserved and % to $extra_chars (the latter is safe because all // pct-encoded sections are now valid). $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%'; // Now replace any bytes that aren't allowed with their pct-encoded versions $position = 0; $strlen = strlen($string); while (($position += strspn($string, $extra_chars, $position)) < $strlen) { $value = ord($string[$position]); // Start position $start = $position; // By default we are valid $valid = true; // No one byte sequences are valid due to the while. // Two byte sequence: if (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { $valid = false; $length = 1; $remaining = 0; } if ($remaining) { if ($position + $length <= $strlen) { for ($position++; $remaining; $position++) { $value = ord($string[$position]); // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $character |= ($value & 0x3F) << (--$remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte: else { $valid = false; $position--; break; } } } else { $position = $strlen - 1; $valid = false; } } // Percent encode anything invalid or not in ucschar if ( // Invalid sequences !$valid // Non-shortest form sequences are invalid || $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of ucschar codepoints // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF || ( // Everything else not in ucschar $character > 0xD7FF && $character < 0xF900 || $character < 0xA0 || $character > 0xEFFFD ) && ( // Everything not in iprivate, if it applies !$iprivate || $character < 0xE000 || $character > 0x10FFFD ) ) { // If we were a character, pretend we weren't, but rather an error. if ($valid) { $position--; } for ($j = $start; $j <= $position; $j++) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1); $j += 2; $position += 2; $strlen += 2; } } } return $string; } /** * Callback function for preg_replace_callback. * * Removes sequences of percent encoded bytes that represent UTF-8 * encoded characters in iunreserved * * @param array $match PCRE match * @return string Replacement */ protected function remove_iunreserved_percent_encoded($match) { // As we just have valid percent encoded sequences we can just explode // and ignore the first member of the returned array (an empty string). $bytes = explode('%', $match[0]); // Initialize the new string (this is what will be returned) and that // there are no bytes remaining in the current sequence (unsurprising // at the first byte!). $string = ''; $remaining = 0; // Loop over each and every byte, and set $value to its value for ($i = 1, $len = count($bytes); $i < $len; $i++) { $value = hexdec($bytes[$i]); // If we're the first byte of sequence: if (!$remaining) { // Start position $start = $i; // By default we are valid $valid = true; // One byte sequence: if ($value <= 0x7F) { $character = $value; $length = 1; } // Two byte sequence: elseif (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { $valid = false; $remaining = 0; } } // Continuation byte: else { // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $remaining--; $character |= ($value & 0x3F) << ($remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence: else { $valid = false; $remaining = 0; $i--; } } // If we've reached the end of the current byte sequence, append it to Unicode::$data if (!$remaining) { // Percent encode anything invalid or not in iunreserved if ( // Invalid sequences !$valid // Non-shortest form sequences are invalid || $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of iunreserved codepoints || $character < 0x2D || $character > 0xEFFFD // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF // Everything else not in iunreserved (this is all BMP) || $character === 0x2F || $character > 0x39 && $character < 0x41 || $character > 0x5A && $character < 0x61 || $character > 0x7A && $character < 0x7E || $character > 0x7E && $character < 0xA0 || $character > 0xD7FF && $character < 0xF900 ) { for ($j = $start; $j <= $i; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } else { for ($j = $start; $j <= $i; $j++) { $string .= chr(hexdec($bytes[$j])); } } } } // If we have any bytes left over they are invalid (i.e., we are // mid-way through a multi-byte sequence) if ($remaining) { for ($j = $start; $j < $len; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } return $string; } protected function scheme_normalization() { if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo']) { $this->iuserinfo = null; } if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost']) { $this->ihost = null; } if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port']) { $this->port = null; } if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath']) { $this->ipath = ''; } if (isset($this->ihost) && empty($this->ipath)) { $this->ipath = '/'; } if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery']) { $this->iquery = null; } if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment']) { $this->ifragment = null; } } /** * Check if the object represents a valid IRI. This needs to be done on each * call as some things change depending on another part of the IRI. * * @return bool */ public function is_valid() { $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null; if ($this->ipath !== '' && ( $isauthority && $this->ipath[0] !== '/' || ( $this->scheme === null && !$isauthority && strpos($this->ipath, ':') !== false && (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/')) ) ) ) { return false; } return true; } /** * Set the entire IRI. Returns true on success, false on failure (if there * are any invalid characters). * * @param string $iri * @return bool */ protected function set_iri($iri) { static $cache; if (!$cache) { $cache = array(); } if ($iri === null) { return true; } if (isset($cache[$iri])) { list($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return) = $cache[$iri]; return $return; } $parsed = $this->parse_iri((string) $iri); $return = $this->set_scheme($parsed['scheme']) && $this->set_authority($parsed['authority']) && $this->set_path($parsed['path']) && $this->set_query($parsed['query']) && $this->set_fragment($parsed['fragment']); $cache[$iri] = array($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return); return $return; } /** * Set the scheme. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $scheme * @return bool */ protected function set_scheme($scheme) { if ($scheme === null) { $this->scheme = null; } elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme)) { $this->scheme = null; return false; } else { $this->scheme = strtolower($scheme); } return true; } /** * Set the authority. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $authority * @return bool */ protected function set_authority($authority) { static $cache; if (!$cache) { $cache = array(); } if ($authority === null) { $this->iuserinfo = null; $this->ihost = null; $this->port = null; return true; } if (isset($cache[$authority])) { list($this->iuserinfo, $this->ihost, $this->port, $return) = $cache[$authority]; return $return; } $remaining = $authority; if (($iuserinfo_end = strrpos($remaining, '@')) !== false) { $iuserinfo = substr($remaining, 0, $iuserinfo_end); $remaining = substr($remaining, $iuserinfo_end + 1); } else { $iuserinfo = null; } if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false) { $port = substr($remaining, $port_start + 1); if ($port === false || $port === '') { $port = null; } $remaining = substr($remaining, 0, $port_start); } else { $port = null; } $return = $this->set_userinfo($iuserinfo) && $this->set_host($remaining) && $this->set_port($port); $cache[$authority] = array($this->iuserinfo, $this->ihost, $this->port, $return); return $return; } /** * Set the iuserinfo. * * @param string $iuserinfo * @return bool */ protected function set_userinfo($iuserinfo) { if ($iuserinfo === null) { $this->iuserinfo = null; } else { $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:'); $this->scheme_normalization(); } return true; } /** * Set the ihost. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $ihost * @return bool */ protected function set_host($ihost) { if ($ihost === null) { $this->ihost = null; return true; } if (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']') { if (Requests_IPv6::check_ipv6(substr($ihost, 1, -1))) { $this->ihost = '[' . Requests_IPv6::compress(substr($ihost, 1, -1)) . ']'; } else { $this->ihost = null; return false; } } else { $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;='); // Lowercase, but ignore pct-encoded sections (as they should // remain uppercase). This must be done after the previous step // as that can add unescaped characters. $position = 0; $strlen = strlen($ihost); while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen) { if ($ihost[$position] === '%') { $position += 3; } else { $ihost[$position] = strtolower($ihost[$position]); $position++; } } $this->ihost = $ihost; } $this->scheme_normalization(); return true; } /** * Set the port. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $port * @return bool */ protected function set_port($port) { if ($port === null) { $this->port = null; return true; } if (strspn($port, '0123456789') === strlen($port)) { $this->port = (int) $port; $this->scheme_normalization(); return true; } $this->port = null; return false; } /** * Set the ipath. * * @param string $ipath * @return bool */ protected function set_path($ipath) { static $cache; if (!$cache) { $cache = array(); } $ipath = (string) $ipath; if (isset($cache[$ipath])) { $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)]; } else { $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/'); $removed = $this->remove_dot_segments($valid); $cache[$ipath] = array($valid, $removed); $this->ipath = ($this->scheme !== null) ? $removed : $valid; } $this->scheme_normalization(); return true; } /** * Set the iquery. * * @param string $iquery * @return bool */ protected function set_query($iquery) { if ($iquery === null) { $this->iquery = null; } else { $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true); $this->scheme_normalization(); } return true; } /** * Set the ifragment. * * @param string $ifragment * @return bool */ protected function set_fragment($ifragment) { if ($ifragment === null) { $this->ifragment = null; } else { $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?'); $this->scheme_normalization(); } return true; } /** * Convert an IRI to a URI (or parts thereof) * * @param string|bool IRI to convert (or false from {@see get_iri}) * @return string|false URI if IRI is valid, false otherwise. */ protected function to_uri($string) { if (!is_string($string)) { return false; } static $non_ascii; if (!$non_ascii) { $non_ascii = implode('', range("\x80", "\xFF")); } $position = 0; $strlen = strlen($string); while (($position += strcspn($string, $non_ascii, $position)) < $strlen) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1); $position += 3; $strlen += 2; } return $string; } /** * Get the complete IRI * * @return string */ protected function get_iri() { if (!$this->is_valid()) { return false; } $iri = ''; if ($this->scheme !== null) { $iri .= $this->scheme . ':'; } if (($iauthority = $this->get_iauthority()) !== null) { $iri .= '//' . $iauthority; } $iri .= $this->ipath; if ($this->iquery !== null) { $iri .= '?' . $this->iquery; } if ($this->ifragment !== null) { $iri .= '#' . $this->ifragment; } return $iri; } /** * Get the complete URI * * @return string */ protected function get_uri() { return $this->to_uri($this->get_iri()); } /** * Get the complete iauthority * * @return string */ protected function get_iauthority() { if ($this->iuserinfo === null && $this->ihost === null && $this->port === null) { return null; } $iauthority = ''; if ($this->iuserinfo !== null) { $iauthority .= $this->iuserinfo . '@'; } if ($this->ihost !== null) { $iauthority .= $this->ihost; } if ($this->port !== null) { $iauthority .= ':' . $this->port; } return $iauthority; } /** * Get the complete authority * * @return string */ protected function get_authority() { $iauthority = $this->get_iauthority(); if (is_string($iauthority)) { return $this->to_uri($iauthority); } else { return $iauthority; } } } data[$key])) { return null; } return $this->flatten($this->data[$key]); } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ public function offsetSet($key, $value) { if ($key === null) { throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset'); } $key = strtolower($key); if (!isset($this->data[$key])) { $this->data[$key] = array(); } $this->data[$key][] = $value; } /** * Get all values for a given header * * @param string $key * @return array Header values */ public function getValues($key) { $key = strtolower($key); if (!isset($this->data[$key])) { return null; } return $this->data[$key]; } /** * Flattens a value into a string * * Converts an array into a string by imploding values with a comma, as per * RFC2616's rules for folding headers. * * @param string|array $value Value to flatten * @return string Flattened value */ public function flatten($value) { if (is_array($value)) { $value = implode(',', $value); } return $value; } /** * Get an iterator for the data * * Converts the internal * @return ArrayIterator */ public function getIterator() { return new Requests_Utility_FilteredIterator($this->data, array($this, 'flatten')); } } proxy = $args; } elseif (is_array($args)) { if (count($args) == 1) { list($this->proxy) = $args; } elseif (count($args) == 3) { list($this->proxy, $this->user, $this->pass) = $args; $this->use_authentication = true; } else { throw new Requests_Exception('Invalid number of arguments', 'proxyhttpbadargs'); } } } /** * Register the necessary callbacks * * @since 1.6 * @see curl_before_send * @see fsockopen_remote_socket * @see fsockopen_remote_host_path * @see fsockopen_header * @param Requests_Hooks $hooks Hook system */ public function register(Requests_Hooks &$hooks) { $hooks->register('curl.before_send', array(&$this, 'curl_before_send')); $hooks->register('fsockopen.remote_socket', array(&$this, 'fsockopen_remote_socket')); $hooks->register('fsockopen.remote_host_path', array(&$this, 'fsockopen_remote_host_path')); if ($this->use_authentication) { $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header')); } } /** * Set cURL parameters before the data is sent * * @since 1.6 * @param resource $handle cURL resource */ public function curl_before_send(&$handle) { curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($handle, CURLOPT_PROXY, $this->proxy); if ($this->use_authentication) { curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string()); } } /** * Alter remote socket information before opening socket connection * * @since 1.6 * @param string $remote_socket Socket connection string */ public function fsockopen_remote_socket(&$remote_socket) { $remote_socket = $this->proxy; } /** * Alter remote path before getting stream data * * @since 1.6 * @param string $path Path to send in HTTP request string ("GET ...") * @param string $url Full URL we're requesting */ public function fsockopen_remote_host_path(&$path, $url) { $path = $url; } /** * Add extra headers to the request before sending * * @since 1.6 * @param string $out HTTP header string */ public function fsockopen_header(&$out) { $out .= sprintf("Proxy-Authorization: Basic %s\r\n", base64_encode($this->get_auth_string())); } /** * Get the authentication string (user:pass) * * @since 1.6 * @return string */ public function get_auth_string() { return $this->user . ':' . $this->pass; } }useragent = 'X';` * * @var array */ public $options = array(); /** * Create a new session * * @param string|null $url Base URL for requests * @param array $headers Default headers for requests * @param array $data Default data for requests * @param array $options Default options for requests */ public function __construct($url = null, $headers = array(), $data = array(), $options = array()) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->options = $options; if (empty($this->options['cookies'])) { $this->options['cookies'] = new Requests_Cookie_Jar(); } } /** * Get a property's value * * @param string $key Property key * @return mixed|null Property value, null if none found */ public function __get($key) { if (isset($this->options[$key])) { return $this->options[$key]; } return null; } /** * Set a property's value * * @param string $key Property key * @param mixed $value Property value */ public function __set($key, $value) { $this->options[$key] = $value; } /** * Remove a property's value * * @param string $key Property key */ public function __isset($key) { return isset($this->options[$key]); } /** * Remove a property's value * * @param string $key Property key */ public function __unset($key) { if (isset($this->options[$key])) { unset($this->options[$key]); } } /**#@+ * @see request() * @param string $url * @param array $headers * @param array $options * @return Requests_Response */ /** * Send a GET request */ public function get($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::GET, $options); } /** * Send a HEAD request */ public function head($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::HEAD, $options); } /** * Send a DELETE request */ public function delete($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::DELETE, $options); } /**#@-*/ /**#@+ * @see request() * @param string $url * @param array $headers * @param array $data * @param array $options * @return Requests_Response */ /** * Send a POST request */ public function post($url, $headers = array(), $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::POST, $options); } /** * Send a PUT request */ public function put($url, $headers = array(), $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::PUT, $options); } /** * Send a PATCH request * * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the * specification recommends that should send an ETag * * @link https://tools.ietf.org/html/rfc5789 */ public function patch($url, $headers, $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::PATCH, $options); } /**#@-*/ /** * Main interface for HTTP requests * * This method initiates a request and sends it via a transport before * parsing. * * @see Requests::request() * * @throws Requests_Exception On invalid URLs (`nonhttp`) * * @param string $url URL to request * @param array $headers Extra headers to send with the request * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests * @param string $type HTTP request type (use Requests constants) * @param array $options Options for the request (see {@see Requests::request}) * @return Requests_Response */ public function request($url, $headers = array(), $data = array(), $type = Requests::GET, $options = array()) { $request = $this->merge_request(compact('url', 'headers', 'data', 'options')); return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']); } /** * Send multiple HTTP requests simultaneously * * @see Requests::request_multiple() * * @param array $requests Requests data (see {@see Requests::request_multiple}) * @param array $options Global and default options (see {@see Requests::request}) * @return array Responses (either Requests_Response or a Requests_Exception object) */ public function request_multiple($requests, $options = array()) { foreach ($requests as $key => $request) { $requests[$key] = $this->merge_request($request, false); } $options = array_merge($this->options, $options); // Disallow forcing the type, as that's a per request setting unset($options['type']); return Requests::request_multiple($requests, $options); } /** * Merge a request's data with the default data * * @param array $request Request data (same form as {@see request_multiple}) * @param boolean $merge_options Should we merge options as well? * @return array Request data */ protected function merge_request($request, $merge_options = true) { if ($this->url !== null) { $request['url'] = Requests_IRI::absolutize($this->url, $request['url']); $request['url'] = $request['url']->uri; } if (empty($request['headers'])) { $request['headers'] = array(); } $request['headers'] = array_merge($this->headers, $request['headers']); if (empty($request['data'])) { if (is_array($this->data)) { $request['data'] = $this->data; } } elseif (is_array($request['data']) && is_array($this->data)) { $request['data'] = array_merge($this->data, $request['data']); } if ($merge_options !== false) { $request['options'] = array_merge($this->options, $request['options']); // Disallow forcing the type, as that's a per request setting unset($request['options']['type']); } return $request; } } 0 is executed later */ public function register($hook, $callback, $priority = 0); /** * Dispatch a message * * @param string $hook Hook name * @param array $parameters Parameters to pass to callbacks * @return boolean Successfulness */ public function dispatch($hook, $parameters = array()); }type = $type; $this->data = $data; } /** * Like {@see getCode()}, but a string code. * * @codeCoverageIgnore * @return string */ public function getType() { return $this->type; } /** * Gives any relevant data * * @codeCoverageIgnore * @return mixed */ public function getData() { return $this->data; } }name = $name; $this->value = $value; $this->attributes = $attributes; $default_flags = array( 'creation' => time(), 'last-access' => time(), 'persistent' => false, 'host-only' => true, ); $this->flags = array_merge($default_flags, $flags); $this->reference_time = time(); if ($reference_time !== null) { $this->reference_time = $reference_time; } $this->normalize(); } /** * Check if a cookie is expired. * * Checks the age against $this->reference_time to determine if the cookie * is expired. * * @return boolean True if expired, false if time is valid. */ public function is_expired() { // RFC6265, s. 4.1.2.2: // If a cookie has both the Max-Age and the Expires attribute, the Max- // Age attribute has precedence and controls the expiration date of the // cookie. if (isset($this->attributes['max-age'])) { $max_age = $this->attributes['max-age']; return $max_age < $this->reference_time; } if (isset($this->attributes['expires'])) { $expires = $this->attributes['expires']; return $expires < $this->reference_time; } return false; } /** * Check if a cookie is valid for a given URI * * @param Requests_IRI $uri URI to check * @return boolean Whether the cookie is valid for the given URI */ public function uri_matches(Requests_IRI $uri) { if (!$this->domain_matches($uri->host)) { return false; } if (!$this->path_matches($uri->path)) { return false; } return empty($this->attributes['secure']) || $uri->scheme === 'https'; } /** * Check if a cookie is valid for a given domain * * @param string $string Domain to check * @return boolean Whether the cookie is valid for the given domain */ public function domain_matches($string) { if (!isset($this->attributes['domain'])) { // Cookies created manually; cookies created by Requests will set // the domain to the requested domain return true; } $domain_string = $this->attributes['domain']; if ($domain_string === $string) { // The domain string and the string are identical. return true; } // If the cookie is marked as host-only and we don't have an exact // match, reject the cookie if ($this->flags['host-only'] === true) { return false; } if (strlen($string) <= strlen($domain_string)) { // For obvious reasons, the string cannot be a suffix if the domain // is shorter than the domain string return false; } if (substr($string, -1 * strlen($domain_string)) !== $domain_string) { // The domain string should be a suffix of the string. return false; } $prefix = substr($string, 0, strlen($string) - strlen($domain_string)); if (substr($prefix, -1) !== '.') { // The last character of the string that is not included in the // domain string should be a %x2E (".") character. return false; } // The string should be a host name (i.e., not an IP address). return !preg_match('#^(.+\.)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $string); } /** * Check if a cookie is valid for a given path * * From the path-match check in RFC 6265 section 5.1.4 * * @param string $request_path Path to check * @return boolean Whether the cookie is valid for the given path */ public function path_matches($request_path) { if (empty($request_path)) { // Normalize empty path to root $request_path = '/'; } if (!isset($this->attributes['path'])) { // Cookies created manually; cookies created by Requests will set // the path to the requested path return true; } $cookie_path = $this->attributes['path']; if ($cookie_path === $request_path) { // The cookie-path and the request-path are identical. return true; } if (strlen($request_path) > strlen($cookie_path) && substr($request_path, 0, strlen($cookie_path)) === $cookie_path) { if (substr($cookie_path, -1) === '/') { // The cookie-path is a prefix of the request-path, and the last // character of the cookie-path is %x2F ("/"). return true; } if (substr($request_path, strlen($cookie_path), 1) === '/') { // The cookie-path is a prefix of the request-path, and the // first character of the request-path that is not included in // the cookie-path is a %x2F ("/") character. return true; } } return false; } /** * Normalize cookie and attributes * * @return boolean Whether the cookie was successfully normalized */ public function normalize() { foreach ($this->attributes as $key => $value) { $orig_value = $value; $value = $this->normalize_attribute($key, $value); if ($value === null) { unset($this->attributes[$key]); continue; } if ($value !== $orig_value) { $this->attributes[$key] = $value; } } return true; } /** * Parse an individual cookie attribute * * Handles parsing individual attributes from the cookie values. * * @param string $name Attribute name * @param string|boolean $value Attribute value (string value, or true if empty/flag) * @return mixed Value if available, or null if the attribute value is invalid (and should be skipped) */ protected function normalize_attribute($name, $value) { switch (strtolower($name)) { case 'expires': // Expiration parsing, as per RFC 6265 section 5.2.1 if (is_int($value)) { return $value; } $expiry_time = strtotime($value); if ($expiry_time === false) { return null; } return $expiry_time; case 'max-age': // Expiration parsing, as per RFC 6265 section 5.2.2 if (is_int($value)) { return $value; } // Check that we have a valid age if (!preg_match('/^-?\d+$/', $value)) { return null; } $delta_seconds = (int) $value; if ($delta_seconds <= 0) { $expiry_time = 0; } else { $expiry_time = $this->reference_time + $delta_seconds; } return $expiry_time; case 'domain': // Domain normalization, as per RFC 6265 section 5.2.3 if ($value[0] === '.') { $value = substr($value, 1); } return $value; default: return $value; } } /** * Format a cookie for a Cookie header * * This is used when sending cookies to a server. * * @return string Cookie formatted for Cookie header */ public function format_for_header() { return sprintf('%s=%s', $this->name, $this->value); } /** * Format a cookie for a Cookie header * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::format_for_header} * @return string */ public function formatForHeader() { return $this->format_for_header(); } /** * Format a cookie for a Set-Cookie header * * This is used when sending cookies to clients. This isn't really * applicable to client-side usage, but might be handy for debugging. * * @return string Cookie formatted for Set-Cookie header */ public function format_for_set_cookie() { $header_value = $this->format_for_header(); if (!empty($this->attributes)) { $parts = array(); foreach ($this->attributes as $key => $value) { // Ignore non-associative attributes if (is_numeric($key)) { $parts[] = $value; } else { $parts[] = sprintf('%s=%s', $key, $value); } } $header_value .= '; ' . implode('; ', $parts); } return $header_value; } /** * Format a cookie for a Set-Cookie header * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::format_for_set_cookie} * @return string */ public function formatForSetCookie() { return $this->format_for_set_cookie(); } /** * Get the cookie value * * Attributes and other data can be accessed via methods. */ public function __toString() { return $this->value; } /** * Parse a cookie string into a cookie object * * Based on Mozilla's parsing code in Firefox and related projects, which * is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265 * specifies some of this handling, but not in a thorough manner. * * @param string Cookie header value (from a Set-Cookie header) * @return Requests_Cookie Parsed cookie object */ public static function parse($string, $name = '', $reference_time = null) { $parts = explode(';', $string); $kvparts = array_shift($parts); if (!empty($name)) { $value = $string; } elseif (strpos($kvparts, '=') === false) { // Some sites might only have a value without the equals separator. // Deviate from RFC 6265 and pretend it was actually a blank name // (`=foo`) // // https://bugzilla.mozilla.org/show_bug.cgi?id=169091 $name = ''; $value = $kvparts; } else { list($name, $value) = explode('=', $kvparts, 2); } $name = trim($name); $value = trim($value); // Attribute key are handled case-insensitively $attributes = new Requests_Utility_CaseInsensitiveDictionary(); if (!empty($parts)) { foreach ($parts as $part) { if (strpos($part, '=') === false) { $part_key = $part; $part_value = true; } else { list($part_key, $part_value) = explode('=', $part, 2); $part_value = trim($part_value); } $part_key = trim($part_key); $attributes[$part_key] = $part_value; } } return new Requests_Cookie($name, $value, $attributes, array(), $reference_time); } /** * Parse all Set-Cookie headers from request headers * * @param Requests_Response_Headers $headers Headers to parse from * @param Requests_IRI|null $origin URI for comparing cookie origins * @param int|null $time Reference time for expiration calculation * @return array */ public static function parse_from_headers(Requests_Response_Headers $headers, Requests_IRI $origin = null, $time = null) { $cookie_headers = $headers->getValues('Set-Cookie'); if (empty($cookie_headers)) { return array(); } $cookies = array(); foreach ($cookie_headers as $header) { $parsed = self::parse($header, '', $time); // Default domain/path attributes if (empty($parsed->attributes['domain']) && !empty($origin)) { $parsed->attributes['domain'] = $origin->host; $parsed->flags['host-only'] = true; } else { $parsed->flags['host-only'] = false; } $path_is_valid = (!empty($parsed->attributes['path']) && $parsed->attributes['path'][0] === '/'); if (!$path_is_valid && !empty($origin)) { $path = $origin->path; // Default path normalization as per RFC 6265 section 5.1.4 if (substr($path, 0, 1) !== '/') { // If the uri-path is empty or if the first character of // the uri-path is not a %x2F ("/") character, output // %x2F ("/") and skip the remaining steps. $path = '/'; } elseif (substr_count($path, '/') === 1) { // If the uri-path contains no more than one %x2F ("/") // character, output %x2F ("/") and skip the remaining // step. $path = '/'; } else { // Output the characters of the uri-path from the first // character up to, but not including, the right-most // %x2F ("/"). $path = substr($path, 0, strrpos($path, '/')); } $parsed->attributes['path'] = $path; } // Reject invalid cookie domains if (!empty($origin) && !$parsed->domain_matches($origin->host)) { continue; } $cookies[$parsed->name] = $parsed; } return $cookies; } /** * Parse all Set-Cookie headers from request headers * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::parse_from_headers} * @return string */ public static function parseFromHeaders(Requests_Response_Headers $headers) { return self::parse_from_headers($headers); } } $value) { $this->offsetSet($key, $value); } } /** * Check if the given item exists * * @param string $key Item key * @return boolean Does the item exist? */ public function offsetExists($key) { $key = strtolower($key); return isset($this->data[$key]); } /** * Get the value for the item * * @param string $key Item key * @return string Item value */ public function offsetGet($key) { $key = strtolower($key); if (!isset($this->data[$key])) { return null; } return $this->data[$key]; } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ public function offsetSet($key, $value) { if ($key === null) { throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset'); } $key = strtolower($key); $this->data[$key] = $value; } /** * Unset the given header * * @param string $key */ public function offsetUnset($key) { unset($this->data[strtolower($key)]); } /** * Get an iterator for the data * * @return ArrayIterator */ public function getIterator() { return new ArrayIterator($this->data); } /** * Get the headers as an array * * @return array Header data */ public function getAll() { return $this->data; } } callback = $callback; } /** * Get the current item's value after filtering * * @return string */ public function current() { $value = parent::current(); $value = call_user_func($this->callback, $value); return $value; } } code = $data->status_code; } parent::__construct($reason, $data); } }type = $type; } if ($code !== null) { $this->code = $code; } if ($message !== null) { $this->reason = $message; } $message = sprintf('%d %s', $this->code, $this->reason); parent::__construct($message, $this->type, $data, $this->code); } /** * Get the error message */ public function getReason() { return $this->reason; } } reason = $reason; } $message = sprintf('%d %s', $this->code, $this->reason); parent::__construct($message, 'httpresponse', $data, $this->code); } /** * Get the status message */ public function getReason() { return $this->reason; } /** * Get the correct exception class for a given error code * * @param int|bool $code HTTP status code, or false if unavailable * @return string Exception class name to use */ public static function get_class($code) { if (!$code) { return 'Requests_Exception_HTTP_Unknown'; } $class = sprintf('Requests_Exception_HTTP_%d', $code); if (class_exists($class)) { return $class; } return 'Requests_Exception_HTTP_Unknown'; } }dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options)); if (!empty($options['transport'])) { $transport = $options['transport']; if (is_string($options['transport'])) { $transport = new $transport(); } } else { $need_ssl = (0 === stripos($url, 'https://')); $capabilities = array('ssl' => $need_ssl); $transport = self::get_transport($capabilities); } $response = $transport->request($url, $headers, $data, $options); $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options)); return self::parse_response($response, $url, $headers, $data, $options); } /** * Send multiple HTTP requests simultaneously * * The `$requests` parameter takes an associative or indexed array of * request fields. The key of each request can be used to match up the * request with the returned data, or with the request passed into your * `multiple.request.complete` callback. * * The request fields value is an associative array with the following keys: * * - `url`: Request URL Same as the `$url` parameter to * {@see Requests::request} * (string, required) * - `headers`: Associative array of header fields. Same as the `$headers` * parameter to {@see Requests::request} * (array, default: `array()`) * - `data`: Associative array of data fields or a string. Same as the * `$data` parameter to {@see Requests::request} * (array|string, default: `array()`) * - `type`: HTTP request type (use Requests constants). Same as the `$type` * parameter to {@see Requests::request} * (string, default: `Requests::GET`) * - `cookies`: Associative array of cookie name to value, or cookie jar. * (array|Requests_Cookie_Jar) * * If the `$options` parameter is specified, individual requests will * inherit options from it. This can be used to use a single hooking system, * or set all the types to `Requests::POST`, for example. * * In addition, the `$options` parameter takes the following global options: * * - `complete`: A callback for when a request is complete. Takes two * parameters, a Requests_Response/Requests_Exception reference, and the * ID from the request array (Note: this can also be overridden on a * per-request basis, although that's a little silly) * (callback) * * @param array $requests Requests data (see description for more information) * @param array $options Global and default options (see {@see Requests::request}) * @return array Responses (either Requests_Response or a Requests_Exception object) */ public static function request_multiple($requests, $options = array()) { $options = array_merge(self::get_default_options(true), $options); if (!empty($options['hooks'])) { $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple')); if (!empty($options['complete'])) { $options['hooks']->register('multiple.request.complete', $options['complete']); } } foreach ($requests as $id => &$request) { if (!isset($request['headers'])) { $request['headers'] = array(); } if (!isset($request['data'])) { $request['data'] = array(); } if (!isset($request['type'])) { $request['type'] = self::GET; } if (!isset($request['options'])) { $request['options'] = $options; $request['options']['type'] = $request['type']; } else { if (empty($request['options']['type'])) { $request['options']['type'] = $request['type']; } $request['options'] = array_merge($options, $request['options']); } self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']); // Ensure we only hook in once if ($request['options']['hooks'] !== $options['hooks']) { $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple')); if (!empty($request['options']['complete'])) { $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']); } } } unset($request); if (!empty($options['transport'])) { $transport = $options['transport']; if (is_string($options['transport'])) { $transport = new $transport(); } } else { $transport = self::get_transport(); } $responses = $transport->request_multiple($requests, $options); foreach ($responses as $id => &$response) { // If our hook got messed with somehow, ensure we end up with the // correct response if (is_string($response)) { $request = $requests[$id]; self::parse_multiple($response, $request); $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id)); } } return $responses; } /** * Get the default options * * @see Requests::request() for values returned by this method * @param boolean $multirequest Is this a multirequest? * @return array Default option values */ protected static function get_default_options($multirequest = false) { $defaults = array( 'timeout' => 10, 'connect_timeout' => 10, 'useragent' => 'php-requests/' . self::VERSION, 'protocol_version' => 1.1, 'redirected' => 0, 'redirects' => 10, 'follow_redirects' => true, 'blocking' => true, 'type' => self::GET, 'filename' => false, 'auth' => false, 'proxy' => false, 'cookies' => false, 'max_bytes' => false, 'idn' => true, 'hooks' => null, 'transport' => null, 'verify' => Requests::get_certificate_path(), 'verifyname' => true, ); if ($multirequest !== false) { $defaults['complete'] = null; } return $defaults; } /** * Get default certificate path. * * @return string Default certificate path. */ public static function get_certificate_path() { if ( ! empty( Requests::$certificate_path ) ) { return Requests::$certificate_path; } return dirname(__FILE__) . '/Requests/Transport/cacert.pem'; } /** * Set default certificate path. * * @param string $path Certificate path, pointing to a PEM file. */ public static function set_certificate_path( $path ) { Requests::$certificate_path = $path; } /** * Set the default values * * @param string $url URL to request * @param array $headers Extra headers to send with the request * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests * @param string $type HTTP request type * @param array $options Options for the request * @return array $options */ protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) { if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) { throw new Requests_Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url); } if (empty($options['hooks'])) { $options['hooks'] = new Requests_Hooks(); } if (is_array($options['auth'])) { $options['auth'] = new Requests_Auth_Basic($options['auth']); } if ($options['auth'] !== false) { $options['auth']->register($options['hooks']); } if (is_string($options['proxy']) || is_array($options['proxy'])) { $options['proxy'] = new Requests_Proxy_HTTP($options['proxy']); } if ($options['proxy'] !== false) { $options['proxy']->register($options['hooks']); } if (is_array($options['cookies'])) { $options['cookies'] = new Requests_Cookie_Jar($options['cookies']); } elseif (empty($options['cookies'])) { $options['cookies'] = new Requests_Cookie_Jar(); } if ($options['cookies'] !== false) { $options['cookies']->register($options['hooks']); } if ($options['idn'] !== false) { $iri = new Requests_IRI($url); $iri->host = Requests_IDNAEncoder::encode($iri->ihost); $url = $iri->uri; } // Massage the type to ensure we support it. $type = strtoupper($type); if (!isset($options['data_format'])) { if (in_array($type, array(self::HEAD, self::GET, self::DELETE))) { $options['data_format'] = 'query'; } else { $options['data_format'] = 'body'; } } } /** * HTTP response parser * * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`) * @throws Requests_Exception On missing head/body separator (`noversion`) * @throws Requests_Exception On missing head/body separator (`toomanyredirects`) * * @param string $headers Full response text including headers and body * @param string $url Original request URL * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects * @return Requests_Response */ protected static function parse_response($headers, $url, $req_headers, $req_data, $options) { $return = new Requests_Response(); if (!$options['blocking']) { return $return; } $return->raw = $headers; $return->url = $url; if (!$options['filename']) { if (($pos = strpos($headers, "\r\n\r\n")) === false) { // Crap! throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator'); } $headers = substr($return->raw, 0, $pos); $return->body = substr($return->raw, $pos + strlen("\n\r\n\r")); } else { $return->body = ''; } // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3) $headers = str_replace("\r\n", "\n", $headers); // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2) $headers = preg_replace('/\n[ \t]/', ' ', $headers); $headers = explode("\n", $headers); preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches); if (empty($matches)) { throw new Requests_Exception('Response could not be parsed', 'noversion', $headers); } $return->protocol_version = (float) $matches[1]; $return->status_code = (int) $matches[2]; if ($return->status_code >= 200 && $return->status_code < 300) { $return->success = true; } foreach ($headers as $header) { list($key, $value) = explode(':', $header, 2); $value = trim($value); preg_replace('#(\s+)#i', ' ', $value); $return->headers[$key] = $value; } if (isset($return->headers['transfer-encoding'])) { $return->body = self::decode_chunked($return->body); unset($return->headers['transfer-encoding']); } if (isset($return->headers['content-encoding'])) { $return->body = self::decompress($return->body); } //fsockopen and cURL compatibility if (isset($return->headers['connection'])) { unset($return->headers['connection']); } $options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options)); if ($return->is_redirect() && $options['follow_redirects'] === true) { if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) { if ($return->status_code === 303) { $options['type'] = self::GET; } $options['redirected']++; $location = $return->headers['location']; if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) { // relative redirect, for compatibility make it absolute $location = Requests_IRI::absolutize($url, $location); $location = $location->uri; } $hook_args = array( &$location, &$req_headers, &$req_data, &$options, $return ); $options['hooks']->dispatch('requests.before_redirect', $hook_args); $redirected = self::request($location, $req_headers, $req_data, $options['type'], $options); $redirected->history[] = $return; return $redirected; } elseif ($options['redirected'] >= $options['redirects']) { throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return); } } $return->redirects = $options['redirected']; $options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options)); return $return; } /** * Callback for `transport.internal.parse_response` * * Internal use only. Converts a raw HTTP response to a Requests_Response * while still executing a multiple request. * * @param string $response Full response text including headers and body (will be overwritten with Response instance) * @param array $request Request data as passed into {@see Requests::request_multiple()} * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object */ public static function parse_multiple(&$response, $request) { try { $url = $request['url']; $headers = $request['headers']; $data = $request['data']; $options = $request['options']; $response = self::parse_response($response, $url, $headers, $data, $options); } catch (Requests_Exception $e) { $response = $e; } } /** * Decoded a chunked body as per RFC 2616 * * @see https://tools.ietf.org/html/rfc2616#section-3.6.1 * @param string $data Chunked body * @return string Decoded body */ protected static function decode_chunked($data) { if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) { return $data; } $decoded = ''; $encoded = $data; while (true) { $is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches); if (!$is_chunked) { // Looks like it's not chunked after all return $data; } $length = hexdec(trim($matches[1])); if ($length === 0) { // Ignore trailer headers return $decoded; } $chunk_length = strlen($matches[0]); $decoded .= substr($encoded, $chunk_length, $length); $encoded = substr($encoded, $chunk_length + $length + 2); if (trim($encoded) === '0' || empty($encoded)) { return $decoded; } } // We'll never actually get down here // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd /** * Convert a key => value array to a 'key: value' array for headers * * @param array $array Dictionary of header values * @return array List of headers */ public static function flatten($array) { $return = array(); foreach ($array as $key => $value) { $return[] = sprintf('%s: %s', $key, $value); } return $return; } /** * Convert a key => value array to a 'key: value' array for headers * * @codeCoverageIgnore * @deprecated Misspelling of {@see Requests::flatten} * @param array $array Dictionary of header values * @return array List of headers */ public static function flattern($array) { return self::flatten($array); } /** * Decompress an encoded body * * Implements gzip, compress and deflate. Guesses which it is by attempting * to decode. * * @param string $data Compressed data in one of the above formats * @return string Decompressed string */ public static function decompress($data) { if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") { // Not actually compressed. Probably cURL ruining this for us. return $data; } if (function_exists('gzdecode') && ($decoded = @gzdecode($data)) !== false) { return $decoded; } elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) { return $decoded; } elseif (($decoded = self::compatible_gzinflate($data)) !== false) { return $decoded; } elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) { return $decoded; } return $data; } /** * Decompression of deflated string while staying compatible with the majority of servers. * * Certain Servers will return deflated data with headers which PHP's gzinflate() * function cannot handle out of the box. The following function has been created from * various snippets on the gzinflate() PHP documentation. * * Warning: Magic numbers within. Due to the potential different formats that the compressed * data may be returned in, some "magic offsets" are needed to ensure proper decompression * takes place. For a simple progmatic way to determine the magic offset in use, see: * https://core.trac.wordpress.org/ticket/18273 * * @since 2.8.1 * @link https://core.trac.wordpress.org/ticket/18273 * @link https://secure.php.net/manual/en/function.gzinflate.php#70875 * @link https://secure.php.net/manual/en/function.gzinflate.php#77336 * * @param string $gzData String to decompress. * @return string|bool False on failure. */ public static function compatible_gzinflate($gzData) { // Compressed data might contain a full zlib header, if so strip it for // gzinflate() if (substr($gzData, 0, 3) == "\x1f\x8b\x08") { $i = 10; $flg = ord(substr($gzData, 3, 1)); if ($flg > 0) { if ($flg & 4) { list($xlen) = unpack('v', substr($gzData, $i, 2)); $i = $i + 2 + $xlen; } if ($flg & 8) { $i = strpos($gzData, "\0", $i) + 1; } if ($flg & 16) { $i = strpos($gzData, "\0", $i) + 1; } if ($flg & 2) { $i = $i + 2; } } $decompressed = self::compatible_gzinflate(substr($gzData, $i)); if (false !== $decompressed) { return $decompressed; } } // If the data is Huffman Encoded, we must first strip the leading 2 // byte Huffman marker for gzinflate() // The response is Huffman coded by many compressors such as // java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's // System.IO.Compression.DeflateStream. // // See https://decompres.blogspot.com/ for a quick explanation of this // data type $huffman_encoded = false; // low nibble of first byte should be 0x08 list(, $first_nibble) = unpack('h', $gzData); // First 2 bytes should be divisible by 0x1F list(, $first_two_bytes) = unpack('n', $gzData); if (0x08 == $first_nibble && 0 == ($first_two_bytes % 0x1F)) { $huffman_encoded = true; } if ($huffman_encoded) { if (false !== ($decompressed = @gzinflate(substr($gzData, 2)))) { return $decompressed; } } if ("\x50\x4b\x03\x04" == substr($gzData, 0, 4)) { // ZIP file format header // Offset 6: 2 bytes, General-purpose field // Offset 26: 2 bytes, filename length // Offset 28: 2 bytes, optional field length // Offset 30: Filename field, followed by optional field, followed // immediately by data list(, $general_purpose_flag) = unpack('v', substr($gzData, 6, 2)); // If the file has been compressed on the fly, 0x08 bit is set of // the general purpose field. We can use this to differentiate // between a compressed document, and a ZIP file $zip_compressed_on_the_fly = (0x08 == (0x08 & $general_purpose_flag)); if (!$zip_compressed_on_the_fly) { // Don't attempt to decode a compressed zip file return $gzData; } // Determine the first byte of data, based on the above ZIP header // offsets: $first_file_start = array_sum(unpack('v2', substr($gzData, 26, 4))); if (false !== ($decompressed = @gzinflate(substr($gzData, 30 + $first_file_start)))) { return $decompressed; } return false; } // Finally fall back to straight gzinflate if (false !== ($decompressed = @gzinflate($gzData))) { return $decompressed; } // Fallback for all above failing, not expected, but included for // debugging and preventing regressions and to track stats if (false !== ($decompressed = @gzinflate(substr($gzData, 2)))) { return $decompressed; } return false; } public static function match_domain($host, $reference) { // Check for a direct match if ($host === $reference) { return true; } // Calculate the valid wildcard match if the host is not an IP address // Also validates that the host has 3 parts or more, as per Firefox's // ruleset. $parts = explode('.', $host); if (ip2long($host) === false && count($parts) >= 3) { $parts[0] = '*'; $wildcard = implode('.', $parts); if ($wildcard === $reference) { return true; } } return false; } } $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', '8a0ad02df6a5087f2c380f8fd52db273' => $vendorDir . '/wp-cli/cache-command/cache-command.php', 'f3f0199a3ecd9f501d0a3b361bd2f61c' => $vendorDir . '/wp-cli/entity-command/entity-command.php', 'c65f753375faee349b7adc48c2ee7cc2' => $vendorDir . '/wp-cli/db-command/db-command.php', '3937806105cc8e221b8fa8db5b70d2f2' => $vendorDir . '/wp-cli/mustangostang-spyc/includes/functions.php', 'be01b9b16925dcb22165c40b46681ac6' => $vendorDir . '/wp-cli/php-cli-tools/lib/cli/cli.php', '3f201033d5aceb2293314273be88f7c6' => $vendorDir . '/wp-cli/extension-command/extension-command.php', 'd979c11fe80ba96ae3037b43429fe546' => $vendorDir . '/wp-cli/scaffold-command/scaffold-command.php', 'b66d29757fcb2fb7a9608d068e3716b0' => $vendorDir . '/wp-cli/checksum-command/checksum-command.php', '5c6ec5cff8f9d625772c8ed147f6b894' => $vendorDir . '/wp-cli/export-command/export-command.php', 'ac949ce40a981819ba132473518a9a31' => $vendorDir . '/wp-cli/wp-config-transformer/src/WPConfigTransformer.php', '5deaf6ce9c8bbdfb65104c7e938d5875' => $vendorDir . '/wp-cli/config-command/config-command.php', '68c39b88215b6cf7a0da164166670ef9' => $vendorDir . '/wp-cli/core-command/core-command.php', 'f958dca3f412fd7975da1700912a9321' => $vendorDir . '/wp-cli/eval-command/eval-command.php', '30cbb6e4122dc988e494c6b9c0438233' => $vendorDir . '/wp-cli/import-command/import-command.php', '5e099d3cac677dd2bec1003ea7707745' => $vendorDir . '/wp-cli/media-command/media-command.php', 'ba366f96f4fddbdef61ad7a862b44f61' => $vendorDir . '/wp-cli/package-command/package-command.php', '7654e00bf0e632580764400bd8293a9c' => $vendorDir . '/wp-cli/cron-command/cron-command.php', '021d3a13471556f0b57038d679f7f8ea' => $vendorDir . '/wp-cli/embed-command/embed-command.php', 'ffb465a494c3101218c4417180c2c9a2' => $vendorDir . '/wp-cli/i18n-command/i18n-command.php', 'ace0d205db7f4135ec32132a0076d555' => $vendorDir . '/wp-cli/language-command/language-command.php', '1c88c1eff05217a8cac80c64c9ac2080' => $vendorDir . '/wp-cli/maintenance-mode-command/maintenance-mode-command.php', 'f399c1c8d0c787d5c94c09884cdd9762' => $vendorDir . '/wp-cli/rewrite-command/rewrite-command.php', '080fadd667195d055c5a23386f270261' => $vendorDir . '/wp-cli/role-command/role-command.php', '8ecb13f8bbc22b1b34d12b14ec01077a' => $vendorDir . '/wp-cli/search-replace-command/search-replace-command.php', '9f04dd0aa5d67ec75a75c88c345a079e' => $vendorDir . '/wp-cli/server-command/server-command.php', '129d58fa8151374aceb8571bcaa97504' => $vendorDir . '/wp-cli/shell-command/shell-command.php', '8519779bbb65eeb842af2f629ce7b6f8' => $vendorDir . '/wp-cli/super-admin-command/super-admin-command.php', '1f05372afcc7d0c51a305cef1d56dd01' => $vendorDir . '/wp-cli/widget-command/widget-command.php', ); __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', '8a0ad02df6a5087f2c380f8fd52db273' => __DIR__ . '/..' . '/wp-cli/cache-command/cache-command.php', 'f3f0199a3ecd9f501d0a3b361bd2f61c' => __DIR__ . '/..' . '/wp-cli/entity-command/entity-command.php', 'c65f753375faee349b7adc48c2ee7cc2' => __DIR__ . '/..' . '/wp-cli/db-command/db-command.php', '3937806105cc8e221b8fa8db5b70d2f2' => __DIR__ . '/..' . '/wp-cli/mustangostang-spyc/includes/functions.php', 'be01b9b16925dcb22165c40b46681ac6' => __DIR__ . '/..' . '/wp-cli/php-cli-tools/lib/cli/cli.php', '3f201033d5aceb2293314273be88f7c6' => __DIR__ . '/..' . '/wp-cli/extension-command/extension-command.php', 'd979c11fe80ba96ae3037b43429fe546' => __DIR__ . '/..' . '/wp-cli/scaffold-command/scaffold-command.php', 'b66d29757fcb2fb7a9608d068e3716b0' => __DIR__ . '/..' . '/wp-cli/checksum-command/checksum-command.php', '5c6ec5cff8f9d625772c8ed147f6b894' => __DIR__ . '/..' . '/wp-cli/export-command/export-command.php', 'ac949ce40a981819ba132473518a9a31' => __DIR__ . '/..' . '/wp-cli/wp-config-transformer/src/WPConfigTransformer.php', '5deaf6ce9c8bbdfb65104c7e938d5875' => __DIR__ . '/..' . '/wp-cli/config-command/config-command.php', '68c39b88215b6cf7a0da164166670ef9' => __DIR__ . '/..' . '/wp-cli/core-command/core-command.php', 'f958dca3f412fd7975da1700912a9321' => __DIR__ . '/..' . '/wp-cli/eval-command/eval-command.php', '30cbb6e4122dc988e494c6b9c0438233' => __DIR__ . '/..' . '/wp-cli/import-command/import-command.php', '5e099d3cac677dd2bec1003ea7707745' => __DIR__ . '/..' . '/wp-cli/media-command/media-command.php', 'ba366f96f4fddbdef61ad7a862b44f61' => __DIR__ . '/..' . '/wp-cli/package-command/package-command.php', '7654e00bf0e632580764400bd8293a9c' => __DIR__ . '/..' . '/wp-cli/cron-command/cron-command.php', '021d3a13471556f0b57038d679f7f8ea' => __DIR__ . '/..' . '/wp-cli/embed-command/embed-command.php', 'ffb465a494c3101218c4417180c2c9a2' => __DIR__ . '/..' . '/wp-cli/i18n-command/i18n-command.php', 'ace0d205db7f4135ec32132a0076d555' => __DIR__ . '/..' . '/wp-cli/language-command/language-command.php', '1c88c1eff05217a8cac80c64c9ac2080' => __DIR__ . '/..' . '/wp-cli/maintenance-mode-command/maintenance-mode-command.php', 'f399c1c8d0c787d5c94c09884cdd9762' => __DIR__ . '/..' . '/wp-cli/rewrite-command/rewrite-command.php', '080fadd667195d055c5a23386f270261' => __DIR__ . '/..' . '/wp-cli/role-command/role-command.php', '8ecb13f8bbc22b1b34d12b14ec01077a' => __DIR__ . '/..' . '/wp-cli/search-replace-command/search-replace-command.php', '9f04dd0aa5d67ec75a75c88c345a079e' => __DIR__ . '/..' . '/wp-cli/server-command/server-command.php', '129d58fa8151374aceb8571bcaa97504' => __DIR__ . '/..' . '/wp-cli/shell-command/shell-command.php', '8519779bbb65eeb842af2f629ce7b6f8' => __DIR__ . '/..' . '/wp-cli/super-admin-command/super-admin-command.php', '1f05372afcc7d0c51a305cef1d56dd01' => __DIR__ . '/..' . '/wp-cli/widget-command/widget-command.php', ); public static $prefixLengthsPsr4 = array ( 'c' => array ( 'cweagans\\Composer\\' => 18, ), 'W' => array ( 'WP_CLI\\Maintenance\\' => 19, 'WP_CLI\\MaintenanceMode\\' => 23, 'WP_CLI\\I18n\\' => 12, 'WP_CLI\\Embeds\\' => 14, 'WP_CLI\\' => 7, ), 'S' => array ( 'Symfony\\Polyfill\\Mbstring\\' => 26, 'Symfony\\Polyfill\\Ctype\\' => 23, 'Symfony\\Component\\Yaml\\' => 23, 'Symfony\\Component\\Translation\\' => 30, 'Symfony\\Component\\Process\\' => 26, 'Symfony\\Component\\Finder\\' => 25, 'Symfony\\Component\\Filesystem\\' => 29, 'Symfony\\Component\\EventDispatcher\\' => 34, 'Symfony\\Component\\DependencyInjection\\' => 38, 'Symfony\\Component\\Debug\\' => 24, 'Symfony\\Component\\Console\\' => 26, 'Symfony\\Component\\Config\\' => 25, 'Seld\\PharUtils\\' => 15, 'Seld\\JsonLint\\' => 14, ), 'P' => array ( 'Psr\\Log\\' => 8, 'Prophecy\\' => 9, 'Peast\\test\\' => 11, 'Peast\\' => 6, ), 'M' => array ( 'Mustangostang\\' => 14, ), 'J' => array ( 'JsonSchema\\' => 11, 'JakubOnderka\\PhpConsoleHighlighter\\' => 35, 'JakubOnderka\\PhpConsoleColor\\' => 29, ), 'G' => array ( 'Gettext\\Languages\\' => 18, 'Gettext\\' => 8, ), 'D' => array ( 'Doctrine\\Instantiator\\' => 22, 'Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\' => 55, ), 'C' => array ( 'Composer\\XdebugHandler\\' => 23, 'Composer\\Spdx\\' => 14, 'Composer\\Semver\\' => 16, 'Composer\\CaBundle\\' => 18, 'Composer\\' => 9, ), ); public static $prefixDirsPsr4 = array ( 'cweagans\\Composer\\' => array ( 0 => __DIR__ . '/..' . '/cweagans/composer-patches/src', ), 'WP_CLI\\Maintenance\\' => array ( 0 => __DIR__ . '/../..' . '/utils/maintenance', ), 'WP_CLI\\MaintenanceMode\\' => array ( 0 => __DIR__ . '/..' . '/wp-cli/maintenance-mode-command/src', ), 'WP_CLI\\I18n\\' => array ( 0 => __DIR__ . '/..' . '/wp-cli/i18n-command/src', ), 'WP_CLI\\Embeds\\' => array ( 0 => __DIR__ . '/..' . '/wp-cli/embed-command/src', ), 'WP_CLI\\' => array ( 0 => __DIR__ . '/..' . '/wp-cli/entity-command/src/WP_CLI', 1 => __DIR__ . '/..' . '/wp-cli/shell-command/src/WP_CLI', ), 'Symfony\\Polyfill\\Mbstring\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', ), 'Symfony\\Polyfill\\Ctype\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', ), 'Symfony\\Component\\Yaml\\' => array ( 0 => __DIR__ . '/..' . '/symfony/yaml', ), 'Symfony\\Component\\Translation\\' => array ( 0 => __DIR__ . '/..' . '/symfony/translation', ), 'Symfony\\Component\\Process\\' => array ( 0 => __DIR__ . '/..' . '/symfony/process', ), 'Symfony\\Component\\Finder\\' => array ( 0 => __DIR__ . '/..' . '/symfony/finder', ), 'Symfony\\Component\\Filesystem\\' => array ( 0 => __DIR__ . '/..' . '/symfony/filesystem', ), 'Symfony\\Component\\EventDispatcher\\' => array ( 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', ), 'Symfony\\Component\\DependencyInjection\\' => array ( 0 => __DIR__ . '/..' . '/symfony/dependency-injection', ), 'Symfony\\Component\\Debug\\' => array ( 0 => __DIR__ . '/..' . '/symfony/debug', ), 'Symfony\\Component\\Console\\' => array ( 0 => __DIR__ . '/..' . '/symfony/console', ), 'Symfony\\Component\\Config\\' => array ( 0 => __DIR__ . '/..' . '/symfony/config', ), 'Seld\\PharUtils\\' => array ( 0 => __DIR__ . '/..' . '/seld/phar-utils/src', ), 'Seld\\JsonLint\\' => array ( 0 => __DIR__ . '/..' . '/seld/jsonlint/src/Seld/JsonLint', ), 'Psr\\Log\\' => array ( 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', ), 'Prophecy\\' => array ( 0 => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy', ), 'Peast\\test\\' => array ( 0 => __DIR__ . '/..' . '/mck89/peast/test/Peast', ), 'Peast\\' => array ( 0 => __DIR__ . '/..' . '/mck89/peast/lib/Peast', ), 'Mustangostang\\' => array ( 0 => __DIR__ . '/..' . '/wp-cli/mustangostang-spyc/src', ), 'JsonSchema\\' => array ( 0 => __DIR__ . '/..' . '/justinrainbow/json-schema/src/JsonSchema', ), 'JakubOnderka\\PhpConsoleHighlighter\\' => array ( 0 => __DIR__ . '/..' . '/jakub-onderka/php-console-highlighter/src', ), 'JakubOnderka\\PhpConsoleColor\\' => array ( 0 => __DIR__ . '/..' . '/jakub-onderka/php-console-color/src', ), 'Gettext\\Languages\\' => array ( 0 => __DIR__ . '/..' . '/gettext/languages/src', ), 'Gettext\\' => array ( 0 => __DIR__ . '/..' . '/gettext/gettext/src', ), 'Doctrine\\Instantiator\\' => array ( 0 => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator', ), 'Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\' => array ( ), 'Composer\\XdebugHandler\\' => array ( 0 => __DIR__ . '/..' . '/composer/xdebug-handler/src', ), 'Composer\\Spdx\\' => array ( ), 'Composer\\Semver\\' => array ( 0 => __DIR__ . '/..' . '/composer/semver/src', ), 'Composer\\CaBundle\\' => array ( 0 => __DIR__ . '/..' . '/composer/ca-bundle/src', ), 'Composer\\' => array ( 0 => __DIR__ . '/..' . '/composer/composer/src/Composer', ), ); public static $fallbackDirsPsr4 = array ( 0 => __DIR__ . '/..' . '/wp-cli/cache-command/src', 1 => __DIR__ . '/..' . '/wp-cli/checksum-command/src', 2 => __DIR__ . '/..' . '/wp-cli/config-command/src', 3 => __DIR__ . '/..' . '/wp-cli/core-command/src', 4 => __DIR__ . '/..' . '/wp-cli/cron-command/src', 5 => __DIR__ . '/..' . '/wp-cli/db-command/src', 6 => __DIR__ . '/..' . '/wp-cli/entity-command/src', 7 => __DIR__ . '/..' . '/wp-cli/eval-command/src', 8 => __DIR__ . '/..' . '/wp-cli/export-command/src', 9 => __DIR__ . '/..' . '/wp-cli/extension-command/src', 10 => __DIR__ . '/..' . '/wp-cli/import-command/src', 11 => __DIR__ . '/..' . '/wp-cli/language-command/src', 12 => __DIR__ . '/..' . '/wp-cli/media-command/src', 13 => __DIR__ . '/..' . '/wp-cli/package-command/src', 14 => __DIR__ . '/..' . '/wp-cli/rewrite-command/src', 15 => __DIR__ . '/..' . '/wp-cli/role-command/src', 16 => __DIR__ . '/..' . '/wp-cli/scaffold-command/src', 17 => __DIR__ . '/..' . '/wp-cli/search-replace-command/src', 18 => __DIR__ . '/..' . '/wp-cli/server-command/src', 19 => __DIR__ . '/..' . '/wp-cli/shell-command/src', 20 => __DIR__ . '/..' . '/wp-cli/super-admin-command/src', 21 => __DIR__ . '/..' . '/wp-cli/widget-command/src', ); public static $prefixesPsr0 = array ( 'p' => array ( 'phpDocumentor' => array ( 0 => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src', ), ), 'c' => array ( 'cli' => array ( 0 => __DIR__ . '/..' . '/wp-cli/php-cli-tools/lib', ), ), 'W' => array ( 'WP_CLI' => array ( 0 => __DIR__ . '/..' . '/wp-cli/wp-cli/php', ), ), 'R' => array ( 'Requests' => array ( 0 => __DIR__ . '/..' . '/rmccue/requests/library', ), ), 'O' => array ( 'Oxymel' => array ( 0 => __DIR__ . '/..' . '/nb/oxymel', ), ), 'M' => array ( 'Mustache' => array ( 0 => __DIR__ . '/..' . '/mustache/mustache/src', ), ), 'B' => array ( 'Behat\\Gherkin' => array ( 0 => __DIR__ . '/..' . '/behat/gherkin/src', ), 'Behat\\Behat' => array ( 0 => __DIR__ . '/..' . '/behat/behat/src', ), ), ); public static $classMap = array ( 'ExampleClass' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/tests/skip-on-5.3/class.php', 'ExampleTrait' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/tests/skip-on-5.3/trait.php', 'JakubOnderka\\PhpParallelLint\\ArrayIterator' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Settings.php', 'JakubOnderka\\PhpParallelLint\\Blame' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\ConsoleWriter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Error' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\ErrorFormatter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/ErrorFormatter.php', 'JakubOnderka\\PhpParallelLint\\Exception' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\FileWriter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\IWriter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\InvalidArgumentException' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\JsonOutput' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Manager' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Manager.php', 'JakubOnderka\\PhpParallelLint\\MultipleWriter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\NotExistsPathException' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\NullWriter' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Output' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\ParallelLint' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/ParallelLint.php', 'JakubOnderka\\PhpParallelLint\\Process\\GitBlameProcess' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/GitBlameProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\LintProcess' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/LintProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\PhpExecutable' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/PhpExecutable.php', 'JakubOnderka\\PhpParallelLint\\Process\\PhpProcess' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/PhpProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\Process' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/Process.php', 'JakubOnderka\\PhpParallelLint\\Process\\SkipLintProcess' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Process/SkipLintProcess.php', 'JakubOnderka\\PhpParallelLint\\RecursiveDirectoryFilterIterator' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Manager.php', 'JakubOnderka\\PhpParallelLint\\Result' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Result.php', 'JakubOnderka\\PhpParallelLint\\RunTimeException' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\Settings' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Settings.php', 'JakubOnderka\\PhpParallelLint\\SyntaxError' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\TextOutput' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\TextOutputColored' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JsonSerializable' => __DIR__ . '/..' . '/jakub-onderka/php-parallel-lint/src/JsonSerializable.php', 'SebastianBergmann\\Comparator\\ArrayComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ArrayComparator.php', 'SebastianBergmann\\Comparator\\Comparator' => __DIR__ . '/..' . '/sebastian/comparator/src/Comparator.php', 'SebastianBergmann\\Comparator\\ComparisonFailure' => __DIR__ . '/..' . '/sebastian/comparator/src/ComparisonFailure.php', 'SebastianBergmann\\Comparator\\DOMNodeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DOMNodeComparator.php', 'SebastianBergmann\\Comparator\\DateTimeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DateTimeComparator.php', 'SebastianBergmann\\Comparator\\DoubleComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DoubleComparator.php', 'SebastianBergmann\\Comparator\\ExceptionComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ExceptionComparator.php', 'SebastianBergmann\\Comparator\\Factory' => __DIR__ . '/..' . '/sebastian/comparator/src/Factory.php', 'SebastianBergmann\\Comparator\\MockObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/MockObjectComparator.php', 'SebastianBergmann\\Comparator\\NumericComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/NumericComparator.php', 'SebastianBergmann\\Comparator\\ObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ObjectComparator.php', 'SebastianBergmann\\Comparator\\ResourceComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ResourceComparator.php', 'SebastianBergmann\\Comparator\\ScalarComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ScalarComparator.php', 'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/SplObjectStorageComparator.php', 'SebastianBergmann\\Comparator\\TypeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/TypeComparator.php', 'SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php', 'SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php', 'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php', 'SebastianBergmann\\Diff\\LCS\\LongestCommonSubsequence' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/LongestCommonSubsequence.php', 'SebastianBergmann\\Diff\\LCS\\MemoryEfficientImplementation' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php', 'SebastianBergmann\\Diff\\LCS\\TimeEfficientImplementation' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php', 'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php', 'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php', 'SebastianBergmann\\Environment\\Console' => __DIR__ . '/..' . '/sebastian/environment/src/Console.php', 'SebastianBergmann\\Environment\\Runtime' => __DIR__ . '/..' . '/sebastian/environment/src/Runtime.php', 'SebastianBergmann\\Exporter\\Exporter' => __DIR__ . '/..' . '/sebastian/exporter/src/Exporter.php', 'SebastianBergmann\\GlobalState\\Blacklist' => __DIR__ . '/..' . '/sebastian/global-state/src/Blacklist.php', 'SebastianBergmann\\GlobalState\\CodeExporter' => __DIR__ . '/..' . '/sebastian/global-state/src/CodeExporter.php', 'SebastianBergmann\\GlobalState\\Exception' => __DIR__ . '/..' . '/sebastian/global-state/src/Exception.php', 'SebastianBergmann\\GlobalState\\Restorer' => __DIR__ . '/..' . '/sebastian/global-state/src/Restorer.php', 'SebastianBergmann\\GlobalState\\RuntimeException' => __DIR__ . '/..' . '/sebastian/global-state/src/RuntimeException.php', 'SebastianBergmann\\GlobalState\\Snapshot' => __DIR__ . '/..' . '/sebastian/global-state/src/Snapshot.php', 'SebastianBergmann\\RecursionContext\\Context' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Context.php', 'SebastianBergmann\\RecursionContext\\Exception' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Exception.php', 'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/recursion-context/src/InvalidArgumentException.php', 'SebastianBergmann\\Version' => __DIR__ . '/..' . '/sebastian/version/src/Version.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$prefixDirsPsr4; $loader->fallbackDirsPsr4 = ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$fallbackDirsPsr4; $loader->prefixesPsr0 = ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$prefixesPsr0; $loader->classMap = ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$classMap; }, null, ClassLoader::class); } } * 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 resetAuthentications() { $this->authentications = array(); } /** * {@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); } } } * 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('[%.1fMiB/%.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) { /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */ $helper = $this->helperSet->get('question'); $question = new Question($question); $question->setHidden(true); return $helper->ask($this->input, $this->getErrorOutput(), $question); } /** * {@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); if (!is_array($result)) { return (string) array_search($result, $choices, true); } $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; } } * 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 $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 $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 $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 $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); } * 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\Helper\QuestionHelper; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Formatter\OutputFormatterInterface; use Symfony\Component\Console\Input\StreamableInputInterface; 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( new QuestionHelper(), ))); } 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; } public function setUserInputs(array $inputs) { if (!$this->input instanceof StreamableInputInterface) { throw new \RuntimeException('Setting the user inputs requires at least the version 3.2 of the symfony/console component.'); } $this->input->setStream($this->createStream($inputs)); $this->input->setInteractive(true); } private function createStream(array $inputs) { $stream = fopen('php://memory', 'r+', false); foreach ($inputs as $input) { fwrite($stream, $input.PHP_EOL); } rewind($stream); return $stream; } } * 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; } } * 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.')'); } } * 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), )); } } * 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].''; } } * 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\IO\NullIO; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\QuestionHelper; 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.'; } }); } $this->io = new NullIO(); parent::__construct('Composer', Composer::getVersion()); } /** * {@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'); if (getenv('COMPOSER_NO_INTERACTION')) { $input->setInteractive(false); } $io = $this->io = new ConsoleIO($input, $output, new HelperSet(array( new QuestionHelper(), ))); ErrorHandler::register($io); if ($input->hasParameterOption('--no-cache')) { $io->writeError('Disabling cache usage', true, IOInterface::DEBUG); putenv('COMPOSER_CACHE_DIR='.(Platform::isWindows() ? 'nul' : '/dev/null')); } // 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 (CommandNotFoundException $e) { // we'll check command validity again later after plugins are loaded $commandName = false; } 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::getVersion(), 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 (!Platform::isWindows() && function_exists('exec') && !getenv('COMPOSER_ALLOW_SUPERUSER') && !file_exists('/.dockerenv')) { 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).'MiB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MiB), 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; if ($this->getIO() && method_exists($this->getIO(), 'resetAuthentications')) { $this->getIO()->resetAuthentications(); } } /** * @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 && Composer::BRANCH_ALIAS_VERSION !== '@package_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.')); $definition->addOption(new InputOption('--no-cache', null, InputOption::VALUE_NONE, 'Prevent use of the cache')); 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; } } * 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 { } * 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(); } * 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)) { if (!is_callable($callable)) { $className = is_object($callable[0]) ? get_class($callable[0]) : $callable[0]; throw new \RuntimeException('Subscriber '.$className.'::'.$callable[1].' for event '.$event->getName().' is not callable, make sure the function is defined and public'); } $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); $script = explode(' ', substr($callable, 1)); $scriptName = $script[0]; unset($script[0]); $args = array_merge($script, $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); } try { $scriptEvent = new Script\Event($scriptName, $event->getComposer(), $event->getIO(), $event->isDevMode(), $args, $flags); $scriptEvent->setOriginatingEvent($event); $return = $this->dispatch($scriptName, $scriptEvent); } catch (ScriptExecutionException $e) { $this->io->writeError(sprintf('Script %s was called via %s', $callable, $event->getName()), true, IOInterface::QUIET); throw $e; } } } 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); } else { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(false); if ($phpPath) { putenv('PHP_BINARY=' . $phpPath); } } 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(false); if (!$phpPath) { throw new \RuntimeException('Failed to locate PHP binary to execute '.$phpPath); } $phpArgs = $finder->findArguments(); $phpArgs = $phpArgs ? ' ' . implode(' ', $phpArgs) : ''; $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) . $phpArgs . $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); } } * 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; } } * 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(); } * 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.' || substr($key, 0, 8) === 'scripts.') { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config[reset($bits)]; 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.' || substr($key, 0, 8) === 'scripts.') { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config[reset($bits)]; 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]); if (0 === count($config[$type])) { unset($config[$type]); } }); } 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; } } * 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; }; } } * 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; use Composer\Util\PackageSorter; /** * @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, $this->devMode === false); // 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, )); } return count($classMap); } 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 * @param bool $filterOutRequireDevPackages whether to filter out require-dev packages * @return array array('psr-0' => array('Ns\\Foo' => array('installDir'))) */ public function parseAutoloads(array $packageMap, PackageInterface $mainPackage, $filterOutRequireDevPackages = false) { $mainPackageMap = array_shift($packageMap); if ($filterOutRequireDevPackages) { $packageMap = $this->filterPackageMap($packageMap, $mainPackage); } $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 (strpos($path, '.phar') !== false) { $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) . " . '/"; $vendorPharPathCode = ' => \'phar://\' . ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/"; $appBaseDirCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/"; $appBaseDirPharCode = ' => \'phar://\' . ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/"; $absoluteVendorPathCode = ' => ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1); $absoluteVendorPharPathCode = ' => ' . substr(var_export(rtrim('phar://' . $vendorDir, '\\/') . '/', true), 0, -1); $absoluteAppBaseDirCode = ' => ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1); $absoluteAppBaseDirPharCode = ' => ' . substr(var_export(rtrim('phar://' . $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 = strtr( var_export($value, true), array( $absoluteVendorPathCode => $vendorPathCode, $absoluteVendorPharPathCode => $vendorPharPathCode, $absoluteAppBaseDirCode => $appBaseDirCode, $absoluteAppBaseDirPharCode => $appBaseDirPharCode, ) ); $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); } /** * Filters out dev-dependencies * * @param array $packageMap * @param PackageInterface $mainPackage * @return array */ protected function filterPackageMap(array $packageMap, PackageInterface $mainPackage) { $packages = array(); $include = array(); foreach ($packageMap as $item) { $package = $item[0]; $name = $package->getName(); $packages[$name] = $package; } $add = function (PackageInterface $package) use (&$add, $packages, &$include) { foreach ($package->getRequires() as $link) { $target = $link->getTarget(); if (!isset($include[$target])) { $include[$target] = true; if (isset($packages[$target])) { $add($packages[$target]); } } } }; $add($mainPackage); return array_filter( $packageMap, function ($item) use ($include) { $package = $item[0]; foreach ($package->getNames() as $name) { if (isset($include[$name])) { return true; } } return false; } ); } /** * 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(); foreach ($packageMap as $item) { list($package, $path) = $item; $name = $package->getName(); $packages[$name] = $package; $paths[$name] = $path; } $sortedPackages = PackageSorter::sortPackages($packages); $sortedPackageMap = array(); foreach ($sortedPackages as $package) { $name = $package->getName(); $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); } } * 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; } // check non-realpath of file for directories symlink in project dir if ($blacklist && preg_match($blacklist, strtr($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('{<<<[ \t]*([\'"]?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)(?:\s*)\\2(?=\s+|[;,.)])}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; } } * 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') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $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; } * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Symfony\Component\Console\Output\OutputInterface; trigger_error('The ' . __NAMESPACE__ . '\XdebugHandler class is deprecated, use Composer\XdebugHandler\XdebugHandler instead,', E_USER_DEPRECATED); /** * @deprecated use Composer\XdebugHandler\XdebugHandler instead */ class XdebugHandler extends XdebugHandler\XdebugHandler { const ENV_ALLOW = 'COMPOSER_ALLOW_XDEBUG'; const ENV_VERSION = 'COMPOSER_XDEBUG_VERSION'; public function __construct(OutputInterface $output) { parent::__construct('composer', '--ansi'); } } * 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\MarkAliasUninstalledOperation; 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\BasePackage; 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); $ruleSetSize = $solver->getRuleSetSize(); $solver = null; } 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 ".$ruleSetSize." 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 $jobType = $operation->getJobType(); if ('install' === $jobType) { $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage()); } // updating, force dev packages' references if they're in root package refs if ($this->update) { $package = null; if ('update' === $jobType) { $package = $operation->getTargetPackage(); } elseif ('install' === $jobType) { $package = $operation->getPackage(); } if ($package && $package->isDev()) { $references = $this->package->getReferences(); if (isset($references[$package->getName()])) { $this->updateInstallReferences($package, $references[$package->getName()]); } } if ('update' === $jobType) { $targetPackage = $operation->getTargetPackage(); if ($targetPackage->isDev()) { $initialPackage = $operation->getInitialPackage(); if ($targetPackage->getVersion() === $initialPackage->getVersion() && (!$targetPackage->getSourceReference() || $targetPackage->getSourceReference() === $initialPackage->getSourceReference()) && (!$targetPackage->getDistReference() || $targetPackage->getDistReference() === $initialPackage->getDistReference()) ) { $this->io->writeError(' - Skipping update of ' . $targetPackage->getPrettyName() . ' to the same reference-locked version', true, IOInterface::DEBUG); $this->io->writeError('', true, IOInterface::DEBUG); continue; } } } } $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($jobType); 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($jobType, 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; } } } if ($this->executeOperations || $this->writeLock) { $localRepo->write(); } $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($jobType); if (defined($event) && $this->runScripts) { $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation); } } 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(), '*')) { if ($installedDevPkg instanceof AliasPackage) { $finalOps[] = new MarkAliasUninstalledOperation($installedDevPkg, 'non-dev install removing it'); $installedDevPkg = $installedDevPkg->getAliasOf(); } $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(), $newPackage->getDistType(), $newPackage->getDistSha1Checksum()); if ($package instanceof CompletePackage && $newPackage instanceof CompletePackage) { $package->setAbandoned($newPackage->getReplacementPackage() ?: $newPackage->isAbandoned()); } $package->setDistMirrors($newPackage->getDistMirrors()); $package->setSourceMirrors($newPackage->getSourceMirrors()); $package->setTransportOptions($newPackage->getTransportOptions()); } } } private function updatePackageUrl(PackageInterface $package, $sourceUrl, $sourceType, $sourceReference, $distUrl, $distType, $distShaSum) { $oldSourceRef = $package->getSourceReference(); if ($package->getSourceUrl() !== $sourceUrl) { $package->setSourceType($sourceType); $package->setSourceUrl($sourceUrl); $package->setSourceReference($sourceReference); } // only update dist url for github/bitbucket/gitlab 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|(?:www\.)?gitlab\.com)/}i', $distUrl)) { $package->setDistUrl($distUrl); $package->setDistType($distType); $package->setDistSha1Checksum($distShaSum); $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|(?:www\.)?gitlab\.com)/}i', $package->getDistUrl())) { $package->setDistReference($reference); $package->setDistUrl(preg_replace('{(?<=/|sha=)[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 = BasePackage::packageNameToRegexp($whiteListedPattern); if (preg_match($patternRegexp, $package->getName())) { return true; } } return false; } /** * @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); $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; $nameMatchesRequiredPackage = false; $depPackages = $pool->whatProvides($packageName); $matchesByPattern = array(); // check if the name is a glob pattern that did not match directly if (empty($depPackages)) { // add any installed package matching the whitelisted name/pattern $whitelistPatternSearchRegexp = BasePackage::packageNameToRegexp($packageName, '^%s$'); foreach ($localOrLockRepo->search($whitelistPatternSearchRegexp) as $installedPackage) { $matchesByPattern[] = $pool->whatProvides($installedPackage['name']); } // add root requirements which match the whitelisted name/pattern $whitelistPatternRegexp = BasePackage::packageNameToRegexp($packageName); foreach ($rootRequiredPackageNames as $rootRequiredPackageName) { if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) { $nameMatchesRequiredPackage = true; break; } } } if (!empty($matchesByPattern)) { $depPackages = array_merge($depPackages, call_user_func_array('array_merge', $matchesByPattern)); } 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()]) && !preg_match(BasePackage::packageNameToRegexp($packageName), $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 (package 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; } } * 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 { } * 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; /** * @var BaseEvent */ private $originatingEvent; /** * 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; $this->originatingEvent = null; } /** * 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; } /** * Set the originating event. * * @return \Composer\EventDispatcher\Event|null */ public function getOriginatingEvent() { return $this->originatingEvent; } /** * Set the originating event. * * @param \Composer\EventDispatcher\Event $event * @return $this */ public function setOriginatingEvent(BaseEvent $event) { $this->originatingEvent = $this->calculateOriginatingEvent($event); return $this; } /** * Returns the upper-most event in chain. * * @param \Composer\EventDispatcher\Event $event * @return \Composer\EventDispatcher\Event */ private function calculateOriginatingEvent(BaseEvent $event) { if ($event instanceof Event && $event->getOriginatingEvent()) { return $this->calculateOriginatingEvent($event->getOriginatingEvent()); } return $event; } } * 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 { } * 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'; } * 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; } } * 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-Fa-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); } if (substr($name, 0, 8) === 'scripts.') { return $this->addSubNode('scripts', substr($name, 8), $value); } return $this->addMainKey($name, $value); } public function removeProperty($name) { if (substr($name, 0, 6) === 'extra.') { return $this->removeSubNode('extra', substr($name, 6)); } if (substr($name, 0, 8) === 'scripts.') { return $this->removeSubNode('scripts', substr($name, 8)); } return $this->removeMainKey($name); } public function addSubNode($mainNode, $name, $value) { $decoded = JsonFile::parseJson($this->contents); $subName = null; if (in_array($mainNode, array('config', 'extra', 'scripts')) && 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 ($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', 'scripts')) && 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 $keyRegex = str_replace('/', '\\\\?/', preg_quote($name)); if ($this->pregMatch('{"'.$keyRegex.'"\s*:}i', $children)) { // find best match for the value of "name" if (preg_match_all('{'.self::$DEFINES.'"'.$keyRegex.'"\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); } // no break default: throw new \RuntimeException('Failed to execute regex: Unknown error'); } } return $count; } } * 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; const COMPOSER_SCHEMA_PATH = '/../../../res/composer-schema.json'; 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 * @param string|null $schemaFile a path to the schema file * @throws JsonValidationException * @return bool true on success */ public function validateSchema($schema = self::STRICT_SCHEMA, $schemaFile = null) { $content = file_get_contents($this->path); $data = json_decode($content); if (null === $data && 'null' !== $content) { self::validateSyntax($content, $this->path); } if (null === $schemaFile) { $schemaFile = __DIR__ . self::COMPOSER_SCHEMA_PATH; } // 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 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()); } } * 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) { $code = hexdec($match[2]); // 0xD800..0xDFFF denotes UTF-16 surrogate pair which won't be unescaped // see https://github.com/composer/composer/issues/7510 if (0xD800 <= $code && 0xDFFF >= $code) { return $match[0]; } 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; } } * 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 { } getRequires(), $package->getDevRequires()) as $link) { /** @var Link $link */ $target = $link->getTarget(); $usageList[$target][] = $package->getName(); } } $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) { $v = $v[3]; }; } array_walk($array, $transform); asort($array); array_walk($array, $restore); }; $stable_sort($weightList); $sortedPackages = array(); foreach (array_keys($weightList) as $name) { $sortedPackages[] = $packages[$name]; } return $sortedPackages; } } * 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($io); $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) { // before composer 1.9, origin URLs had no port number in them $bcOriginUrl = preg_replace('{:\d+}', '', $originUrl); if (!in_array($originUrl, $this->config->get('gitlab-domains'), true) && !in_array($bcOriginUrl, $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; } if (isset($authTokens[$bcOriginUrl])) { $this->io->setAuthentication($originUrl, $authTokens[$bcOriginUrl], '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); } } * 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 (is_link($directory)) { return unlink($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) { $unlinked = @$this->unlinkImplementation($path); if (!$unlinked) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $unlinked = @$this->unlinkImplementation($path); } if (!$unlinked) { $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) { $deleted = @rmdir($path); if (!$deleted) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $deleted = @rmdir($path); } if (!$deleted) { $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 string $source * @param string $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) === ':' || substr($path, 0, 2) === '\\\\'; } /** * 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 $this->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 $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. * * We test if the path is a directory and not an ordinary link, then check * that the mode value returned from lstat (which gives the status of the * link itself) is not a directory, by replicating the POSIX S_ISDIR test. * * This logic works because PHP does not set the mode value for a junction, * since there is no universal file type flag for it. Unfortunately an * uninitialized variable in PHP prior to 7.2.16 and 7.3.3 may cause a * random value to be returned. See https://bugs.php.net/bug.php?id=77552 * * If this random value passes the S_ISDIR test, then a junction will not be * detected and a recursive delete operation could lead to loss of data in * the target directory. Note that Windows rmdir can handle this situation * and will only delete the junction (from Windows 7 onwards). * * @param string $junction Path to check. * @return bool */ public function isJunction($junction) { if (!Platform::isWindows()) { return false; } // Important to clear all caches first clearstatcache(true, $junction); if (!is_dir($junction) || is_link($junction)) { return false; } $stat = lstat($junction); // S_ISDIR test (S_IFDIR is 0x4000, S_IFMT is 0xF000 bitmask) return $stat ? 0x4000 !== ($stat['mode'] & 0xF000) : false; } /** * 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)); } return $this->rmdir($junction); } } * 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; } } } * 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 * @return bool */ public static function handle($level, $message, $file, $line) { // error code is not included in error_reporting if (!(error_reporting() & $level)) { return; } if (filter_var(ini_get('xdebug.scream'), FILTER_VALIDATE_BOOLEAN)) { $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)))); } } return true; } /** * 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; } } * 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); $safeCommand = preg_replace("{--password (.*[^\\\\]\') }", '--password \'***\' ', $safeCommand); $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 = func_num_args() > 1; $this->errorOutput = null; // TODO in v3, commands should be passed in as arrays of cmd + args if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) { $process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout()); } else { $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) { return self::escapeArgument($argument); } /** * Copy of ProcessUtils::escapeArgument() that is deprecated in Symfony 3.3 and 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]; } } * 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); } } * 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); } } * 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($io); $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; } } * 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' || PHP_SAPI === 'phpdbg') && (!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 = rawurldecode($proxy['user']); if (isset($proxy['pass'])) { $auth .= ':' . rawurldecode($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::getVersion(), 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 string|array $header * @return array */ private static function fixHttpHeaderField($header) { if (!is_array($header)) { $header = explode("\r\n", $header); } uasort($header, function ($el) { return stripos($el, 'content-type') === 0 ? 1 : -1; }); return $header; } } * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; /** * @author Andreas Schempp */ class Zip { /** * Gets content of the root composer.json inside a ZIP archive. * * @param string $pathToZip * @param string $filename * * @return string|null */ public static function getComposerJson($pathToZip) { if (!extension_loaded('zip')) { throw new \RuntimeException('The Zip Util requires PHP\'s zip extension'); } $zip = new \ZipArchive(); if ($zip->open($pathToZip) !== true) { return null; } if (0 == $zip->numFiles) { $zip->close(); return null; } $foundFileIndex = self::locateFile($zip, 'composer.json'); if (false === $foundFileIndex) { $zip->close(); return null; } $content = null; $configurationFileName = $zip->getNameIndex($foundFileIndex); $stream = $zip->getStream($configurationFileName); if (false !== $stream) { $content = stream_get_contents($stream); } $zip->close(); return $content; } /** * Find a file by name, returning the one that has the shortest path. * * @param \ZipArchive $zip * @param string $filename * * @return bool|int */ private static 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; } } * 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 ' . ProcessExecutor::escape($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 ' . ProcessExecutor::escape($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 .= '-u ' . $this->getUser() . ' '; if ($useClient) { $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 .= '@' . $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); } } public function windowsLogin($password) { $command = $this->generateP4Command(' login -a'); // TODO in v3 generate command as an array if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) { $process = Process::fromShellCommandline($command, null, null, $password); } else { $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 ' . ProcessExecutor::escape($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 ' . ProcessExecutor::escape($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 ' . ProcessExecutor::escape($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 '.ProcessExecutor::escape('//' . $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 '. ProcessExecutor::escape($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) { if (strpos($line, 'Label') !== 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) { if (strpos($line, 'Depot') !== false) { $fields = explode(' ', $line); if (strcmp($this->p4Depot, $fields[1]) === 0) { $this->p4DepotType = $fields[3]; return $this->isStream(); } } } return false; } /** * @param string $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 ' . ProcessExecutor::escape($label)); $this->executeCommand($command); $changes = $this->commandResult; if (strpos($changes, 'Change') !== 0) { return null; } $fields = explode(' ', $changes); return $fields[1]; } /** * @param string $fromReference * @param string $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 ' . ProcessExecutor::escape($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; } } * 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 and we have no auth configured yet $this->process->execute('git remote -v', $output, $cwd); if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match) && !$this->io->hasAuthentication($match[3])) { $this->io->setAuthentication($match[3], rawurldecode($match[1]), rawurldecode($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 ssh key access, try https with auth if (preg_match('{^git@' . self::getGitHubDomainsRegex($this->config) . ':(.+?)\.git$}i', $url, $match) || preg_match('{^(https?)://' . self::getGitHubDomainsRegex($this->config) . '/(.*)}', $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 ( preg_match('{^(git)@' . self::getGitLabDomainsRegex($this->config) . ':(.+?)\.git$}i', $url, $match) || preg_match('{^(https?)://' . self::getGitLabDomainsRegex($this->config) . '/(.*)}', $url, $match) ) { if ($match[1] === 'git') { $match[1] = 'https'; } if (!$this->io->hasAuthentication($match[2])) { $gitLabUtil = new GitLab($this->io, $this->config, $this->process); $message = 'Cloning failed, enter your GitLab credentials to access private repos'; if (!$gitLabUtil->authorizeOAuth($match[2]) && $this->io->isInteractive()) { $gitLabUtil->authorizeOAuthInteractively($match[1], $match[2], $message); } } if ($this->io->hasAuthentication($match[2])) { $auth = $this->io->getAuthentication($match[2]); if ($auth['password'] === 'private-token' || $auth['password'] === 'oauth2' || $auth['password'] === 'gitlab-ci-token') { $authUrl = $match[1] . '://' . rawurlencode($auth['password']) . ':' . rawurlencode($auth['username']) . '@' . $match[2] . '/' . $match[3]; // swap username and password } else { $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)) { return; } } } elseif ($this->isAuthenticationFailure($url, $match)) { // private non-github/gitlab/bitbucket 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 (' . $match[2] . '):'); $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; } } } $errorMsg = $this->process->getErrorOutput(); if ($initialClone) { $this->filesystem->removeDirectory($origCwd); } $this->throwException('Failed to execute ' . $command . "\n\n" . $errorMsg, $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) { $sanitizedUrl = preg_replace('{://([^@]+?):(.+?)@}', '://', $url); return sprintf('git remote set-url origin %s && git remote update --prune origin && git remote set-url origin %s', ProcessExecutor::escape($url), ProcessExecutor::escape($sanitizedUrl)); }; $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 ($this->checkRefIsInMirror($url, $dir, $ref)) { return true; } if ($this->syncMirror($url, $dir)) { return $this->checkRefIsInMirror($url, $dir, $ref); } return false; } private function checkRefIsInMirror($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), $ignoredOutput, $dir); if ($exitCode === 0) { return true; } } 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', 'fatal: could not read Username', ); $errorOutput = $this->process->getErrorOutput(); foreach ($authFailures as $authFailure) { if (strpos($errorOutput, $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 getGitLabDomainsRegex(Config $config) { return '(' . implode('|', array_map('preg_quote', $config->get('gitlab-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]; } } } * 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\XdebugHandler\XdebugHandler; /** * 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 { /** * 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() { return XdebugHandler::getAllIniFiles(); } /** * 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; } } * 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; /** * @var string|null */ private static $version; /** * @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($io); } 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); return $this->executeWithAuthRetry($command, $cwd, $url, $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) { // A local command has no remote url return $this->executeWithAuthRetry($command, $cwd, '', $path, $verbose); } private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose) { // Regenerate the command at each try, to use the newly user-provided credentials $command = $this->getCommand($svnCommand, $url, $path); $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($svnCommand, $cwd, $url, $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; } /** * Returns the version of the svn binary contained in PATH * * @return string|null */ public function binaryVersion() { if (!self::$version) { if (0 === $this->process->execute('svn --version', $output)) { if (preg_match('{(\d+(?:\.\d+)+)}', $output, $match)) { self::$version = $match[1]; } } } return self::$version; } } * 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) ); } } } * 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($io); $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; } /** * Extract ratelimit from response. * * @param array $headers Headers from Composer\Downloader\TransportException. * * @return array Associative array with the keys limit and reset. */ public 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; } /** * Finds whether a request failed due to rate limiting * * @param array $headers Headers from Composer\Downloader\TransportException. * * @return bool */ public function isRateLimited(array $headers) { foreach ($headers as $header) { if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) { return true; } } return false; } } * 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; /** * @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; } } * 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; use Composer\Spdx\SpdxLicenses; /** * 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.'; } else { $licenses = (array) $manifest['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(); foreach ($licenses as $license) { $spdxLicense = $licenseValidator->getLicenseByIdentifier($license); if ($spdxLicense && $spdxLicense[3]) { if (preg_match('{^[AL]?GPL-[123](\.[01])?\+$}i', $license)) { $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)) { $warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, use "'.$license.'-only" or "'.$license.'-or-later" instead', $license ); } else { $warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, see https://spdx.org/licenses/', $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 ); } } // report scripts-descriptions for non-existent scripts $scriptsDescriptions = isset($manifest['scripts-descriptions']) ? $manifest['scripts-descriptions'] : array(); $scripts = isset($manifest['scripts']) ? $manifest['scripts'] : array(); foreach ($scriptsDescriptions as $scriptName => $scriptDescription) { if (!array_key_exists($scriptName, $scripts)) { $warnings[] = sprintf( 'Description for non-existent script "%s" found in "scripts-descriptions"', $scriptName ); } } // 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); } } * 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\Composer; use Composer\Semver\Constraint\Constraint; use Composer\Package\Version\VersionParser; 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 * * @param array $options */ public function setOptions(array $options) { $this->options = array_replace_recursive($this->options, $options); } /** * Check is disable TLS. * * @return bool */ 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; } /** * @param array $headers array of returned headers like from getLastHeaders() * @return string|null */ public function findStatusMessage(array $headers) { $value = null; foreach ($headers as $header) { if (preg_match('{^HTTP/\S+ \d+}i', $header)) { // 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 = $header; } } 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, rawurldecode($match[1]), rawurldecode($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, 26) === 'http://repo.packagist.org/') { // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol $fileUrl = 'http://' . gethostbyname('repo.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 ') . $this->stripCredentialsFromUrl($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 ((!preg_match('{^http://(repo\.)?packagist\.org/p/}', $fileUrl) || (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); return true; }); try { $result = $this->getRemoteContents($originUrl, $fileUrl, $ctx, $http_response_header); if (!empty($http_response_header[0])) { $statusCode = $this->findStatusCode($http_response_header); if ($statusCode >= 400 && $this->findHeaderValue($http_response_header, 'content-type') === 'application/json') { self::outputWarnings($this->io, $originUrl, json_decode($result, true)); } if (in_array($statusCode, array(401, 403)) && $this->retryAuthFailure) { $this->promptAuthAndRetry($statusCode, $this->findStatusMessage($http_response_header), null, $http_response_header); } } $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 && !filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { $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; $locationHeader = null; if (!empty($http_response_header[0])) { $statusCode = $this->findStatusCode($http_response_header); $contentType = $this->findHeaderValue($http_response_header, 'content-type'); $locationHeader = $this->findHeaderValue($http_response_header, 'location'); } // check for bitbucket login page asking to authenticate if ($originUrl === 'bitbucket.org' && !$this->isPublicBitBucketDownload($fileUrl) && substr($fileUrl, -4) === '.zip' && (!$locationHeader || substr($locationHeader, -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); return true; }); $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 contents of remote URL. * * @param string $originUrl The origin URL * @param string $fileUrl The file URL * @param resource $context The stream context * * @return string|false The response contents or false on failure */ protected function getRemoteContents($originUrl, $fileUrl, $context, array &$responseHeaders = null) { try { $e = null; $result = file_get_contents($fileUrl, false, $context); } catch (\Throwable $e) { } catch (\Exception $e) { } $responseHeaders = isset($http_response_header) ? $http_response_header : array(); if (null !== $e) { throw $e; } 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); } 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, $warning = null, $headers = array()) { if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) { $gitHubUtil = new GitHub($this->io, $this->config, null); $message = "\n"; $rateLimited = $gitHubUtil->isRateLimited($headers); if ($rateLimited) { $rateLimit = $gitHubUtil->getRateLimit($headers); if ($this->io->hasAuthentication($this->originUrl)) { $message = 'Review your configured GitHub OAuth token or enter a new one to go over the API rate limit.'; } else { $message = 'Create a GitHub OAuth token to go over the API rate limit.'; } $message = sprintf( 'GitHub API limit (%d calls/hr) is exhausted, could not fetch '.$this->fileUrl.'. '.$message.' You can also wait until %s for the rate limit to reset.', $rateLimit['limit'], $rateLimit['reset'] )."\n"; } else { $message .= 'Could not fetch '.$this->fileUrl.', please '; if ($this->io->hasAuthentication($this->originUrl)) { $message .= 'review your configured GitHub OAuth token or enter a new one to access private repos'; } else { $message .= 'create a GitHub OAuth token to access private repos'; } } 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)) && in_array($auth['password'], array('gitlab-ci-token', 'private-token'), true)) { 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->writeError(' Authentication required ('.$this->originUrl.'):'); $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']; } elseif (!CaBundle::isOpensslParseSafe() && $host === 'repo.packagist.org') { // handle subjectAltName for packagist.org's repo domain on very old PHPs $tlsOptions['ssl']['CN_match'] = 'packagist.org'; } } $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' || $auth['password'] === 'gitlab-ci-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, $this->stripCredentialsFromUrl($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'; } public static function outputWarnings(IOInterface $io, $url, $data) { foreach (array('warning', 'info') as $type) { if (empty($data[$type])) { continue; } if (!empty($data[$type . '-versions'])) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($data[$type . '-versions']); $composer = new Constraint('==', $versionParser->normalize(Composer::getVersion())); if (!$constraint->matches($composer)) { continue; } } $io->writeError('<'.$type.'>'.ucfirst($type).' from '.$url.': '.$data[$type].''); } } public static function getOrigin($urlOrPath) { $hostPort = parse_url($urlOrPath, PHP_URL_HOST); if (!$hostPort) { return $urlOrPath; } if (parse_url($urlOrPath, PHP_URL_PORT)) { $hostPort .= ':'.parse_url($urlOrPath, PHP_URL_PORT); } return $hostPort; } private function stripCredentialsFromUrl($url) { // GitHub repository rename result in redirect locations containing the access_token as GET parameter // e.g. https://api.github.com/repositories/9999999999?access_token=github_token return preg_replace('{([&?]access_token=)[^&]+}', '$1***', $url); } } * 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 Jonas Renaudot */ class Hg { /** * @var \Composer\IO\IOInterface */ private $io; /** * @var \Composer\Config */ private $config; /** * @var \Composer\Util\ProcessExecutor */ private $process; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process) { $this->io = $io; $this->config = $config; $this->process = $process; } public function runCommand($commandCallable, $url, $cwd) { $this->config->prohibitUrlByConfig($url, $this->io); // Try as is $command = call_user_func($commandCallable, $url); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } // Try with the authentication informations available if (preg_match('{^(https?)://((.+)(?:\:(.+))?@)?([^/]+)(/.*)?}mi', $url, $match) && $this->io->hasAuthentication($match[5])) { $auth = $this->io->getAuthentication($match[5]); $authenticatedUrl = $match[1] . '://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[5] . (!empty($match[6]) ? $match[6] : null); $command = call_user_func($commandCallable, $authenticatedUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } $error = $this->process->getErrorOutput(); } else { $error = 'The given URL (' . $url . ') does not match the required format (http(s)://(username:password@)example.com/path-to-repository)'; } $this->throwException('Failed to clone ' . $url . ', ' . "\n\n" . $error, $url); } 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) { if (0 !== $this->process->execute('hg --version', $ignoredOutput)) { throw new \RuntimeException(self::sanitizeUrl('Failed to clone ' . $url . ', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput())); } throw new \RuntimeException(self::sanitizeUrl($message)); } } * 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 { /** * 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|void */ 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); }; } } } * 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 bool 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; } } * 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); } * 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); } } * 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; protected $conflictAddedMap; protected $addedPackages; protected $addedPackagesByNames; 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|null 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|null 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()) { /** @var PackageInterface $package */ $package = $workQueue->dequeue(); if (isset($this->addedMap[$package->id])) { continue; } $this->addedMap[$package->id] = true; $this->addedPackages[] = $package; foreach ($package->getNames() as $name) { $this->addedPackagesByNames[$name][] = $package; } 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, $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link)); foreach ($possibleRequires as $require) { $workQueue->enqueue($require); } } $packageName = $package->getName(); $obsoleteProviders = $this->pool->whatProvides($packageName, null); foreach ($obsoleteProviders as $provider) { if ($provider === $package) { continue; } if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) { $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package)); } elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) { $reason = ($packageName == $provider->getName()) ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES; $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $provider, $reason, $package)); } } } } protected function addConflictRules($ignorePlatformReqs = false) { /** @var PackageInterface $package */ foreach ($this->addedPackages as $package) { foreach ($package->getConflicts() as $link) { if (!isset($this->addedPackagesByNames[$link->getTarget()])) { continue; } if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) { continue; } /** @var PackageInterface $possibleConflict */ foreach ($this->addedPackagesByNames[$link->getTarget()] as $possibleConflict) { $conflictMatch = $this->pool->match($possibleConflict, $link->getTarget(), $link->getConstraint(), true); if ($conflictMatch === Pool::MATCH || $conflictMatch === Pool::MATCH_REPLACE) { $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $possibleConflict, Rule::RULE_PACKAGE_CONFLICT, $link)); } } } // check obsoletes and implicit obsoletes of a package $isInstalled = isset($this->installedMap[$package->id]); foreach ($package->getReplaces() as $link) { if (!isset($this->addedPackagesByNames[$link->getTarget()])) { continue; } /** @var PackageInterface $possibleConflict */ foreach ($this->addedPackagesByNames[$link->getTarget()] 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)); } } } } } 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(); $this->conflictAddedMap = array(); $this->addedPackages = array(); $this->addedPackagesByNames = array(); foreach ($this->installedMap as $package) { $this->addRulesForPackage($package, $ignorePlatformReqs); } $this->addRulesForJobs($ignorePlatformReqs); $this->addConflictRules($ignorePlatformReqs); // Remove references to packages $this->addedPackages = $this->addedPackagesByNames = null; return $this->rules; } } * 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 int $fromLiteral A literal the node used to watch * @param int $toLiteral A literal the node should watch now * @param RuleWatchNode $node 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); } } * 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 $job; 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 $this->job; } 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 &= ~(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.'; } $packages = $pool->whatProvides($targetName); $package = count($packages) ? current($packages) : phpversion(); if ($targetName === 'hhvm') { if ($package instanceof CompletePackage) { return $text . ' -> your HHVM version ('.$package->getPrettyVersion().') does not satisfy that requirement.'; } else { return $text . ' -> you are running this with PHP and not HHVM.'; } } 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); } } * 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 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 */ public 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; } } * 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; } } * 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(); $literalCount = count($literals); $this->watch1 = $literalCount > 0 ? $literals[0] : 0; $this->watch2 = $literalCount > 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; } } } * 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); $job = $reason['job']; $packageName = $job['packageName']; $constraint = $job['constraint']; if (isset($constraint)) { $packages = $this->pool->whatProvides($packageName, $constraint); } else { $packages = array(); } if ($job && $job['cmd'] === 'install' && empty($packages)) { // handle php/hhvm if ($packageName === 'php' || $packageName === 'php-64bit' || $packageName === 'hhvm') { $version = phpversion(); $available = $this->pool->whatProvides($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 ".$packageName.$this->constraintToText($constraint).' but '; if (defined('HHVM_VERSION') || (count($available) && $packageName === 'hhvm')) { return $msg . 'your HHVM version does not satisfy that requirement.'; } if ($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($packageName, 'ext-')) { if (false !== strpos($packageName, ' ')) { return "\n - The requested PHP extension ".$packageName.' should be required as '.str_replace(' ', '-', $packageName).'.'; } $ext = substr($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 ".$packageName.$this->constraintToText($constraint).' '.$error.'. Install or enable PHP\'s '.$ext.' extension.'; } // handle linked libs if (0 === stripos($packageName, 'lib-')) { if (strtolower($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 ".$packageName.$this->constraintToText($constraint).' '.$error; } return "\n - The requested linked library ".$packageName.$this->constraintToText($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_./-]+$}', $packageName)) { $illegalChars = preg_replace('{[A-Za-z0-9_./-]+}', '', $packageName); return "\n - The requested package ".$packageName.' could not be found, it looks like its name is invalid, "'.$illegalChars.'" is not allowed in package names.'; } if ($providers = $this->pool->whatProvides($packageName, $constraint, true, true)) { return "\n - The requested package ".$packageName.$this->constraintToText($constraint).' is satisfiable by '.$this->getPackageList($providers).' but these conflict with your requirements or minimum-stability.'; } if ($providers = $this->pool->whatProvides($packageName, null, true, true)) { return "\n - The requested package ".$packageName.$this->constraintToText($constraint).' exists as '.$this->getPackageList($providers).' but these are rejected by your constraint.'; } return "\n - The requested package ".$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) { $packageName = $job['packageName']; $constraint = $job['constraint']; switch ($job['cmd']) { case 'install': $packages = $this->pool->whatProvides($packageName, $constraint); if (!$packages) { return 'No package found to satisfy install request for '.$packageName.$this->constraintToText($constraint); } return 'Installation request for '.$packageName.$this->constraintToText($constraint).' -> satisfiable by '.$this->getPackageList($packages).'.'; case 'update': return 'Update request for '.$packageName.$this->constraintToText($constraint).'.'; case 'remove': return 'Removal request for '.$packageName.$this->constraintToText($constraint).''; } if (isset($constraint)) { $packages = $this->pool->whatProvides($packageName, $constraint); } else { $packages = array(); } return 'Job(cmd='.$job['cmd'].', target='.$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() : ''; } } * 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; } } public function __toString() { $decisionMap = $this->decisionMap; ksort($decisionMap); $str = '['; foreach ($decisionMap as $packageId => $level) { $str .= $packageId.':'.$level.','; } $str .= ']'; return $str; } } * 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 bool */ public $testFlagLearnedPositiveLiteral = false; /** @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($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('', true, IOInterface::DEBUG); $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) { if ($literal < 0) { $this->testFlagLearnedPositiveLiteral = true; } $learnedLiterals[0] = -$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) { if ($conflictRule->getType() == RuleSet::TYPE_LEARNED) { $why = spl_object_hash($conflictRule); $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); $pass = 1; $this->io->writeError('Looking at all rules.', true, IOInterface::DEBUG); for ($i = 0, $n = 0; $n < $rulesCount; $i++, $n++) { if ($i == $rulesCount) { if (1 === $pass) { $this->io->writeError("Something's changed, looking at all rules again (pass #$pass)", false, IOInterface::DEBUG); } else { $this->io->overwriteError("Something's changed, looking at all rules again (pass #$pass)", false, null, IOInterface::DEBUG); } $i = 0; $pass++; } $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($literal)) { continue 2; // next rule } } else { if ($this->decisions->decidedInstall($literal)) { continue 2; // next rule } if ($this->decisions->undecided($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; } } } * 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" ); } } * 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; } } * 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); } } * 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; } } * 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); } } * 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; } } * 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]); } } * 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).')'; } } * 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).')'; } } * 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()).')'; } } * 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).')'; } } * 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(); } * 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(); } } * 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()).')'; } } * 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() { return $this->literal1.','.$this->literal2; } /** * 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) { // specialized fast-case if ($rule instanceof self) { if ($this->literal1 !== $rule->literal1) { return false; } if ($this->literal2 !== $rule->literal2) { return false; } return true; } $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; } } * 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; } } * 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); } } * 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|null 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); } } * 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); } * 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); } } } * 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 callable $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); } } * 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 \SplFileInfo $file */ $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'); } } * 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|null 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; } } * 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())) { array_push($nameParts, $package->getDistReference(), $package->getDistType()); } else { array_push($nameParts, $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); try { // Download sources $this->downloadManager->download($package, $sourcePath); } catch (\Exception $e) { $filesystem->removeDirectory($sourcePath); throw $e; } // 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; } } * 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(); } } * 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]); } } * 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 { } * 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 { } * 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 { } * 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 { } * 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 { } * 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) { return array('version' => $version, 'commit' => null, 'pretty_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]; } } } 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; } // 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]; 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); } } } } * 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; use Composer\Semver\Semver; 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; } /** * @return bool */ public static function isUpgrade($normalizedFrom, $normalizedTo) { if (substr($normalizedFrom, 0, 4) === 'dev-' || substr($normalizedTo, 0, 4) === 'dev-') { return true; } $sorted = Semver::sort(array($normalizedTo, $normalizedFrom)); return $sorted[0] === $normalizedFrom; } } * 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; } } * 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(); /** * @param string $reference * * @return void */ public function setSourceReference($reference); /** * @param string $url * * @return void */ public function setDistUrl($url); /** * @param string $type * * @return void */ public function setDistType($type); /** * @param string $reference * * @return void */ public function setDistReference($reference); } * 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; } } * 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(); if (null !== ($value = $package->getSourceReference())) { $data['source']['reference'] = $value; } if ($mirrors = $package->getSourceMirrors()) { $data['source']['mirrors'] = $mirrors; } } if ($package->getDistType()) { $data['dist']['type'] = $package->getDistType(); $data['dist']['url'] = $package->getDistUrl(); if (null !== ($value = $package->getDistReference())) { $data['dist']['reference'] = $value; } if (null !== ($value = $package->getDistSha1Checksum())) { $data['dist']['shasum'] = $value; } 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; } } * 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; } } * 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); } } * 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(isset($config['source']['reference']) ? $config['source']['reference'] : null); 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; } } } * 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'); } * 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\IO\IOInterface; 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; /** * @var IOInterface */ private $io; public function __construct(RepositoryManager $manager, Config $config, VersionParser $parser = null, VersionGuesser $versionGuesser = null, IOInterface $io = null) { parent::__construct($parser); $this->manager = $manager; $this->config = $config; $this->versionGuesser = $versionGuesser ?: new VersionGuesser($config, new ProcessExecutor(), $this->versionParser); $this->io = $io; } /** * @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__'; } elseif ($this->io) { if ($err = ValidatingArrayLoader::hasPackageNamingError($config['name'])) { $this->io->writeError('Deprecation warning: Your package name '.$err.' Make sure you fix this as Composer 2.0 will error.'); } } $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 ($this->io) { foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) { if (isset($config[$linkType])) { foreach ($config[$linkType] as $linkName => $constraint) { if ($err = ValidatingArrayLoader::hasPackageNamingError($linkName, true)) { $this->io->writeError('Deprecation warning: '.$linkType.'.'.$err.' Make sure you fix this as Composer 2.0 will error.'); } } } } } 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' === VersionParser::parseStability($reqVersion)) { $name = strtolower($reqName); $references[$name] = $match[1]; } } return $references; } } * 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\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 ($err = self::hasPackageNamingError($config['name'])) { $this->warnings[] = 'Deprecation warning: Your package name '.$err.' Make sure you fix this as Composer 2.0 will error.'; } 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']); } } // check for license validity on newly updated branches if (isset($this->config['license']) && (!$releaseDate || $releaseDate->getTimestamp() >= strtotime('-8days'))) { 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']) ); } } } 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', 'chat') 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', 'chat') 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 ($err = self::hasPackageNamingError($package, true)) { $this->warnings[] = 'Deprecation warning: '.$linkType.'.'.$err.' Make sure you fix this as Composer 2.0 will error.'; } elseif (!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; } public static function hasPackageNamingError($name, $isLink = false) { if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) { return; } if (!preg_match('{^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*$}iD', $name)) { return $name.' is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match "[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*".'; } $reservedNames = array('nul', 'con', 'prn', 'aux', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9', 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'); $bits = explode('/', strtolower($name)); if (in_array($bits[0], $reservedNames, true) || in_array($bits[1], $reservedNames, true)) { return $name.' is reserved, package and vendor names can not match any of: '.implode(', ', $reservedNames).'.'; } if (preg_match('{\.json$}', $name)) { return $name.' is invalid, package names can not end in .json, consider renaming it or perhaps using a -json suffix instead.'; } if (preg_match('{[A-Z]}', $name)) { if ($isLink) { return $name.' is invalid, it should not contain uppercase characters. Please use '.strtolower($name).' instead.'; } $suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name); $suggestName = strtolower($suggestName); return $name.' is invalid, it should not contain uppercase characters. We suggest using '.$suggestName.' instead.'; } } 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; } } * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Comparer; /** * class Comparer * * @author Hector Prats */ class Comparer { private $source; private $update; private $changed; public function setSource($source) { $this->source = $source; } public function setUpdate($update) { $this->update = $update; } public function getChanged($toString = false, $explicated = false) { $changed = $this->changed; if (!count($changed)) { return false; } if ($explicated) { foreach ($changed as $sectionKey => $itemSection) { foreach ($itemSection as $itemKey => $item) { $changed[$sectionKey][$itemKey] = $item.' ('.$sectionKey.')'; } } } if ($toString) { foreach ($changed as $sectionKey => $itemSection) { foreach ($itemSection as $itemKey => $item) { $changed['string'][] = $item."\r\n"; } } $changed = implode("\r\n", $changed['string']); } return $changed; } public function doCompare() { $source = array(); $destination = array(); $this->changed = array(); $currentDirectory = getcwd(); chdir($this->source); $source = $this->doTree('.', $source); if (!is_array($source)) { return; } chdir($currentDirectory); chdir($this->update); $destination = $this->doTree('.', $destination); if (!is_array($destination)) { exit; } chdir($currentDirectory); foreach ($source as $dir => $value) { foreach ($value as $file => $hash) { if (isset($destination[$dir][$file])) { if ($hash !== $destination[$dir][$file]) { $this->changed['changed'][] = $dir.'/'.$file; } } else { $this->changed['removed'][] = $dir.'/'.$file; } } } foreach ($destination as $dir => $value) { foreach ($value as $file => $hash) { if (!isset($source[$dir][$file])) { $this->changed['added'][] = $dir.'/'.$file; } } } } private function doTree($dir, &$array) { if ($dh = opendir($dir)) { while ($file = readdir($dh)) { if ($file !== '.' && $file !== '..') { if (is_dir($dir.'/'.$file)) { if (!count($array)) { $array[0] = 'Temp'; } if (!$this->doTree($dir.'/'.$file, $array)) { return false; } } else { if (filesize($dir.'/'.$file)) { set_time_limit(30); $array[$dir][$file] = md5_file($dir.'/'.$file); } } } } if (count($array) > 1 && isset($array['0'])) { unset($array['0']); } return $array; } return false; } } * 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; } } * 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; } } * 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; } /** * Build a regexp from a package name, expanding * globs as required * * @param string $whiteListedPattern * @param bool $wrap Wrap the cleaned string by the given string * @return string */ public static function packageNameToRegexp($whiteListedPattern, $wrap = '{^%s$}i') { $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern)); return sprintf($wrap, $cleanedWhiteListedPattern); } } * 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().')'; } public function setDistUrl($url) { return $this->aliasOf->setDistUrl($url); } public function setDistType($type) { return $this->aliasOf->setDistType($type); } } * 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#installing-dependencies', '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; } } * 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); } * 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(); } * 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().''; } } * 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/symfony/console/Resources/bin/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/justinrainbow/json-schema/') ->in(__DIR__.'/../../vendor/composer/spdx-licenses/') ->in(__DIR__.'/../../vendor/composer/semver/') ->in(__DIR__.'/../../vendor/composer/ca-bundle/') ->in(__DIR__.'/../../vendor/composer/xdebug-handler/') ->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); $content = preg_replace('{SOURCE_VERSION = \'[^\']+\';}', 'SOURCE_VERSION = \'\';', $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') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.cache_by_default'), FILTER_VALIDATE_BOOLEAN)) { 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; } } * 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 { /* * Examples of the following constants in the various configurations they can be in * * releases (phar): * const VERSION = '1.8.2'; * const BRANCH_ALIAS_VERSION = ''; * const RELEASE_DATE = '2019-01-29 15:00:53'; * const SOURCE_VERSION = ''; * * snapshot builds (phar): * const VERSION = 'd3873a05650e168251067d9648845c220c50e2d7'; * const BRANCH_ALIAS_VERSION = '1.9-dev'; * const RELEASE_DATE = '2019-02-20 07:43:56'; * const SOURCE_VERSION = ''; * * source (git clone): * const VERSION = '1.9.1'; * const BRANCH_ALIAS_VERSION = ''; * const RELEASE_DATE = '2019-11-01 17:20:17'; * const SOURCE_VERSION = '1.8-dev+source'; */ const VERSION = '1.9.1'; const BRANCH_ALIAS_VERSION = ''; const RELEASE_DATE = '2019-11-01 17:20:17'; const SOURCE_VERSION = '1.9-dev+source'; public static function getVersion() { // no replacement done, this must be a source checkout if (self::VERSION === '@package_version'.'@') { return self::SOURCE_VERSION; } // we have a branch alias and version is a commit id, this must be a snapshot build if (self::BRANCH_ALIAS_VERSION !== '' && preg_match('{^[a-f0-9]{40}$}', self::VERSION)) { return self::BRANCH_ALIAS_VERSION.'+'.self::VERSION; } return self::VERSION; } /** * @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; } } * 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 (!self::isUsable($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 static function isUsable($path) { return !preg_match('{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $path); } public function isEnabled() { return $this->enabled; } public function getRoot() { return $this->root; } public function read($file) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (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) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (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) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (file_exists($this->root . $file)) { return $this->filesystem->unlink($this->root . $file); } } return false; } public function clear() { if ($this->enabled) { $this->filesystem->emptyDirectory($this->root); return true; } 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) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (file_exists($this->root . $file)) { return sha1_file($this->root . $file); } } return false; } public function sha256($file) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (file_exists($this->root . $file)) { return hash_file('sha256', $this->root . $file); } } return false; } protected function getFinder() { return Finder::create()->in($this->root)->files(); } } * 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. Read more at https://getcomposer.org/doc/03-cli.md#clear-cache-clearcache- 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.'); return 0; } } * 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\Input\InputOption; 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.') ->setDefinition(array( new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables checking of require-dev packages requirements.'), )) ->setHelp( <<php composer.phar check-platform-reqs EOT ); } protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(); $requires = $composer->getPackage()->getRequires(); if ($input->getOption('no-dev')) { $dependencies = $composer->getLocker()->getLockedRepository(!$input->getOption('no-dev'))->getPackages(); } else { $dependencies = $composer->getRepositoryManager()->getLocalRepository()->getPackages(); // fallback to lockfile if installed repo is empty if (!$dependencies) { $dependencies = $composer->getLocker()->getLockedRepository(true)->getPackages(); } $requires += $composer->getPackage()->getDevRequires(); } foreach ($requires as $require => $link) { $requires[$require] = array($link); } foreach ($dependencies 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[] $links */ 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'); $rendererStyle = $renderer->getStyle(); $rendererStyle->setVerticalBorderChar(''); $rendererStyle->setCellRowContentFormat('%s '); $renderer->setRows($table)->render(); } } * 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'), new InputOption('ignore', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore specified package(s). Use it with the --outdated option if you don\'t want to be informed about new versions of some packages.'), )) ->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. Read more at https://getcomposer.org/doc/03-cli.md#outdated EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $args = array( 'command' => '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'); $args['--ignore'] = $input->getOption('ignore'); $input = new ArrayInput($args); return $this->getApplication()->run($input, $output); } /** * {@inheritDoc} */ public function isProxyCommand() { return true; } } * 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\IO\IOInterface; 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 Read more at https://getcomposer.org/doc/03-cli.md#config 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, true, IOInterface::QUIET); 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), 'use-github-api' => 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]))) { if ($settingKey === 'disable-tls' && $this->config->get('disable-tls')) { $this->getIO()->writeError('You are now running Composer with SSL/TLS protection enabled.'); } $this->configSource->removeConfigSetting($settingKey); return 0; } if (isset($uniqueConfigValues[$settingKey])) { $this->handleSingleValue($settingKey, $uniqueConfigValues[$settingKey], $values, 'addConfigSetting'); return 0; } if (isset($multiConfigValues[$settingKey])) { $this->handleMultiValue($settingKey, $multiConfigValues[$settingKey], $values, 'addConfigSetting'); return 0; } // 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]))) { $this->configSource->removeProperty($settingKey); return 0; } if (isset($uniqueProps[$settingKey])) { $this->handleSingleValue($settingKey, $uniqueProps[$settingKey], $values, 'addProperty'); return 0; } if (isset($multiProps[$settingKey])) { $this->handleMultiValue($settingKey, $multiProps[$settingKey], $values, 'addProperty'); return 0; } // handle repositories if (preg_match('/^repos?(?:itories)?\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeRepository($matches[1]); return 0; } if (2 === count($values)) { $this->configSource->addRepository($matches[1], array( 'type' => $values[0], 'url' => $values[1], )); return 0; } if (1 === count($values)) { $value = strtolower($values[0]); if (true === $booleanValidator($value)) { if (false === $booleanNormalizer($value)) { $this->configSource->addRepository($matches[1], false); return 0; } } else { $value = JsonFile::parseJson($values[0]); $this->configSource->addRepository($matches[1], $value); return 0; } } 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')) { $this->configSource->removeProperty($settingKey); return 0; } $this->configSource->addProperty($settingKey, $values[0]); return 0; } // handle platform if (preg_match('/^platform\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } $this->configSource->addConfigSetting($settingKey, $values[0]); return 0; } if ($settingKey === 'platform' && $input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } // 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 0; } 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 0; } // handle script if (preg_match('/^scripts\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeProperty($settingKey); return 0; } $this->configSource->addProperty($settingKey, count($values) > 1 ? $values : $values[0]); return 0; } 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] )); } $normalizedValue = $normalizer($values[0]); if ($key === 'disable-tls') { if (!$normalizedValue && $this->config->get('disable-tls')) { $this->getIO()->writeError('You are now running Composer with SSL/TLS protection enabled.'); } elseif ($normalizedValue && !$this->config->get('disable-tls')) { $this->getIO()->writeError('You are now running Composer with SSL/TLS protection disabled.'); } } return call_user_func(array($this->configSource, $method), $key, $normalizedValue); } 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 . ')', true, IOInterface::QUIET); } else { $io->write('[' . $k . $key . '] ' . $value . '', true, IOInterface::QUIET); } } } } * 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\ArrayInput; 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 Read more at https://getcomposer.org/doc/03-cli.md#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); } } } $question = 'Would you like to install dependencies now [yes]? '; if ($input->isInteractive() && $this->hasDependencies($options) && $io->askConfirmation($question, true)) { $this->installDependencies($output); } return 0; } /** * {@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); $createDefaultPackagistRepo = true; foreach ($repositories as $repo) { $repoConfig = RepositoryFactory::configFromString($io, $config, $repo); if ( (isset($repoConfig['packagist']) && $repoConfig === array('packagist' => false)) || (isset($repoConfig['packagist.org']) && $repoConfig === array('packagist.org' => false)) ) { $createDefaultPackagistRepo = false; continue; } $repos[] = RepositoryFactory::createRepo($io, $config, $repoConfig); } if ($createDefaultPackagistRepo) { $repos[] = RepositoryFactory::createRepo($io, $config, array( 'type' => 'composer', 'url' => 'https://repo.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 = strtolower($name); } else { if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $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_.-]+$}D', $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 ($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.', '')); // prepare to resolve dependencies $repos = $this->getRepos(); $preferredStability = $minimumStability ?: 'stable'; $phpVersion = $repos->findPackage('php', '*')->getPrettyVersion(); $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, $phpVersion, $preferredStability); } $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, $phpVersion, $preferredStability); } $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', $checkProvidedVersions = true) { 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, $checkProvidedVersions ? $requirement['version'] : null, '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'); // TODO in v3 always call with an array if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) { $cmd = new Process(array($gitBin, 'config', '-l')); } else { $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)); $ignorePlatformReqs = $input->hasOption('ignore-platform-reqs') && $input->getOption('ignore-platform-reqs'); // ignore phpVersion if platform requirements are ignored if ($ignorePlatformReqs) { $phpVersion = null; } $package = $versionSelector->findBestCandidate($name, $requiredVersion, $phpVersion, $preferredStability); if (!$package) { // platform packages can not be found in the pool in versions other than the local platform's has // so if platform reqs are ignored we just take the user's word for it if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) { return array($name, $requiredVersion ?: '*'); } // 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)); } private function installDependencies($output) { try { $installCommand = $this->getApplication()->find('install'); $installCommand->run(new ArrayInput(array()), $output); } catch (\Exception $e) { $this->getIO()->writeError('Could not install dependencies. Run `composer install` to see more information.'); } } private function hasDependencies($options) { $requires = (array) $options['require']; $devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : array(); return !empty($requires) || !empty($devRequires); } } * 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('ignore', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore specified package(s). Use it with the --outdated option if you don\'t want to be informed about new versions of some 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('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); } elseif ($input->getOption('ignore')) { $io->writeError('You are using the option "ignore" for action other than "outdated", it will be ignored.'); } 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; } if ($input->getOption('tree') && $input->getOption('latest')) { $io->writeError('The --tree (-t) option is not usable in combination with --latest (-l)'); 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 (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')) { $arrayTree = $this->generatePackageTree($package, $installedRepo, $repos); if ('json' === $format) { $io->write(JsonFile::encode(array('installed' => array($arrayTree)))); } else { $this->displayPackageTree(array($arrayTree)); } } 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; } if ($input->getOption('path')) { $io->write($package->getName(), false); $io->write(' ' . strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n")); return $exitCode; } $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')) { $rootRequires = $this->getRootRequires(); $packages = $installedRepo->getPackages(); usort($packages, 'strcmp'); $arrayTree = array(); foreach ($packages as $package) { if (in_array($package->getName(), $rootRequires, true)) { $arrayTree[] = $this->generatePackageTree($package, $installedRepo, $repos); } } if ('json' === $format) { $io->write(JsonFile::encode(array('installed' => $arrayTree))); } else { $this->displayPackageTree($arrayTree); } 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'); $ignoredPackages = array_map('strtolower', $input->getOption('ignore')); $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; if ($showLatest && $showVersion) { foreach ($packages[$type] as $package) { if (is_object($package)) { $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion, $showMinorOnly); if ($latestPackage === false) { continue; } $latestPackages[$package->getPrettyName()] = $latestPackage; } } } $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(); foreach ($packages[$type] as $package) { $packageViewData = array(); if (is_object($package)) { $latestPackage = null; if ($showLatest && isset($latestPackages[$package->getPrettyName()])) { $latestPackage = $latestPackages[$package->getPrettyName()]; } // Determine if Composer is checking outdated dependencies and if current package should trigger non-default exit code $packageIsUpToDate = $latestPackage && $latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion() && !$latestPackage->isAbandoned(); $packageIsIgnored = \in_array($package->getPrettyName(), $ignoredPackages, true); if ($input->getOption('outdated') && ($packageIsUpToDate || $packageIsIgnored)) { continue; } elseif ($input->getOption('outdated') || $input->getOption('strict')) { $hasOutdatedPackages = true; } $packageViewData['name'] = $package->getPrettyName(); $nameLength = max($nameLength, strlen($package->getPrettyName())); if ($writeVersion) { $packageViewData['version'] = $package->getFullPrettyVersion(); $versionLength = max($versionLength, strlen($package->getFullPrettyVersion())); } if ($writeLatest && $latestPackage) { $packageViewData['latest'] = $latestPackage->getFullPrettyVersion(); $packageViewData['latest-status'] = $this->getUpdateStatus($latestPackage, $package); $latestLength = max($latestLength, strlen($latestPackage->getFullPrettyVersion())); } 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; $nameLength = max($nameLength, strlen($package)); } $viewData[$type][] = $packageViewData; } $viewMetaData[$type] = array( 'nameLength' => $nameLength, 'versionLength' => $versionLength, 'latestLength' => $latestLength, ); 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->writeError('' . $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())); if ($installedRepo->hasPackage($package)) { $io->write('path : ' . sprintf('%s', realpath($this->getComposer()->getInstallationManager()->getInstallPath($package)))); } $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 array $arrayTree */ protected function displayPackageTree(array $arrayTree) { $io = $this->getIO(); foreach ($arrayTree as $package) { $io->write(sprintf('%s', $package['name']), false); $io->write(' ' . $package['version'], false); $io->write(' ' . strtok($package['description'], "\r\n")); if (isset($package['requires'])) { $requires = $package['requires']; $treeBar = '├'; $j = 0; $total = count($requires); foreach ($requires as $require) { $requireName = $require['name']; $j++; if ($j === $total) { $treeBar = '└'; } $level = 1; $color = $this->colors[$level]; $info = sprintf( '%s──<%s>%s %s', $treeBar, $color, $requireName, $color, $require['version'] ); $this->writeTreeLine($info); $treeBar = str_replace('└', ' ', $treeBar); $packagesInTree = array($package['name'], $requireName); $this->displayTree($require, $packagesInTree, $treeBar, $level + 1); } } } } /** * Generate the package tree * * @param PackageInterface $package * @param RepositoryInterface $installedRepo * @param RepositoryInterface $distantRepos * @return array */ protected function generatePackageTree( PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos ) { $requires = $package->getRequires(); ksort($requires); $children = array(); foreach ($requires as $requireName => $require) { $packagesInTree = array($package->getName(), $requireName); $treeChildDesc = array( 'name' => $requireName, 'version' => $require->getPrettyConstraint(), ); $deepChildren = $this->addTree($requireName, $require, $installedRepo, $distantRepos, $packagesInTree); if ($deepChildren) { $treeChildDesc['requires'] = $deepChildren; } $children[] = $treeChildDesc; } $tree = array( 'name' => $package->getPrettyName(), 'version' => $package->getPrettyVersion(), 'description' => $package->getDescription(), ); if ($children) { $tree['requires'] = $children; } return $tree; } /** * Display a package tree * * @param PackageInterface|string $package * @param array $packagesInTree * @param string $previousTreeBar * @param int $level */ protected function displayTree( $package, array $packagesInTree, $previousTreeBar = '├', $level = 1 ) { $previousTreeBar = str_replace('├', '│', $previousTreeBar); if (isset($package['requires'])) { $requires = $package['requires']; $treeBar = $previousTreeBar . ' ├'; $i = 0; $total = count($requires); foreach ($requires as $require) { $currentTree = $packagesInTree; $i++; if ($i === $total) { $treeBar = $previousTreeBar . ' └'; } $colorIdent = $level % count($this->colors); $color = $this->colors[$colorIdent]; $circularWarn = in_array( $require['name'], $currentTree, true ) ? '(circular dependency aborted here)' : ''; $info = rtrim(sprintf( '%s──<%s>%s %s %s', $treeBar, $color, $require['name'], $color, $require['version'], $circularWarn )); $this->writeTreeLine($info); $treeBar = str_replace('└', ' ', $treeBar); $currentTree[] = $require['name']; $this->displayTree($require, $currentTree, $treeBar, $level + 1); } } } /** * Display a package tree * * @param string $name * @param PackageInterface|string $package * @param RepositoryInterface $installedRepo * @param RepositoryInterface $distantRepos * @param array $packagesInTree * @return array */ protected function addTree( $name, $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos, array $packagesInTree ) { $children = array(); 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); foreach ($requires as $requireName => $require) { $currentTree = $packagesInTree; $treeChildDesc = array( 'name' => $requireName, 'version' => $require->getPrettyConstraint(), ); if (!in_array($requireName, $currentTree, true)) { $currentTree[] = $requireName; $deepChildren = $this->addTree($requireName, $require, $installedRepo, $distantRepos, $currentTree); if ($deepChildren) { $treeChildDesc['requires'] = $deepChildren; } } $children[] = $treeChildDesc; } } return $children; } 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; } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#depends-why- EOT ) ; } /** * Execute the function. * * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { return parent::doExecute($input, $output, false); } } * 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; use Composer\IO\IOInterface; use Composer\Util\Silencer; /** * @author Jérémy Romey * @author Jordi Boggiano */ class RequireCommand extends InitCommand { private $newlyCreated; private $json; private $file; private $composerBackup; 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( <<file = Factory::getComposerFile(); $io = $this->getIO(); $this->newlyCreated = !file_exists($this->file); if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) { $io->writeError(''.$this->file.' could not be created.'); return 1; } // check for readability by reading the file as is_readable can not be trusted on network-mounts // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926 if (!is_readable($this->file) && false === Silencer::call('file_get_contents', $this->file)) { $io->writeError(''.$this->file.' is not readable.'); return 1; } if (filesize($this->file) === 0) { file_put_contents($this->file, "{\n}\n"); } $this->json = new JsonFile($this->file); $this->composerBackup = file_get_contents($this->json->getPath()); // check for writability by writing to the file as is_writable can not be trusted on network-mounts // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926 if (!is_writable($this->file) && !Silencer::call('file_put_contents', $this->file, $this->composerBackup)) { $io->writeError(''.$this->file.' is not writable.'); return 1; } $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(); try { $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability, !$input->getOption('no-update')); } catch (\Exception $e) { if ($this->newlyCreated) { throw new \RuntimeException('No composer.json present in the current directory, this may be the cause of the following exception.', 0, $e); } throw $e; } $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 $package => $constraint) { if (strtolower($package) === $composer->getPackage()->getName()) { $io->writeError(sprintf('Root package \'%s\' cannot require itself in its composer.json', $package)); return 1; } $versionParser->parseConstraints($constraint); } $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages'); if (!$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) { $composerDefinition = $this->json->read(); foreach ($requirements as $package => $version) { $composerDefinition[$requireKey][$package] = $version; unset($composerDefinition[$removeKey][$package]); } $this->json->write($composerDefinition); } $io->writeError(''.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').''); if ($input->getOption('no-update')) { return 0; } try { return $this->doUpdate($input, $output, $io, $requirements); } catch (\Exception $e) { $this->revertComposerFile(false); throw $e; } } private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements) { // Update packages $this->resetComposer(); $composer = $this->getComposer(true, $input->getOption('no-plugins')); $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress')); $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'); $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) { $this->revertComposerFile(false); } 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; } public function revertComposerFile($hardExit = true) { $io = $this->getIO(); if ($this->newlyCreated) { $io->writeError("\n".'Installation failed, deleting '.$this->file.'.'); unlink($this->json->getPath()); } else { $io->writeError("\n".'Installation failed, reverting '.$this->file.' to its original content.'); file_put_contents($this->json->getPath(), $this->composerBackup); } if ($hardExit) { exit(1); } } } * 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()); } } * 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 - Dependency Manager for PHP Composer is a dependency manager tracking local dependencies of your projects and libraries. See https://getcomposer.org/ for more information. EOT ); return 0; } } * 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 validate requires for overly strict/loose constraints'), 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, $input->hasParameterOption('--no-plugins')); $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, $isStrict); // $errors include publish and lock errors when exists $exitCode = $errors ? 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 ? 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, $isStrict = 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 // Skip when it is a strict check and we don't want to check publish errors if ($checkPublish) { $errors = array_merge($errors, $publishErrors); } elseif (!$isStrict) { $warnings = array_merge($warnings, $publishErrors); } // If checking lock errors, display them as errors, otherwise just show them as warnings // Skip when it is a strict check and we don't want to check lock errors if ($checkLock) { $errors = array_merge($errors, $lockErrors); } elseif (!$isStrict) { $warnings = array_merge($warnings, $lockErrors); } $messages = array( 'error' => $errors, 'warning' => $warnings, ); foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { $io->writeError('<' . $style . '>' . $msg . ''); } } } } * 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 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(strtolower($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'); $rendererStyle = $renderer->getStyle(); $rendererStyle->setVerticalBorderChar(''); $rendererStyle->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); } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload- 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)', false); } elseif ($optimize) { $this->getIO()->writeError('Generating optimized autoload files', false); } else { $this->getIO()->writeError('Generating autoload files', false); } $generator = $composer->getAutoloadGenerator(); $generator->setDevMode(!$input->getOption('no-dev')); $generator->setClassMapAuthoritative($authoritative); $generator->setApcu($apcu); $generator->setRunScripts(!$input->getOption('no-scripts')); $numberOfClasses = $generator->dump($config, $localRepo, $package, $installationManager, 'composer', $optimize); if ($authoritative) { $this->getIO()->overwriteError('Generated optimized autoload files (authoritative) containing '. $numberOfClasses .' classes'); } elseif ($optimize) { $this->getIO()->overwriteError('Generated optimized autoload files containing '. $numberOfClasses .' classes'); } else { $this->getIO()->overwriteError('Generated autoload files containing '. $numberOfClasses .' classes'); } return 0; } } * 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]] Read more at https://getcomposer.org/doc/03-cli.md#archive 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); $eventDispatcher = $composer->getEventDispatcher(); $eventDispatcher->dispatch($commandEvent->getName(), $commandEvent); $eventDispatcher->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; } } * 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' ), )) ->setHelp( <<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')); } } * 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'); $tableStyle = $table->getStyle(); $tableStyle->setVerticalBorderChar(''); $tableStyle->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)); } return 0; } /** * 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; } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#prohibits-why-not- EOT ) ; } /** * Execute the function. * * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { return parent::doExecute($input, $output, true); } } * 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') ->setAliases(array('i')) ->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 Read more at https://getcomposer.org/doc/03-cli.md#install-i 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(); } } * 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\Util\Filesystem; 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. Read more at https://getcomposer.org/doc/03-cli.md#global 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(); $home = $config->get('home'); if (!is_dir($home)) { $fs = new Filesystem(); $fs->ensureDirectoryExists($home); if (!is_dir($home)) { throw new \RuntimeException('Could not create home directory'); } } try { chdir($home); } catch (\Exception $e) { throw new \RuntimeException('Could not switch to home directory "'.$home.'"', 0, $e); } $this->getIO()->writeError('Changed current directory to '.$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; } } * 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\Factory; use Composer\IO\IOInterface; use Composer\IO\NullIO; use Composer\Plugin\PreCommandRunEvent; use Composer\Plugin\PluginEvents; 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|null */ 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) { // initialize a plugin-enabled Composer instance, either local or global $disablePlugins = $input->hasParameterOption('--no-plugins'); $composer = $this->getComposer(false, $disablePlugins); if (null === $composer) { $composer = Factory::createGlobal($this->getIO(), $disablePlugins); } if ($composer) { $preCommandRunEvent = new PreCommandRunEvent(PluginEvents::PRE_COMMAND_RUN, $input, $this->getName()); $composer->getEventDispatcher()->dispatch($preCommandRunEvent->getName(), $preCommandRunEvent); } 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); } } * 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; /** * @throws \Symfony\Component\Console\Exception\InvalidArgumentException */ protected function configure() { $this ->setName('status') ->setDescription('Shows a list of locally modified packages, for packages installed from source.') ->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); } } * 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') ->setAliases(array('run')) ->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 Read more at https://getcomposer.org/doc/03-cli.md#run-script 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) { $description = ''; try { $cmd = $this->getApplication()->find($name); if ($cmd instanceof ScriptAliasCommand) { $description = $cmd->getDescription(); } } catch (\Symfony\Component\Console\Exception\CommandNotFoundException $e) { // ignore scripts that have no command associated, like native Composer script listeners } $table[] = array(' '.$name, $description); } $renderer = new Table($output); $renderer->setStyle('compact'); $rendererStyle = $renderer->getStyle(); $rendererStyle->setVerticalBorderChar(''); $rendererStyle->setCellRowContentFormat('%s '); $renderer->setRows($table)->render(); return 0; } } * 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. Read more at https://getcomposer.org/doc/03-cli.md#create-project 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('no-progress'), $input->getOption('no-install'), $input->getOption('ignore-platform-reqs'), !$input->getOption('no-secure-http') ); } 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, $noProgress = false, $noInstall = false, $ignorePlatformReqs = false, $secureHttp = true) { $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, $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')) ->setClassMapAuthoritative($config->get('classmap-authoritative')) ->setApcuAutoloader($config->get('apcu-autoloader')); if ($disablePlugins) { $installer->disablePlugins(); } $status = $installer->run(); if (0 !== $status) { return $status; } } $hasVcs = $installedFromVcs; if ( !$input->getOption('keep-vcs') && $installedFromVcs && ( $input->getOption('remove-vcs') || !$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, $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(); } $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(); } } * 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('u', '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. Read more at https://getcomposer.org/doc/03-cli.md#update-u 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.'); } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#search 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(), $input->hasParameterOption('--no-plugins')); } $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'] : '')); } return 0; } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#self-update-selfupdate- 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'); } return 0; } 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; } } * 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. Read more at https://getcomposer.org/doc/03-cli.md#suggests 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 0; } // 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(''); } } return 0; } } * 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; use Composer\Package\BasePackage; /** * @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 Read more at https://getcomposer.org/doc/03-cli.md#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]); } } } elseif (isset($composer[$type]) && $matches = preg_grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$type]))) { foreach ($matches as $matchedPackage) { $json->removeLink($type, $matchedPackage); } } elseif (isset($composer[$altType]) && $matches = preg_grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$altType]))) { foreach ($matches as $matchedPackage) { $io->writeError('' . $matchedPackage . ' 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, $matchedPackage); } } } } 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; } } * 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 Read more at https://getcomposer.org/doc/03-cli.md#run-script 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']); } } * 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\Repository\PlatformRepository; 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. Read more at https://getcomposer.org/doc/03-cli.md#diagnose 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://repo.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'); if (!is_array($rate)) { $this->outputResult($rate); } elseif (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'] )); } else { $this->outputResult(true); } } 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)); $platformOverrides = $config->get('platform') ?: array(); $platformRepo = new PlatformRepository(array(), $platformOverrides); $phpPkg = $platformRepo->findPackage('php', '*'); $phpVersion = $phpPkg->getPrettyVersion(); if (false !== strpos($phpPkg->getDescription(), 'overridden')) { $phpVersion .= ' - ' . $phpPkg->getDescription(); } $io->write(sprintf('PHP version: %s', $phpVersion)); 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) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $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 . '://repo.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() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $protocol = extension_loaded('openssl') ? 'https' : 'http'; try { $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://repo.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 . '://repo.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() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $url = 'http://repo.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() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } 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) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $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|string */ private function getGithubRateLimit($domain, $token = null) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } 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) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $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; $hadWarning = 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; } elseif (false !== strpos($message, '')) { $hadWarning = true; } } } if ($hadError) { $io->write('FAIL'); $this->exitCode = max($this->exitCode, 2); } elseif ($hadWarning) { $io->write('WARNING'); $this->exitCode = max($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 (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { $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') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { $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 (filter_var(ini_get('xdebug.profiler_enabled'), FILTER_VALIDATE_BOOLEAN)) { $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; } /** * Check if allow_url_fopen is ON * * @return bool|string */ private function checkConnectivity() { if (!ini_get('allow_url_fopen')) { $result = 'Skipped because allow_url_fopen is missing.'; return $result; } return true; } } * 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(); } * 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; /** * The pre command run event. * * @author Jordi Boggiano */ class PreCommandRunEvent extends Event { /** * @var InputInterface */ private $input; /** * @var string */ private $command; /** * Constructor. * * @param string $name The event name * @param InputInterface $input * @param string $command The command about to be executed */ public function __construct($name, InputInterface $input, $command) { parent::__construct($name); $this->input = $input; $this->command = $command; } /** * Returns the console input * * @return InputInterface */ public function getInput() { return $this->input; } /** * Returns the command about to be executed * * @return string */ public function getCommand() { return $this->command; } } * 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); } * 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; } } * 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'; /** * The PRE_COMMAND_RUN event occurs before a command is executed and lets you modify the input arguments/options * * The event listener method receives a * Composer\Plugin\PreCommandRunEvent instance. * * @var string */ const PRE_COMMAND_RUN = 'pre-command-run'; } * 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; } } * 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(); } * 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 { } * 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\CompletePackage; use Composer\Package\Package; use Composer\Package\Version\VersionParser; use Composer\Repository\RepositoryInterface; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Semver\Constraint\Constraint; use Composer\DependencyResolver\Pool; use Composer\Plugin\Capability\Capability; use Composer\Util\PackageSorter; /** * 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) { $packages = $repo->getPackages(); $sortedPackages = array_reverse(PackageSorter::sortPackages($packages)); foreach ($sortedPackages as $package) { if (!($package instanceof CompletePackage)) { 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; } } * 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), ))); // 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)); $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 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, $io); $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->writeError('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, '\\', '/'), '/'); } } * 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); } * 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 --nested', 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', ProcessExecutor::escape($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_'); } } * 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; } } * 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); } * 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(); } } * 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; use Composer\Cache; /** * @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 && git remote set-url origin %sanitizedUrl% && git remote set-url composer %sanitizedUrl%'; if ($gitVersion && version_compare($gitVersion, '2.3.0-rc0', '>=') && Cache::isUsable($cachePath)) { $this->io->writeError('', true, IOInterface::DEBUG); $this->io->writeError(sprintf(' Cloning to cache at %s', ProcessExecutor::escape($cachePath)), true, IOInterface::DEBUG); try { if (!$this->gitUtil->fetchRefOrSyncMirror($url, $cachePath, $ref)) { $this->io->writeError('Failed to update '.$url.' in cache, package installation for '.$package->getPrettyName().' might fail.'); } if (is_dir($cachePath)) { $command = 'git clone --no-checkout %cachePath% %path% --dissociate --reference %cachePath% ' . '&& cd '.$flag.'%path% ' . '&& git remote set-url origin %sanitizedUrl% && git remote add composer %sanitizedUrl%'; $msg = "Cloning ".$this->getShortHash($ref).' from cache'; } } catch (\RuntimeException $e) { if (0 === strpos(get_class($e), 'PHPUnit')) { throw $e; } } } $this->io->writeError($msg); $commandCallable = function ($url) use ($path, $command, $cachePath) { return str_replace( array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'), array( ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($cachePath), ProcessExecutor::escape(preg_replace('{://([^@]+?):(.+?)@}', '://', $url)), ), $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)) && git remote set-url composer %s'; $commandCallable = function ($url) use ($command, $ref) { return sprintf( $command, ProcessExecutor::escape($url), ProcessExecutor::escape($ref.'^{commit}'), ProcessExecutor::escape(preg_replace('{://([^@]+?):(.+?)@}', '://', $url)) ); }; $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"', ProcessExecutor::escape($fromReference), ProcessExecutor::escape($toReference)); if (0 !== $this->process->execute($command, $output, $path)) { throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()); } return $output; } /** * @param string $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 string $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 string $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; } } * 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'); } $util = new SvnUtil($url, $this->io, $this->config); $flags = ""; if (version_compare($util->binaryVersion(), '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', ProcessExecutor::escape($fromRevision), ProcessExecutor::escape($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'); } } * 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); } } * 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); } } * 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); } * 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} * @throws \RuntimeException * @throws \UnexpectedValueException */ 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); if ($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); } } * 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'; } } * 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); } * 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 (!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); } if (null === self::$isWindows) { self::$isWindows = Platform::isWindows(); if (!self::$isWindows && !self::$hasSystemUnzip) { $this->io->writeError("As there is no 'unzip' command installed zip files are being unpacked using the PHP zip extension."); $this->io->writeError("This may cause invalid reports of corrupted archives. Besides, any UNIX permissions (e.g. executable) defined in the archives will be lost."); $this->io->writeError("Installing 'unzip' may remediate them."); } } 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); } } } * 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 string $source path to source dir. * @param string $target 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 \SimpleXmlElement $package */ $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, '/'); } } * 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 */ } } * 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\IO\NullIO; use Composer\Package\Comparer\Comparer; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; 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, ChangeReportInterface { 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); $origin = RemoteFilesystem::getOrigin($processedUrl); $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); // use from cache if it is present and has a valid checksum or we have no checksum to check against if ($this->cache && (!$checksum || $checksum === $this->cache->sha1($cacheKey)) && $this->cache->copyTo($cacheKey, $fileName)) { $this->io->writeError('Loading from cache', false); } else { // download if cache restore failed if (!$this->outputProgress) { $this->io->writeError('Downloading', false); } // try to download 3 times then fail hard $retries = 3; while ($retries--) { try { $rfs->copy($origin, $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); } } 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->getFullPrettyVersion(); $to = $target->getFullPrettyVersion(); $actionName = VersionParser::isUpgrade($initial->getVersion(), $target->getVersion()) ? 'Updating' : 'Downgrading'; $this->io->writeError(" - " . $actionName . " " . $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(); } /** * {@inheritDoc} * @throws \RuntimeException */ public function getLocalChanges(PackageInterface $package, $targetDir) { $prevIO = $this->io; $prevProgress = $this->outputProgress; $this->io = new NullIO; $this->io->loadConfiguration($this->config); $this->outputProgress = false; $e = null; try { $this->download($package, $targetDir.'_compare', false); $comparer = new Comparer(); $comparer->setSource($targetDir.'_compare'); $comparer->setUpdate($targetDir); $comparer->doCompare(); $output = $comparer->getChanged(true, true); $this->filesystem->removeDirectory($targetDir.'_compare'); } catch (\Exception $e) { } $this->io = $prevIO; $this->outputProgress = $prevProgress; if ($e) { throw $e; } return trim($output); } } * 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(); } $actionName = VersionParser::isUpgrade($initial->getVersion(), $target->getVersion()) ? 'Updating' : 'Downgrading'; $this->io->writeError(" - " . $actionName . " " . $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); } * 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; use Composer\Util\Hg as HgUtils; /** * @author Per Bernhardt */ class HgDownloader extends VcsDownloader { /** * {@inheritDoc} */ public function doDownload(PackageInterface $package, $path, $url) { $hgUtils = new HgUtils($this->io, $this->config, $this->process); $cloneCommand = function ($url) use ($path) { return sprintf('hg clone %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path)); }; $hgUtils->runCommand($cloneCommand, $url, $path); $ref = ProcessExecutor::escape($package->getSourceReference()); $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) { $hgUtils = new HgUtils($this->io, $this->config, $this->process); $ref = $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 = function ($url) use ($ref) { return sprintf('hg pull %s && hg up %s', ProcessExecutor::escape($url), ProcessExecutor::escape($ref)); }; $hgUtils->runCommand($command, $url, $path); } /** * {@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', ProcessExecutor::escape($fromReference), ProcessExecutor::escape($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'); } } * 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); } } * 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); } /** * {@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; } } * 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); } } * 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 (realpath($path) === $realUrl) { if ($output) { $this->io->writeError(sprintf( ' - Installing %s (%s): Source already present', $package->getName(), $package->getFullPrettyVersion() )); } return; } 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); } // Check we can use junctions safely if we are on Windows if (Platform::isWindows() && self::STRATEGY_SYMLINK === $currentStrategy && !$this->safeJunctions()) { $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) { $realUrl = realpath($package->getDistUrl()); if (realpath($path) === $realUrl) { if ($output) { $this->io->writeError(" - Removing " . $package->getName() . " (" . $package->getFullPrettyVersion() . "), source is still present in $path"); } return; } /** * 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']; } } /** * Returns true if junctions can be created and safely used on Windows * * A PHP bug makes junction detection fragile, leading to possible data loss * when removing a package. See https://bugs.php.net/bug.php?id=77552 * * For safety we require a minimum version of Windows 7, so we can call the * system rmdir which will preserve target content if given a junction. * * The PHP bug was fixed in 7.2.16 and 7.3.3 (requires at least Windows 7). * * @return bool */ private function safeJunctions() { // We need to call mklink, and rmdir on Windows 7 (version 6.1) return function_exists('proc_open') && (PHP_WINDOWS_VERSION_MAJOR > 6 || (PHP_WINDOWS_VERSION_MAJOR === 6 && PHP_WINDOWS_VERSION_MINOR >= 1)); } } * 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; use Composer\Util\ProcessExecutor; /** * @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, 'use-github-api' => 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?://repo.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': // 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 'htaccess-protect': $value = $this->getComposerEnv('COMPOSER_HTACCESS_PROTECT'); if (false === $value) { $value = $this->config[$key]; } return $value !== 'false' && (bool) $value; 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 // no break case 'm': $size *= 1024; // intentional fallthrough // no break 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]; case 'use-github-api': 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; } } } /** * Used by long-running custom scripts in composer.json * * "scripts": { * "watch": [ * "Composer\\Config::disableProcessTimeout", * "vendor/bin/long-running-script --watch" * ] * } */ public static function disableProcessTimeout() { // Override global timeout set earlier by environment or config ProcessExecutor::setTimeout(0); } } * 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; } } * 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 */ public function __construct(IOInterface $io, Composer $composer) { 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); } } * 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'; } * 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; } } * 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); } * 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 ]; then case \$(which php) in \$(readlink -n /proc/cygdrive)/*) # We are in Cygwin using Windows php, so the path must be translated dir=\$(cygpath -m "\$dir"); ;; esac fi "\${dir}/$binFile" "\$@" PROXY; return $proxyCode; } } * 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); } * 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; } } } * 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; use Composer\Util\Platform; /** * 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) { if (!$repo->hasPackage($package)) { return false; } $installPath = $this->getInstallPath($package); if (is_readable($installPath)) { return true; } return (Platform::isWindows() && $this->filesystem->isJunction($installPath)) || is_link($installPath); } /** * {@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); } } * 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; } } * 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; use Composer\Package\Version\VersionParser; use Composer\IO\IOInterface; /** * Metapackage installation manager. * * @author Martin Hasoň */ class MetapackageInstaller implements InstallerInterface { private $io; public function __construct(IOInterface $io) { $this->io = $io; } /** * {@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) { $this->io->writeError(" - Installing " . $package->getName() . " (" . $package->getFullPrettyVersion() . ")"); $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); } $name = $target->getName(); $from = $initial->getFullPrettyVersion(); $to = $target->getFullPrettyVersion(); $actionName = VersionParser::isUpgrade($initial->getVersion(), $target->getVersion()) ? 'Updating' : 'Downgrading'; $this->io->writeError(" - " . $actionName . " " . $name . " (" . $from . " => " . $to . ")"); $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); } $this->io->writeError(" - Removing " . $package->getName() . " (" . $package->getFullPrettyVersion() . ")"); $repo->removePackage($package); } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { return ''; } } * 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 & ~umask()); file_put_contents($this->binDir.'/composer-php.bat', $this->generateWindowsPhpProxyCode()); @chmod($this->binDir.'/composer-php.bat', 0777 & ~umask()); } 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"; } } * 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); } } * 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 : ''); } } * 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'; } * 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'] ? ' ('.$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) ); } } * 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 { } * 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 $isVerbose; protected $isVeryVerbose; protected $io; protected $config; protected $versionParser; protected $type; protected $loader; protected $repoConfig; protected $branchErrorOccurred = false; private $drivers; /** @var VcsDriverInterface */ private $driver; /** @var VersionCacheInterface */ private $versionCache; private $emptyReferences = array(); public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $dispatcher = null, array $drivers = null, VersionCacheInterface $versionCache = 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->isVerbose = $io->isVerbose(); $this->isVeryVerbose = $io->isVeryVerbose(); $this->config = $config; $this->repoConfig = $repoConfig; $this->versionCache = $versionCache; } 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; } public function getEmptyReferences() { return $this->emptyReferences; } protected function initialize() { parent::initialize(); $isVerbose = $this->isVerbose; $isVeryVerbose = $this->isVeryVerbose; $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 ($isVeryVerbose) { $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 ($isVeryVerbose) { $this->io->writeError($msg); } elseif ($isVerbose) { $this->io->overwriteError($msg, false); } // strip the release- prefix from tags if present $tag = str_replace('release-', '', $tag); $cachedPackage = $this->getCachedPackageVersion($tag, $identifier, $isVerbose, $isVeryVerbose); if ($cachedPackage) { $this->addPackage($cachedPackage); continue; } elseif ($cachedPackage === false) { $this->emptyReferences[] = $identifier; continue; } if (!$parsedTag = $this->validateTag($tag)) { if ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', invalid tag name'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', no composer file'); } $this->emptyReferences[] = $identifier; 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 ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json'); } continue; } $tagPackageName = isset($data['name']) ? $data['name'] : $this->packageName; if ($existingPackage = $this->findPackage($tagPackageName, $data['version_normalized'])) { if ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', it conflicts with an another tag ('.$existingPackage->getPrettyVersion().') as both resolve to '.$data['version_normalized'].' internally'); } continue; } if ($isVeryVerbose) { $this->io->writeError('Importing tag '.$tag.' ('.$data['version_normalized'].')'); } $this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier))); } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 404) { $this->emptyReferences[] = $identifier; } if ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found' : $e->getMessage()).''); } continue; } } if (!$isVeryVerbose) { $this->io->overwriteError('', false); } $branches = $driver->getBranches(); foreach ($branches as $branch => $identifier) { $msg = 'Reading composer.json of ' . ($this->packageName ?: $this->url) . ' (' . $branch . ')'; if ($isVeryVerbose) { $this->io->writeError($msg); } elseif ($isVerbose) { $this->io->overwriteError($msg, false); } if ($branch === 'trunk' && isset($branches['master'])) { if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', can not parse both master and trunk branches as they both resolve to 9999999-dev internally'); } continue; } if (!$parsedBranch = $this->validateBranch($branch)) { if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', invalid name'); } continue; } // make sure branch packages have a dev flag if ('dev-' === substr($parsedBranch, 0, 4) || '9999999-dev' === $parsedBranch) { $version = 'dev-' . $branch; } else { $prefix = substr($branch, 0, 1) === 'v' ? 'v' : ''; $version = $prefix . preg_replace('{(\.9{7})+}', '.x', $parsedBranch); } $cachedPackage = $this->getCachedPackageVersion($version, $identifier, $isVerbose, $isVeryVerbose); if ($cachedPackage) { $this->addPackage($cachedPackage); continue; } elseif ($cachedPackage === false) { $this->emptyReferences[] = $identifier; continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file'); } $this->emptyReferences[] = $identifier; continue; } // branches are always auto-versioned, read value from branch name $data['version'] = $version; $data['version_normalized'] = $parsedBranch; if ($isVeryVerbose) { $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 ($e->getCode() === 404) { $this->emptyReferences[] = $identifier; } if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file was found'); } continue; } catch (\Exception $e) { if (!$isVeryVerbose) { $this->io->writeError(''); } $this->branchErrorOccurred = true; $this->io->writeError('Skipped branch '.$branch.', '.$e->getMessage().''); $this->io->writeError(''); continue; } } $driver->cleanup(); if (!$isVeryVerbose) { $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 $dataPackageName = isset($data['name']) ? $data['name'] : null; $data['name'] = $this->packageName ?: $dataPackageName; 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; } private function getCachedPackageVersion($version, $identifier, $isVerbose, $isVeryVerbose) { if (!$this->versionCache) { return; } $cachedPackage = $this->versionCache->getVersionPackage($version, $identifier); if ($cachedPackage === false) { if ($isVeryVerbose) { $this->io->writeError('Skipped '.$version.', no composer file (cached from ref '.$identifier.')'); } return false; } if ($cachedPackage) { $msg = 'Found cached composer.json of ' . ($this->packageName ?: $this->url) . ' (' . $version . ')'; if ($isVeryVerbose) { $this->io->writeError($msg); } elseif ($isVerbose) { $this->io->overwriteError($msg, false); } if ($existingPackage = $this->findPackage($cachedPackage['name'], $cachedPackage['version_normalized'])) { if ($isVeryVerbose) { $this->io->writeError('Skipped cached version '.$version.', it conflicts with an another tag ('.$existingPackage->getPrettyVersion().') as both resolve to '.$cachedPackage['version_normalized'].' internally'); } $cachedPackage = null; } } if ($cachedPackage) { return $this->loader->load($cachedPackage); } return null; } } * 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 { } * 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; use Composer\Util\Zip; /** * @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); } } private function getComposerInformation(\SplFileInfo $file) { $json = Zip::getComposerJson($file->getPathname()); if (null === $json) { return false; } $package = JsonFile::parseJson($json, $file->getPathname().'#composer.json'); $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; } } * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository; interface VersionCacheInterface { /** * @param string $version * @param string $identifier * @return array|null|false Package version data if found, false to indicate the identifier is known but has no package, null for an unknown identifier */ public function getVersionPackage($version, $identifier); } * 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(); } } * 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; } } } * 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$#i', $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'; } } * 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); } * 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|/?)$#i', $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); if ($composer) { // 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); } if (strpos($identifier, '/') !== false) { $branches = $this->getBranches(); if (isset($branches[$identifier])) { $identifier = $branches[$identifier]; } } $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s/src/%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); } if (strpos($identifier, '/') !== false) { $branches = $this->getBranches(); if (isset($branches[$identifier])) { $identifier = $branches[$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/2.0/repositories/%s/%s?fields=mainbranch', $this->owner, $this->repository ); $data = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource); if (isset($data['mainbranch'])) { return $data['mainbranch']; } return null; } } * 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 { if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) { throw new \RuntimeException('GitDriver requires a usable cache directory, and it looks like you set it to be disabled'); } $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; } } * 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/([^/]+)/([^/]+)/?$#i', $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; } } * 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} */ protected function shouldCache($identifier) { return $this->cache && preg_match('{@\d+$}', $identifier); } /** * {@inheritdoc} */ public function getComposerInformation($identifier) { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier.'.json')) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } try { $composer = $this->getBaseComposerInformation($identifier); } catch (TransportException $e) { $message = $e->getMessage(); if (stripos($message, 'path not found') === false && stripos($message, 'svn: warning: W160013') === false) { throw $e; } // remember a not-existent composer.json $composer = ''; } if ($this->shouldCache($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($io); $exit = $processExecutor->execute( "svn info --non-interactive ".ProcessExecutor::escape($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 (null === $this->util->binaryVersion()) { 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; } } * 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 bool true if the origin has a port number or a path component in it */ private $hasNonstandardOrigin = false; 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, $match['port']); if (false !== strpos($this->originUrl, ':') || false !== strpos($this->originUrl, '/')) { $this->hasNonstandardOrigin = true; } $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 cacheable 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() { return $this->scheme.'://'.$this->originUrl.'/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() { if ($this->hasNonstandardOrigin) { return 'ssh://git@'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository.'.git'; } 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, $match['port'])) { 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, $portNumber) { $guessedDomain = strtolower($guessedDomain); if (in_array($guessedDomain, $configuredDomains) || ($portNumber && in_array($guessedDomain.':'.$portNumber, $configuredDomains))) { if ($portNumber) { return $guessedDomain.':'.$portNumber; } return $guessedDomain; } if ($portNumber) { $guessedDomain .= ':'.$portNumber; } while (null !== ($part = array_shift($urlParts))) { $guessedDomain .= '/' . $part; if (in_array($guessedDomain, $configuredDomains) || ($portNumber && in_array(preg_replace('{:\d+}', '', $guessedDomain), $configuredDomains))) { return $guessedDomain; } } return false; } } * 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 = strtolower(!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 ( $this->config->get('use-github-api') === false || (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); } $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; } /** * {@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(strtolower(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() { if (false !== strpos($this->originUrl, ':')) { return 'ssh://git@' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git'; } 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 = $gitHubUtil->isRateLimited($e->getHeaders()); 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 = $gitHubUtil->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; } } } /** * 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]; } } } } } } * 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; } } * 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\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 { if (!Cache::isUsable($this->config->get('cache-repo-dir')) || !Cache::isUsable($this->config->get('cache-vcs-dir'))) { throw new \RuntimeException('FossilDriver requires a usable cache directory, and it looks like you set it to be disabled'); } $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 --nested', 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($io); // check whether there is a fossil repo in that path if ($process->execute('fossil info', $output, $url) === 0) { return true; } } return false; } } * 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\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; } if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) { throw new \RuntimeException('PerforceDriver requires a usable cache directory, and it looks like you set it to be disabled'); } $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; } } * 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\Util\Hg as HgUtils; 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 { if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) { throw new \RuntimeException('HgDriver requires a usable cache directory, and it looks like you set it to be disabled'); } $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); $hgUtils = new HgUtils($this->io, $this->config, $this->process); // 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); $repoDir = $this->repoDir; $command = function ($url) use ($repoDir) { return sprintf('hg clone --noupdate %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); }; $hgUtils->runCommand($command, $this->url, null); } } $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($io); // 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($io); $exit = $processExecutor->execute(sprintf('hg identify %s', ProcessExecutor::escape($url)), $ignored); return $exit === 0; } } * 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\Composer; 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']; // force url for packagist.org to repo.packagist.org if (preg_match('{^(?Phttps?)://packagist\.org/?$}i', $this->url, $match)) { $this->url = $match['proto'].'://repo.packagist.org'; } $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); $origin = RemoteFilesystem::getOrigin($url); $json = $this->rfs->getContents($origin, $url, false); $search = JsonFile::parseJson($json, $url); if (empty($search['results'])) { return array(); } $results = array(); foreach ($search['results'] as $result) { // do not show virtual packages in results as they are not directly useful from a composer perspective if (empty($result['virtual'])) { $results[] = $result; } } return $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?://repo\.packagist\.org/?$}i', $this->url) && !empty($this->repoConfig['force-lazy-providers'])) { $this->url = 'https://repo.packagist.org'; $this->baseUrl = 'https://repo.packagist.org'; $this->lazyProvidersUrl = $this->canonicalizeUrl('https://repo.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]) { if (preg_match('{^[^:]++://[^/]*+}', $this->url, $matches)) { return $matches[0] . $url; } return $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); } $origin = RemoteFilesystem::getOrigin($filename); $rfs = $preFileDownloadEvent->getRemoteFilesystem(); $json = $rfs->getContents($origin, $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); RemoteFilesystem::outputWarnings($this->io, $this->url, $data); 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); } $origin = RemoteFilesystem::getOrigin($filename); $rfs = $preFileDownloadEvent->getRemoteFilesystem(); $options = array('http' => array('header' => array('If-Modified-Since: '.$lastModifiedTime))); $json = $rfs->getContents($origin, $filename, false, $options); if ($json === '' && $rfs->findStatusCode($rfs->getLastHeaders()) === 304) { return true; } $data = JsonFile::parseJson($json, $filename); RemoteFilesystem::outputWarnings($this->io, $this->url, $data); $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; } } * 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(); // forward compatibility for composer v2 installed.json if (isset($packages['packages'])) { $packages = $packages['packages']; } 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); } } * 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 { } * 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\CompletePackage; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; use Composer\Plugin\PluginInterface; use Composer\Util\ProcessExecutor; use Composer\Util\Silencer; use Composer\Util\Platform; use Composer\XdebugHandler\XdebugHandler; use Symfony\Component\Process\ExecutableFinder; /** * @author Jordi Boggiano */ class PlatformRepository extends ArrayRepository { const PLATFORM_PACKAGE_REGEX = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[a-z0-9](?:[_.-]?[a-z0-9]+)*|composer-plugin-api)$}iD'; 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(); private $process; public function __construct(array $packages = array(), array $overrides = array(), ProcessExecutor $process = null) { $this->process = $process === null ? (new ProcessExecutor()) : $process; 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 = XdebugHandler::getSkippedVersion())) { $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 'imagick': $imagick = new \Imagick(); $imageMagickVersion = $imagick->getVersion(); // 6.x: ImageMagick 6.2.9 08/24/06 Q16 http://www.imagemagick.org // 7.x: ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org preg_match('/^ImageMagick ([\d.]+)(?:-(\d+))?/', $imageMagickVersion['versionString'], $matches); if (isset($matches[2])) { $prettyVersion = "{$matches[1]}.{$matches[2]}"; } else { $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); } $hhvmVersion = defined('HHVM_VERSION') ? HHVM_VERSION : null; if ($hhvmVersion === null && !Platform::isWindows()) { $finder = new ExecutableFinder(); $hhvm = $finder->find('hhvm'); if ($hhvm !== null) { $exitCode = $this->process->execute( ProcessExecutor::escape($hhvm). ' --php -d hhvm.jit=0 -r "echo HHVM_VERSION;" 2>/dev/null', $hhvmVersion ); if ($exitCode !== 0) { $hhvmVersion = null; } } } if ($hhvmVersion) { try { $prettyVersion = $hhvmVersion; $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', $hhvmVersion); $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(), '*'); if ($package->getVersion() === $overrider->getVersion()) { $actualText = 'same as actual'; } else { $actualText = 'actual: '.$package->getPrettyVersion(); } $overrider->setDescription($overrider->getDescription().' ('.$actualText.')'); 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()); if ($package->getVersion() === $overrider->getVersion()) { $actualText = 'same as actual'; } else { $actualText = 'actual: '.$package->getPrettyVersion(); } $overrider->setDescription($overrider->getDescription().' ('.$actualText.')'); 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); } } * 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(); } * 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_map('strtolower', (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(); // On forward search, check if any replaced package was required and add the replaced // packages to the list of needles. Contrary to the cross-reference link check below, // replaced packages are the target of links. foreach ($package->getReplaces() as $link) { foreach ($needles as $needle) { if ($link->getSource() === $needle) { if ($constraint === null || ($link->getConstraint()->matches($constraint) === !$invert)) { // already displayed this node's dependencies, cutting short if (in_array($link->getTarget(), $packagesInTree)) { $results[] = array($package, $link, false); continue; } $packagesInTree[] = $link->getTarget(); $dependents = $recurse ? $this->getDependents($link->getTarget(), null, false, true, $packagesInTree) : array(); $results[] = array($package, $link, $dependents); $needles[] = $link->getTarget(); } } } } } // 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[] = array($package, $link, false); continue; } $packagesInTree[] = $link->getSource(); $dependents = $recurse ? $this->getDependents($link->getSource(), null, false, true, $packagesInTree) : array(); $results[] = 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; } } * 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}"; } } * 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(); } * 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 { } * 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); } } } * 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) { /** @var RepositoryInterface $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 PackageInterface[] */ public function findPackages($name, $constraint) { $packages = array(); foreach ($this->getRepositories() 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 RepositoryInterface[] */ 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; } } * 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); if (is_array($versionData) && $versionData['pretty_version']) { $package['version'] = $versionData['pretty_version']; } else { $package['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() { $flags = GLOB_MARK | GLOB_ONLYDIR; if (defined('GLOB_BRACE')) { $flags |= GLOB_BRACE; } elseif (strpos($this->url, '{') !== false || strpos($this->url, '}') !== false) { throw new \RuntimeException('The operating system does not support GLOB_BRACE which is required for the url '. $this->url); } // 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, $flags)); } } * 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 array $depArray * @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 array $depArray 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 array $depArray 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 array $depItem dependency constraint or array of dependency constraints * @param string $depType 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 array $depItem dependency constraint or array of dependency constraints * @param string $depType 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 string $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); } } * 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 string $baseUrl base Url interface * * @return PackageInfo[] */ public function read($baseUrl) { return $this->readPackages($baseUrl); } /** * Read list of packages from * {baseUrl}/p/packages.xml * * @param string $baseUrl * @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 string $baseUrl * @param string $packageName * @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 string $baseUrl * @param string $packageName * @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 string $baseUrl * @param string $packageName * @param string $version * @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); } } * 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; } } * 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; } } * 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; } } * 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 string $origin server * @param string $path 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 string $origin server * @param string $path 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; } } * 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 string $baseUrl base Url interface * * @return PackageInfo[] */ public function read($baseUrl) { return $this->readChannelPackages($baseUrl); } /** * Read list of channel categories from * {baseUrl}/c/categories.xml * * @param string $baseUrl * @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 string $baseUrl * @param string $categoryName * @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 \SimpleXMLElement $packageInfo 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 ); } } * 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; } } * 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; } } * 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 string $url 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 \SimpleXMLElement $channelXml * @param string[] $supportedVersions 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; } } * 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 ($io) { $io->loadConfiguration($config); } 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; } } * 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; } } * 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); } * 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 { } * 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 { } * 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; = 50600 && !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\ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::getInitializer($loader)); } else { $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); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit5925cbfbda4231e100bd9070d8ec30d5::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire5925cbfbda4231e100bd9070d8ec30d5($fileIdentifier, $file); } return $loader; } } function composerRequire5925cbfbda4231e100bd9070d8ec30d5($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { require $file; $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } } array($vendorDir . '/cweagans/composer-patches/src'), 'WP_CLI\\Maintenance\\' => array($baseDir . '/utils/maintenance'), 'WP_CLI\\MaintenanceMode\\' => array($vendorDir . '/wp-cli/maintenance-mode-command/src'), 'WP_CLI\\I18n\\' => array($vendorDir . '/wp-cli/i18n-command/src'), 'WP_CLI\\Embeds\\' => array($vendorDir . '/wp-cli/embed-command/src'), 'WP_CLI\\' => array($vendorDir . '/wp-cli/entity-command/src/WP_CLI', $vendorDir . '/wp-cli/shell-command/src/WP_CLI'), 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), 'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'), 'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'), 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), 'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'), 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), 'Symfony\\Component\\DependencyInjection\\' => array($vendorDir . '/symfony/dependency-injection'), 'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'), 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), 'Symfony\\Component\\Config\\' => array($vendorDir . '/symfony/config'), 'Seld\\PharUtils\\' => array($vendorDir . '/seld/phar-utils/src'), 'Seld\\JsonLint\\' => array($vendorDir . '/seld/jsonlint/src/Seld/JsonLint'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), 'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src/Prophecy'), 'Peast\\test\\' => array($vendorDir . '/mck89/peast/test/Peast'), 'Peast\\' => array($vendorDir . '/mck89/peast/lib/Peast'), 'Mustangostang\\' => array($vendorDir . '/wp-cli/mustangostang-spyc/src'), 'JsonSchema\\' => array($vendorDir . '/justinrainbow/json-schema/src/JsonSchema'), 'JakubOnderka\\PhpConsoleHighlighter\\' => array($vendorDir . '/jakub-onderka/php-console-highlighter/src'), 'JakubOnderka\\PhpConsoleColor\\' => array($vendorDir . '/jakub-onderka/php-console-color/src'), 'Gettext\\Languages\\' => array($vendorDir . '/gettext/languages/src'), 'Gettext\\' => array($vendorDir . '/gettext/gettext/src'), 'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'), 'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'), 'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'), 'Composer\\CaBundle\\' => array($vendorDir . '/composer/ca-bundle/src'), 'Composer\\' => array($vendorDir . '/composer/composer/src/Composer'), '' => array($vendorDir . '/wp-cli/cache-command/src', $vendorDir . '/wp-cli/checksum-command/src', $vendorDir . '/wp-cli/config-command/src', $vendorDir . '/wp-cli/core-command/src', $vendorDir . '/wp-cli/cron-command/src', $vendorDir . '/wp-cli/db-command/src', $vendorDir . '/wp-cli/entity-command/src', $vendorDir . '/wp-cli/eval-command/src', $vendorDir . '/wp-cli/export-command/src', $vendorDir . '/wp-cli/extension-command/src', $vendorDir . '/wp-cli/import-command/src', $vendorDir . '/wp-cli/language-command/src', $vendorDir . '/wp-cli/media-command/src', $vendorDir . '/wp-cli/package-command/src', $vendorDir . '/wp-cli/rewrite-command/src', $vendorDir . '/wp-cli/role-command/src', $vendorDir . '/wp-cli/scaffold-command/src', $vendorDir . '/wp-cli/search-replace-command/src', $vendorDir . '/wp-cli/server-command/src', $vendorDir . '/wp-cli/shell-command/src', $vendorDir . '/wp-cli/super-admin-command/src', $vendorDir . '/wp-cli/widget-command/src'), ); * 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') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $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; } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Spdx; class SpdxLicenses { /** @var string */ const LICENSES_FILE = 'spdx-licenses.json'; /** @var string */ const EXCEPTIONS_FILE = 'spdx-exceptions.json'; /** * Contains all the licenses. * * The array is indexed by license identifiers, which contain * a numerically indexed array with license details. * * [ lowercased license identifier => * [ 0 => identifier (string), 1 => full name (string), 2 => osi certified (bool), 3 => deprecated (bool) ] * , ... * ] * * @var array */ private $licenses; /** * @var string */ private $licensesExpression; /** * Contains all the license exceptions. * * The array is indexed by license exception identifiers, which contain * a numerically indexed array with license exception details. * * [ lowercased exception identifier => * [ 0 => exception identifier (string), 1 => full name (string) ] * , ... * ] * * @var array */ private $exceptions; /** * @var string */ private $exceptionsExpression; public function __construct() { $this->loadLicenses(); $this->loadExceptions(); } /** * Returns license metadata by license identifier. * * This function adds a link to the full license text to the license metadata. * The array returned is in the form of: * * [ 0 => full name (string), 1 => osi certified, 2 => link to license text (string), 3 => deprecation status (bool) ] * * @param string $identifier * * @return array|null */ public function getLicenseByIdentifier($identifier) { $key = strtolower($identifier); if (!isset($this->licenses[$key])) { return; } list($identifier, $name, $isOsiApproved, $isDeprecatedLicenseId) = $this->licenses[$key]; return array( $name, $isOsiApproved, 'https://spdx.org/licenses/' . $identifier . '.html#licenseText', $isDeprecatedLicenseId, ); } /** * Returns all licenses information, keyed by the lowercased license identifier. * * @return array[] Each item is [ 0 => identifier (string), 1 => full name (string), 2 => osi certified (bool), 3 => deprecated (bool) ] */ public function getLicenses() { return $this->licenses; } /** * Returns license exception metadata by license exception identifier. * * This function adds a link to the full license exception text to the license exception metadata. * The array returned is in the form of: * * [ 0 => full name (string), 1 => link to license text (string) ] * * @param string $identifier * * @return array|null */ public function getExceptionByIdentifier($identifier) { $key = strtolower($identifier); if (!isset($this->exceptions[$key])) { return; } list($identifier, $name) = $this->exceptions[$key]; return array( $name, 'https://spdx.org/licenses/' . $identifier . '.html#licenseExceptionText', ); } /** * Returns the short identifier of a license (or license exception) by full name. * * @param string $name * * @return string|null */ public function getIdentifierByName($name) { foreach ($this->licenses as $licenseData) { if ($licenseData[1] === $name) { return $licenseData[0]; } } foreach ($this->exceptions as $licenseData) { if ($licenseData[1] === $name) { return $licenseData[0]; } } } /** * Returns the OSI Approved status for a license by identifier. * * @param string $identifier * * @return bool */ public function isOsiApprovedByIdentifier($identifier) { return $this->licenses[strtolower($identifier)][2]; } /** * Returns the deprecation status for a license by identifier. * * @param string $identifier * * @return bool */ public function isDeprecatedByIdentifier($identifier) { return $this->licenses[strtolower($identifier)][3]; } /** * @param array|string $license * * @throws \InvalidArgumentException * * @return bool */ public function validate($license) { if (is_array($license)) { $count = count($license); if ($count !== count(array_filter($license, 'is_string'))) { throw new \InvalidArgumentException('Array of strings expected.'); } $license = $count > 1 ? '(' . implode(' OR ', $license) . ')' : (string) reset($license); } if (!is_string($license)) { throw new \InvalidArgumentException(sprintf( 'Array or String expected, %s given.', gettype($license) )); } return $this->isValidLicenseString($license); } /** * @return string */ public static function getResourcesDir() { return dirname(__DIR__) . '/res'; } private function loadLicenses() { if (null !== $this->licenses) { return; } $json = file_get_contents(self::getResourcesDir() . '/' . self::LICENSES_FILE); $this->licenses = array(); foreach (json_decode($json, true) as $identifier => $license) { $this->licenses[strtolower($identifier)] = array($identifier, $license[0], $license[1], $license[2]); } } private function loadExceptions() { if (null !== $this->exceptions) { return; } $json = file_get_contents(self::getResourcesDir() . '/' . self::EXCEPTIONS_FILE); $this->exceptions = array(); foreach (json_decode($json, true) as $identifier => $exception) { $this->exceptions[strtolower($identifier)] = array($identifier, $exception[0]); } } /** * @return string */ private function getLicensesExpression() { if (null === $this->licensesExpression) { $licenses = array_map('preg_quote', array_keys($this->licenses)); rsort($licenses); $licenses = implode('|', $licenses); $this->licensesExpression = $licenses; } return $this->licensesExpression; } /** * @return string */ private function getExceptionsExpression() { if (null === $this->exceptionsExpression) { $exceptions = array_map('preg_quote', array_keys($this->exceptions)); rsort($exceptions); $exceptions = implode('|', $exceptions); $this->exceptionsExpression = $exceptions; } return $this->exceptionsExpression; } /** * @param string $license * * @throws \RuntimeException * * @return bool */ private function isValidLicenseString($license) { if (isset($this->licenses[strtolower($license)])) { return true; } $licenses = $this->getLicensesExpression(); $exceptions = $this->getExceptionsExpression(); $regex = <<[\pL\pN.-]{1,}) # license-id: taken from list (?${licenses}) # license-exception-id: taken from list (?${exceptions}) # license-ref: [DocumentRef-1*(idstring):]LicenseRef-1*(idstring) (?(?:DocumentRef-(?&idstring):)?LicenseRef-(?&idstring)) # simple-expresssion: license-id / license-id+ / license-ref (?(?&licenseid)\+? | (?&licenseid) | (?&licenseref)) # compound-expression: 1*( # simple-expression / # simple-expression WITH license-exception-id / # compound-expression AND compound-expression / # compound-expression OR compound-expression # ) / ( compound-expression ) ) (? (?&simple_expression) ( \s+ WITH \s+ (?&licenseexceptionid))? | \( \s* (?&compound_expression) \s* \) ) (? (?&compound_head) (?: \s+ (?:AND|OR) \s+ (?&compound_expression))? ) # license-expression: 1*1(simple-expression / compound-expression) (?(?&compound_expression) | (?&simple_expression)) ) # end of define ^(NONE | NOASSERTION | (?&license_expression))$ }xi REGEX; $match = preg_match($regex, $license); if (0 === $match) { return false; } if (false === $match) { throw new \RuntimeException('Regex failed to compile/run.'); } return true; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\CaBundle; use Psr\Log\LoggerInterface; use Symfony\Component\Process\PhpProcess; /** * @author Chris Smith * @author Jordi Boggiano */ class CaBundle { private static $caPath; private static $caFileValidity = array(); private static $useOpensslParse; /** * Returns the system CA bundle path, or a path to the bundled one * * 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. * * @param LoggerInterface $logger optional logger for information about which CA files were loaded * @return string path to a CA bundle file or directory */ public static function getSystemCaRootBundlePath(LoggerInterface $logger = null) { if (self::$caPath !== null) { return self::$caPath; } $caBundlePaths = array(); // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable. $caBundlePaths[] = getenv('SSL_CERT_FILE'); // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable. $caBundlePaths[] = getenv('SSL_CERT_DIR'); $caBundlePaths[] = ini_get('openssl.cafile'); $caBundlePaths[] = ini_get('openssl.capath'); $otherLocations = array( '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package) '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package) '/usr/local/share/certs/ca-root-nss.crt', // FreeBSD (ca_root_nss_package) '/usr/ssl/certs/ca-bundle.crt', // Cygwin '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option) '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat? '/etc/ssl/cert.pem', // OpenBSD '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package ); foreach($otherLocations as $location) { $otherLocations[] = dirname($location); } $caBundlePaths = array_merge($caBundlePaths, $otherLocations); foreach ($caBundlePaths as $caBundle) { if (self::caFileUsable($caBundle, $logger)) { return self::$caPath = $caBundle; } if (self::caDirUsable($caBundle)) { return self::$caPath = $caBundle; } } return self::$caPath = static::getBundledCaBundlePath(); // Bundled CA file, last resort } /** * Returns the path to the bundled CA file * * In case you don't want to trust the user or the system, you can use this directly * * @return string path to a CA bundle file */ public static function getBundledCaBundlePath() { $caBundleFile = __DIR__.'/../res/cacert.pem'; // cURL does not understand 'phar://' paths // see https://github.com/composer/ca-bundle/issues/10 if (0 === strpos($caBundleFile, 'phar://')) { file_put_contents( $tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-'), file_get_contents($caBundleFile) ); register_shutdown_function(function() use ($tempCaBundleFile) { @unlink($tempCaBundleFile); }); $caBundleFile = $tempCaBundleFile; } return $caBundleFile; } /** * Validates a CA file using opensl_x509_parse only if it is safe to use * * @param string $filename * @param LoggerInterface $logger optional logger for information about which CA files were loaded * * @return bool */ public static function validateCaFile($filename, LoggerInterface $logger = null) { static $warned = false; if (isset(self::$caFileValidity[$filename])) { return self::$caFileValidity[$filename]; } $contents = file_get_contents($filename); // assume the CA is valid if php is vulnerable to // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html if (!static::isOpensslParseSafe()) { if (!$warned && $logger) { $logger->warning(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 )); $warned = true; } $isValid = !empty($contents); } else { $isValid = (bool) openssl_x509_parse($contents); } if ($logger) { $logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid')); } return self::$caFileValidity[$filename] = $isValid; } /** * 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() { if (null !== self::$useOpensslParse) { return self::$useOpensslParse; } if (PHP_VERSION_ID >= 50600) { return self::$useOpensslParse = true; } // Vulnerable: // PHP 5.3.0 - PHP 5.3.27 // PHP 5.4.0 - PHP 5.4.22 // PHP 5.5.0 - PHP 5.5.6 if ( (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328) || (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423) || (PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507) ) { // This version of PHP has the fix for CVE-2013-6420 applied. return self::$useOpensslParse = true; } if (defined('PHP_WINDOWS_VERSION_BUILD')) { // Windows is probably insecure in this case. return self::$useOpensslParse = false; } $compareDistroVersionPrefix = function ($prefix, $fixedVersion) { $regex = '{^'.preg_quote($prefix).'([0-9]+)$}'; if (preg_match($regex, PHP_VERSION, $m)) { return ((int) $m[1]) >= $fixedVersion; } return false; }; // Hard coded list of PHP distributions with the fix backported. if ( $compareDistroVersionPrefix('5.3.3-7+squeeze', 18) // Debian 6 (Squeeze) || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) // Debian 7 (Wheezy) || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9) // Ubuntu 12.04 (Precise) ) { return self::$useOpensslParse = true; } // Symfony Process component is missing so we assume it is unsafe at this point if (!class_exists('Symfony\Component\Process\PhpProcess')) { return self::$useOpensslParse = false; } // This is where things get crazy, because distros backport security // fixes the chances are on NIX systems the fix has been applied but // it's not possible to verify that from the PHP version. // // To verify exec a new PHP process and run the issue testcase with // known safe input that replicates the bug. // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415 // changes in https://github.com/php/php-src/commit/76a7fd893b7d6101300cc656058704a73254d593 $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJOTwpiM0prY21obGFXNHRWMlZ6ZEdaaGJHVnVNUkF3RGdZRFZRUUhEQWRMdzRQQ3RteHVNUlF3RWdZRFZRUUtEQXRUClpXdDBhVzl1UldsdWN6RWZNQjBHQTFVRUN3d1dUV0ZzYVdOcGIzVnpJRU5sY25RZ1UyVmpkR2x2YmpFaE1COEcKQTFVRUF3d1liV0ZzYVdOcGIzVnpMbk5sYTNScGIyNWxhVzV6TG1SbE1Tb3dLQVlKS29aSWh2Y05BUWtCRmh0egpkR1ZtWVc0dVpYTnpaWEpBYzJWcmRHbHZibVZwYm5NdVpHVXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCCkR3QXdnZ0VLQW9JQkFRRERBZjNobDdKWTBYY0ZuaXlFSnBTU0RxbjBPcUJyNlFQNjV1c0pQUnQvOFBhRG9xQnUKd0VZVC9OYSs2ZnNnUGpDMHVLOURaZ1dnMnRIV1dvYW5TYmxBTW96NVBINlorUzRTSFJaN2UyZERJalBqZGhqaAowbUxnMlVNTzV5cDBWNzk3R2dzOWxOdDZKUmZIODFNTjJvYlhXczROdHp0TE11RDZlZ3FwcjhkRGJyMzRhT3M4CnBrZHVpNVVhd1Raa3N5NXBMUEhxNWNNaEZHbTA2djY1Q0xvMFYyUGQ5K0tBb2tQclBjTjVLTEtlYno3bUxwazYKU01lRVhPS1A0aWRFcXh5UTdPN2ZCdUhNZWRzUWh1K3ByWTNzaTNCVXlLZlF0UDVDWm5YMmJwMHdLSHhYMTJEWAoxbmZGSXQ5RGJHdkhUY3lPdU4rblpMUEJtM3ZXeG50eUlJdlZBZ01CQUFHalFqQkFNQWtHQTFVZEV3UUNNQUF3CkVRWUpZSVpJQVliNFFnRUJCQVFEQWdlQU1Bc0dBMVVkRHdRRUF3SUZvREFUQmdOVkhTVUVEREFLQmdnckJnRUYKQlFjREFqQU5CZ2txaGtpRzl3MEJBUVVGQUFPQ0FRRUFHMGZaWVlDVGJkajFYWWMrMVNub2FQUit2SThDOENhRAo4KzBVWWhkbnlVNGdnYTBCQWNEclk5ZTk0ZUVBdTZacXljRjZGakxxWFhkQWJvcHBXb2NyNlQ2R0QxeDMzQ2tsClZBcnpHL0t4UW9oR0QySmVxa2hJTWxEb214SE83a2EzOStPYThpMnZXTFZ5alU4QVp2V01BcnVIYTRFRU55RzcKbFcyQWFnYUZLRkNyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K'; $script = <<<'EOT' error_reporting(-1); $info = openssl_x509_parse(base64_decode('%s')); var_dump(PHP_VERSION, $info['issuer']['emailAddress'], $info['validFrom_time_t']); EOT; $script = '<'."?php\n".sprintf($script, $cert); try { $process = new PhpProcess($script); $process->mustRun(); } catch (\Exception $e) { // In the case of any exceptions just accept it is not possible to // determine the safety of openssl_x509_parse and bail out. return self::$useOpensslParse = false; } $output = preg_split('{\r?\n}', trim($process->getOutput())); $errorOutput = trim($process->getErrorOutput()); if ( count($output) === 3 && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) && $output[1] === 'string(27) "stefan.esser@sektioneins.de"' && $output[2] === 'int(-1)' && preg_match('{openssl_x509_parse\(\): illegal (?:ASN1 data type for|length in) timestamp in - on line \d+}', $errorOutput) ) { // This PHP has the fix backported probably by a distro security team. return self::$useOpensslParse = true; } return self::$useOpensslParse = false; } /** * Resets the static caches */ public static function reset() { self::$caFileValidity = array(); self::$caPath = null; self::$useOpensslParse = null; } private static function caFileUsable($certFile, LoggerInterface $logger = null) { return $certFile && @is_file($certFile) && @is_readable($certFile) && static::validateCaFile($certFile, $logger); } private static function caDirUsable($certDir) { return $certDir && @is_dir($certDir) && @is_readable($certDir) && glob($certDir . '/*'); } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\XdebugHandler; use Psr\Log\LoggerInterface; /** * @author John Stevenson */ class XdebugHandler { const SUFFIX_ALLOW = '_ALLOW_XDEBUG'; const SUFFIX_INIS = '_ORIGINAL_INIS'; const RESTART_ID = 'internal'; const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS'; const DEBUG = 'XDEBUG_HANDLER_DEBUG'; /** @var string|null */ protected $tmpIni; private static $inRestart; private static $name; private static $skipped; private $cli; private $colorOption; private $debug; private $envAllowXdebug; private $envOriginalInis; private $loaded; private $persistent; private $script; /** @var Status|null */ private $statusWriter; /** * Constructor * * The $envPrefix is used to create distinct environment variables. It is * uppercased and prepended to the default base values. For example 'myapp' * would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS. * * @param string $envPrefix Value used in environment variables * @param string $colorOption Command-line long option to force color output * @throws \RuntimeException If a parameter is invalid */ public function __construct($envPrefix, $colorOption = '') { if (!is_string($envPrefix) || empty($envPrefix) || !is_string($colorOption)) { throw new \RuntimeException('Invalid constructor parameter'); } self::$name = strtoupper($envPrefix); $this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW; $this->envOriginalInis = self::$name.self::SUFFIX_INIS; $this->colorOption = $colorOption; if (extension_loaded('xdebug')) { $ext = new \ReflectionExtension('xdebug'); $this->loaded = $ext->getVersion() ?: 'unknown'; } if ($this->cli = PHP_SAPI === 'cli') { $this->debug = getenv(self::DEBUG); } $this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug); } /** * Activates status message output to a PSR3 logger * * @param LoggerInterface $logger * * @return $this */ public function setLogger(LoggerInterface $logger) { $this->statusWriter->setLogger($logger); return $this; } /** * Sets the main script location if it cannot be called from argv * * @param string $script * * @return $this */ public function setMainScript($script) { $this->script = $script; return $this; } /** * Persist the settings to keep Xdebug out of sub-processes * * @return $this */ public function setPersistent() { $this->persistent = true; return $this; } /** * Checks if Xdebug is loaded and the process needs to be restarted * * This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG * environment variable to 1. This variable is used internally so that * the restarted process is created only once. */ public function check() { $this->notify(Status::CHECK, $this->loaded); $envArgs = explode('|', (string) getenv($this->envAllowXdebug)); if (empty($envArgs[0]) && $this->requiresRestart((bool) $this->loaded)) { // Restart required $this->notify(Status::RESTART); if ($this->prepareRestart()) { $command = $this->getCommand(); $this->notify(Status::RESTARTING, $command); $this->restart($command); } return; } if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) { // Restarting, so unset environment variable and use saved values $this->notify(Status::RESTARTED); Process::setEnv($this->envAllowXdebug); self::$inRestart = true; if (!$this->loaded) { // Skipped version is only set if Xdebug is not loaded self::$skipped = $envArgs[1]; } // Put restart settings in the environment $this->setEnvRestartSettings($envArgs); return; } $this->notify(Status::NORESTART); if ($settings = self::getRestartSettings()) { // Called with existing settings, so sync our settings $this->syncSettings($settings); } } /** * 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 getAllIniFiles() { if (!empty(self::$name)) { $env = getenv(self::$name.self::SUFFIX_INIS); if (false !== $env) { return explode(PATH_SEPARATOR, $env); } } $paths = array((string) php_ini_loaded_file()); if ($scanned = php_ini_scanned_files()) { $paths = array_merge($paths, array_map('trim', explode(',', $scanned))); } return $paths; } /** * Returns an array of restart settings or null * * Settings will be available if the current process was restarted, or * called with the settings from an existing restart. * * @return array|null */ public static function getRestartSettings() { $envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS)); if (count($envArgs) !== 6 || (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) { return; } return array( 'tmpIni' => $envArgs[0], 'scannedInis' => (bool) $envArgs[1], 'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2], 'phprc' => '*' === $envArgs[3] ? false : $envArgs[3], 'inis' => explode(PATH_SEPARATOR, $envArgs[4]), 'skipped' => $envArgs[5], ); } /** * Returns the Xdebug version that triggered a successful restart * * @return string */ public static function getSkippedVersion() { return (string) self::$skipped; } /** * Returns true if Xdebug is loaded, or as directed by an extending class * * @param bool $isLoaded Whether Xdebug is loaded * * @return bool */ protected function requiresRestart($isLoaded) { return $isLoaded; } /** * Allows an extending class to access the tmpIni * * @param string $command */ protected function restart($command) { $this->doRestart($command); } /** * Executes the restarted command then deletes the tmp ini * * @param string $command */ private function doRestart($command) { passthru($command, $exitCode); $this->notify(Status::INFO, 'Restarted process exited '.$exitCode); if ($this->debug === '2') { $this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni); } else { @unlink($this->tmpIni); } exit($exitCode); } /** * 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() { $error = ''; $iniFiles = self::getAllIniFiles(); $scannedInis = count($iniFiles) > 1; $tmpDir = sys_get_temp_dir(); if (!$this->cli) { $error = 'Unsupported SAPI: '.PHP_SAPI; } elseif (!defined('PHP_BINARY')) { $error = 'PHP version is too old: '.PHP_VERSION; } elseif (!$this->checkConfiguration($info)) { $error = $info; } elseif (!$this->checkScanDirConfig()) { $error = 'PHP version does not report scanned inis: '.PHP_VERSION; } elseif (!$this->checkMainScript()) { $error = 'Unable to access main script: '.$this->script; } elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) { $error = $error ?: 'Unable to create temp ini file at: '.$tmpDir; } elseif (!$this->setEnvironment($scannedInis, $iniFiles)) { $error = 'Unable to set environment variables'; } if ($error) { $this->notify(Status::ERROR, $error); } return empty($error); } /** * Returns true if the tmp ini file was written * * @param array $iniFiles All ini files used in the current process * @param string $tmpDir The system temporary directory * @param string $error Set by method if ini file cannot be read * * @return bool */ private function writeTmpIni(array $iniFiles, $tmpDir, &$error) { if (!$this->tmpIni = @tempnam($tmpDir, '')) { return false; } // $iniFiles has at least one item and it may be empty if (empty($iniFiles[0])) { array_shift($iniFiles); } $content = ''; $regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi'; foreach ($iniFiles as $file) { // Check for inaccessible ini files if (!$data = @file_get_contents($file)) { $error = 'Unable to read ini: '.$file; return false; } $content .= preg_replace($regex, ';$1', $data).PHP_EOL; } // Merge loaded settings into our ini content, if it is valid if ($config = parse_ini_string($content)) { $loaded = ini_get_all(null, false); $content .= $this->mergeLoadedConfig($loaded, $config); } // Work-around for https://bugs.php.net/bug.php?id=75932 $content .= 'opcache.enable_cli=0'.PHP_EOL; return @file_put_contents($this->tmpIni, $content); } /** * Returns the restart command line * * @return string */ private function getCommand() { $php = array(PHP_BINARY); $args = array_slice($_SERVER['argv'], 1); if (!$this->persistent) { // Use command-line options array_push($php, '-n', '-c', $this->tmpIni); } if (defined('STDOUT') && Process::supportsColor(STDOUT)) { $args = Process::addColorOption($args, $this->colorOption); } $args = array_merge($php, array($this->script), $args); $cmd = Process::escape(array_shift($args), true, true); foreach ($args as $arg) { $cmd .= ' '.Process::escape($arg); } return $cmd; } /** * Returns true if the restart environment variables were set * * No need to update $_SERVER since this is set in the restarted process. * * @param bool $scannedInis Whether there were scanned ini files * @param array $iniFiles All ini files used in the current process * * @return bool */ private function setEnvironment($scannedInis, array $iniFiles) { $scanDir = getenv('PHP_INI_SCAN_DIR'); $phprc = getenv('PHPRC'); // Make original inis available to restarted process if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) { return false; } if ($this->persistent) { // Use the environment to persist the settings if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$this->tmpIni)) { return false; } } // Flag restarted process and save values for it to use $envArgs = array( self::RESTART_ID, $this->loaded, (int) $scannedInis, false === $scanDir ? '*' : $scanDir, false === $phprc ? '*' : $phprc, ); return putenv($this->envAllowXdebug.'='.implode('|', $envArgs)); } /** * Logs status messages * * @param string $op Status handler constant * @param null|string $data Optional data */ private function notify($op, $data = null) { $this->statusWriter->report($op, $data); } /** * Returns default, changed and command-line ini settings * * @param array $loadedConfig All current ini settings * @param array $iniConfig Settings from user ini files * * @return string */ private function mergeLoadedConfig(array $loadedConfig, array $iniConfig) { $content = ''; foreach ($loadedConfig as $name => $value) { // Value will either be null, string or array (HHVM only) if (!is_string($value) || strpos($name, 'xdebug') === 0 || $name === 'apc.mmap_file_mask') { continue; } if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { // Double-quote escape each value $content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL; } } return $content; } /** * Returns true if the script name can be used * * @return bool */ private function checkMainScript() { if (null !== $this->script) { // Allow an application to set -- for standard input return file_exists($this->script) || '--' === $this->script; } if (file_exists($this->script = $_SERVER['argv'][0])) { return true; } // Use a backtrace to resolve Phar and chdir issues $options = PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS : false; $trace = debug_backtrace($options); if (($main = end($trace)) && isset($main['file'])) { return file_exists($this->script = $main['file']); } return false; } /** * Adds restart settings to the environment * * @param string $envArgs */ private function setEnvRestartSettings($envArgs) { $settings = array( php_ini_loaded_file(), $envArgs[2], $envArgs[3], $envArgs[4], getenv($this->envOriginalInis), self::$skipped, ); Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings)); } /** * Syncs settings and the environment if called with existing settings * * @param array $settings */ private function syncSettings(array $settings) { if (false === getenv($this->envOriginalInis)) { // Called by another app, so make original inis available Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis'])); } self::$skipped = $settings['skipped']; $this->notify(Status::INFO, 'Process called with existing restart settings'); } /** * Returns true if there are scanned inis and PHP is able to report them * * php_ini_scanned_files will fail when PHP_CONFIG_FILE_SCAN_DIR is empty. * Fixed in 7.1.13 and 7.2.1 * * @return bool */ private function checkScanDirConfig() { return !(getenv('PHP_INI_SCAN_DIR') && !PHP_CONFIG_FILE_SCAN_DIR && (PHP_VERSION_ID < 70113 || PHP_VERSION_ID === 70200)); } /** * Returns true if there are no known configuration issues * * @param string $info Set by method */ private function checkConfiguration(&$info) { if (false !== strpos(ini_get('disable_functions'), 'passthru')) { $info = 'passthru function is disabled'; return false; } if (extension_loaded('uopz') && !ini_get('uopz.disable')) { // uopz works at opcode level and disables exit calls if (function_exists('uopz_allow_exit')) { @uopz_allow_exit(true); } else { $info = 'uopz extension is not compatible'; return false; } } return true; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\XdebugHandler; /** * @author John Stevenson */ class PhpConfig { /** * Use the original PHP configuration * * @return array PHP cli options */ public function useOriginal() { $this->getDataAndReset(); return array(); } /** * Use standard restart settings * * @return array PHP cli options */ public function useStandard() { if ($data = $this->getDataAndReset()) { return array('-n', '-c', $data['tmpIni']); } return array(); } /** * Use environment variables to persist settings * * @return array PHP cli options */ public function usePersistent() { if ($data = $this->getDataAndReset()) { Process::setEnv('PHPRC', $data['tmpIni']); Process::setEnv('PHP_INI_SCAN_DIR', ''); } return array(); } /** * Returns restart data if available and resets the environment * * @return array|null */ private function getDataAndReset() { if ($data = XdebugHandler::getRestartSettings()) { Process::setEnv('PHPRC', $data['phprc']); Process::setEnv('PHP_INI_SCAN_DIR', $data['scanDir']); } return $data; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\XdebugHandler; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; /** * @author John Stevenson * @internal */ class Status { const ENV_RESTART = 'XDEBUG_HANDLER_RESTART'; const CHECK = 'Check'; const ERROR = 'Error'; const INFO = 'Info'; const NORESTART = 'NoRestart'; const RESTART = 'Restart'; const RESTARTING = 'Restarting'; const RESTARTED = 'Restarted'; private $debug; private $envAllowXdebug; private $loaded; private $logger; private $time; /** * Constructor * * @param string $envAllowXdebug Prefixed _ALLOW_XDEBUG name * @param bool $debug Whether debug output is required */ public function __construct($envAllowXdebug, $debug) { $start = getenv(self::ENV_RESTART); Process::setEnv(self::ENV_RESTART); $this->time = $start ? round((microtime(true) - $start) * 1000) : 0; $this->envAllowXdebug = $envAllowXdebug; $this->debug = $debug && defined('STDERR'); } /** * @param LoggerInterface $logger */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; } /** * Calls a handler method to report a message * * @param string $op The handler constant * @param null|string $data Data required by the handler */ public function report($op, $data) { if ($this->logger || $this->debug) { call_user_func(array($this, 'report'.$op), $data); } } /** * Outputs a status message * * @param string $text * @param string $level */ private function output($text, $level = null) { if ($this->logger) { $this->logger->log($level ?: LogLevel::DEBUG, $text); } if ($this->debug) { fwrite(STDERR, sprintf('xdebug-handler[%d] %s', getmypid(), $text.PHP_EOL)); } } private function reportCheck($loaded) { $this->loaded = $loaded; $this->output('Checking '.$this->envAllowXdebug); } private function reportError($error) { $this->output(sprintf('No restart (%s)', $error), LogLevel::WARNING); } private function reportInfo($info) { $this->output($info); } private function reportNoRestart() { $this->output($this->getLoadedMessage()); if ($this->loaded) { $text = sprintf('No restart (%s)', $this->getEnvAllow()); if (!getenv($this->envAllowXdebug)) { $text .= ' Allowed by application'; } $this->output($text); } } private function reportRestart() { $this->output($this->getLoadedMessage()); Process::setEnv(self::ENV_RESTART, (string) microtime(true)); } private function reportRestarted() { $loaded = $this->getLoadedMessage(); $text = sprintf('Restarted (%d ms). %s', $this->time, $loaded); $level = $this->loaded ? LogLevel::WARNING : null; $this->output($text, $level); } private function reportRestarting($command) { $text = sprintf('Process restarting (%s)', $this->getEnvAllow()); $this->output($text); $text = 'Running '.$command; $this->output($text); } /** * Returns the _ALLOW_XDEBUG environment variable as name=value * * @return string */ private function getEnvAllow() { return $this->envAllowXdebug.'='.getenv($this->envAllowXdebug); } /** * Returns the Xdebug status and version * * @return string */ private function getLoadedMessage() { $loaded = $this->loaded ? sprintf('loaded (%s)', $this->loaded) : 'not loaded'; return 'The Xdebug extension is '.$loaded; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\XdebugHandler; /** * Provides utility functions to prepare a child process command-line and set * environment variables in that process. * * @author John Stevenson * @internal */ class Process { /** * Returns an array of parameters, including a color option if required * * A color option is needed because child process output is piped. * * @param array $args The script parameters * @param string $colorOption The long option to force color output * * @return array */ public static function addColorOption(array $args, $colorOption) { if (!$colorOption || in_array($colorOption, $args) || !preg_match('/^--([a-z]+$)|(^--[a-z]+=)/', $colorOption, $matches)) { return $args; } if (isset($matches[2])) { // Handle --color(s)= options if (false !== ($index = array_search($matches[2].'auto', $args))) { $args[$index] = $colorOption; return $args; } elseif (preg_grep('/^'.$matches[2].'/', $args)) { return $args; } } elseif (in_array('--no-'.$matches[1], $args)) { return $args; } // Check for NO_COLOR variable (https://no-color.org/) if (false !== getenv('NO_COLOR')) { return $args; } if (false !== ($index = array_search('--', $args))) { // Position option before double-dash delimiter array_splice($args, $index, 0, $colorOption); } else { $args[] = $colorOption; } 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 * @param bool $module The argument is the module to invoke * * @return string The escaped argument */ public static function escape($arg, $meta = true, $module = false) { if (!defined('PHP_WINDOWS_VERSION_BUILD')) { return "'".str_replace("'", "'\\''", $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; } elseif ($module && !$dquotes && $quote) { $meta = false; } } if ($quote) { $arg = '"'.preg_replace('/(\\\\*)$/', '$1$1', $arg).'"'; } if ($meta) { $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg); } return $arg; } /** * Returns true if the output stream supports colors * * This is tricky on Windows, because Cygwin, Msys2 etc emulate pseudo * terminals via named pipes, so we can only check the environment. * * @param mixed $output A valid CLI output stream * * @return bool */ public static function supportsColor($output) { if ('Hyper' === getenv('TERM_PROGRAM')) { return true; } if (defined('PHP_WINDOWS_VERSION_BUILD')) { return (function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support($output)) || false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM'); } if (function_exists('stream_isatty')) { return stream_isatty($output); } if (function_exists('posix_isatty')) { return posix_isatty($output); } $stat = fstat($output); // Check if formatted mode is S_IFCHR return $stat ? 0020000 === ($stat['mode'] & 0170000) : false; } /** * Makes putenv environment changes available in $_SERVER and $_ENV * * @param string $name * @param string|false $value A false value unsets the variable * * @return bool Whether the environment variable was set */ public static function setEnv($name, $value = false) { $unset = false === $value; if (!putenv($unset ? $name : $name.'='.$value)) { return false; } if ($unset) { unset($_SERVER[$name]); } else { $_SERVER[$name] = $value; } // Update $_ENV if it is being used if (false !== stripos((string) ini_get('variables_order'), 'E')) { if ($unset) { unset($_ENV[$name]); } else { $_ENV[$name] = $value; } } return true; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\EmptyConstraint; use Composer\Semver\Constraint\MultiConstraint; use Composer\Semver\Constraint\Constraint; /** * Version parser. * * @author Jordi Boggiano */ class VersionParser { /** * Regex to match pre-release data (sort of). * * Due to backwards compatibility: * - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted. * - Only stabilities as recognized by Composer are allowed to precede a numerical identifier. * - Numerical-only pre-release identifiers are not supported, see tests. * * |--------------| * [major].[minor].[patch] -[pre-release] +[build-metadata] * * @var string */ private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?'; /** @var array */ private static $stabilities = array('stable', 'RC', 'beta', 'alpha', 'dev'); /** * Returns the stability of a version. * * @param string $version * * @return string */ public static function parseStability($version) { $version = preg_replace('{#.+$}i', '', $version); if ('dev-' === substr($version, 0, 4) || '-dev' === substr($version, -4)) { return 'dev'; } preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match); if (!empty($match[3])) { return 'dev'; } if (!empty($match[1])) { if ('beta' === $match[1] || 'b' === $match[1]) { return 'beta'; } if ('alpha' === $match[1] || 'a' === $match[1]) { return 'alpha'; } if ('rc' === $match[1]) { return 'RC'; } } return 'stable'; } /** * @param string $stability * * @return string */ public static function normalizeStability($stability) { $stability = strtolower($stability); return $stability === 'rc' ? 'RC' : $stability; } /** * Normalizes a version string to be able to perform comparisons on it. * * @param string $version * @param string $fullVersion optional complete version string to give more context * * @throws \UnexpectedValueException * * @return string */ public function normalize($version, $fullVersion = null) { $version = trim($version); if (null === $fullVersion) { $fullVersion = $version; } // strip off aliasing if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) { $version = $match[1]; } // match master-like branches if (preg_match('{^(?:dev-)?(?:master|trunk|default)$}i', $version)) { return '9999999-dev'; } // if requirement is branch-like, use full name if ('dev-' === strtolower(substr($version, 0, 4))) { return 'dev-' . substr($version, 4); } // strip off build metadata if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) { $version = $match[1]; } // match classical versioning if (preg_match('{^v?(\d{1,5})(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) { $version = $matches[1] . (!empty($matches[2]) ? $matches[2] : '.0') . (!empty($matches[3]) ? $matches[3] : '.0') . (!empty($matches[4]) ? $matches[4] : '.0'); $index = 5; // match date(time) based versioning } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) { $version = preg_replace('{\D}', '.', $matches[1]); $index = 2; } // add version modifiers if a version was matched if (isset($index)) { if (!empty($matches[$index])) { if ('stable' === $matches[$index]) { return $version; } $version .= '-' . $this->expandStability($matches[$index]) . (!empty($matches[$index + 1]) ? ltrim($matches[$index + 1], '.-') : ''); } if (!empty($matches[$index + 2])) { $version .= '-dev'; } return $version; } // match dev branches if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) { try { return $this->normalizeBranch($match[1]); } catch (\Exception $e) { } } $extraMessage = ''; if (preg_match('{ +as +' . preg_quote($version) . '$}', $fullVersion)) { $extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version'; } elseif (preg_match('{^' . preg_quote($version) . ' +as +}', $fullVersion)) { $extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-'; } throw new \UnexpectedValueException('Invalid version string "' . $version . '"' . $extraMessage); } /** * Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison. * * @param string $branch Branch name (e.g. 2.1.x-dev) * * @return string|false Numeric prefix if present (e.g. 2.1.) or false */ public function parseNumericAliasPrefix($branch) { if (preg_match('{^(?P(\d++\\.)*\d++)(?:\.x)?-dev$}i', $branch, $matches)) { return $matches['version'] . '.'; } return false; } /** * Normalizes a branch name to be able to perform comparisons on it. * * @param string $name * * @return string */ public function normalizeBranch($name) { $name = trim($name); if (in_array($name, array('master', 'trunk', 'default'))) { return $this->normalize($name); } if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) { $version = ''; for ($i = 1; $i < 5; ++$i) { $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x'; } return str_replace('x', '9999999', $version) . '-dev'; } return 'dev-' . $name; } /** * Parses a constraint string into MultiConstraint and/or Constraint objects. * * @param string $constraints * * @return ConstraintInterface */ public function parseConstraints($constraints) { $prettyConstraint = $constraints; if (preg_match('{^([^,\s]*?)@(' . implode('|', self::$stabilities) . ')$}i', $constraints, $match)) { $constraints = empty($match[1]) ? '*' : $match[1]; } if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) { $constraints = $match[1]; } $orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints)); $orGroups = array(); foreach ($orConstraints as $constraints) { $andConstraints = preg_split('{(?< ,]) *(? 1) { $constraintObjects = array(); foreach ($andConstraints as $constraint) { foreach ($this->parseConstraint($constraint) as $parsedConstraint) { $constraintObjects[] = $parsedConstraint; } } } else { $constraintObjects = $this->parseConstraint($andConstraints[0]); } if (1 === count($constraintObjects)) { $constraint = $constraintObjects[0]; } else { $constraint = new MultiConstraint($constraintObjects); } $orGroups[] = $constraint; } if (1 === count($orGroups)) { $constraint = $orGroups[0]; } elseif (2 === count($orGroups) // parse the two OR groups and if they are contiguous we collapse // them into one constraint && $orGroups[0] instanceof MultiConstraint && $orGroups[1] instanceof MultiConstraint && 2 === count($orGroups[0]->getConstraints()) && 2 === count($orGroups[1]->getConstraints()) && ($a = (string) $orGroups[0]) && substr($a, 0, 3) === '[>=' && (false !== ($posA = strpos($a, '<', 4))) && ($b = (string) $orGroups[1]) && substr($b, 0, 3) === '[>=' && (false !== ($posB = strpos($b, '<', 4))) && substr($a, $posA + 2, -1) === substr($b, 4, $posB - 5) ) { $constraint = new MultiConstraint(array( new Constraint('>=', substr($a, 4, $posA - 5)), new Constraint('<', substr($b, $posB + 2, -1)), )); } else { $constraint = new MultiConstraint($orGroups, false); } $constraint->setPrettyString($prettyConstraint); return $constraint; } /** * @param string $constraint * * @throws \UnexpectedValueException * * @return array */ private function parseConstraint($constraint) { if (preg_match('{^([^,\s]+?)@(' . implode('|', self::$stabilities) . ')$}i', $constraint, $match)) { $constraint = $match[1]; if ($match[2] !== 'stable') { $stabilityModifier = $match[2]; } } if (preg_match('{^v?[xX*](\.[xX*])*$}i', $constraint)) { return array(new EmptyConstraint()); } $versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?' . self::$modifierRegex . '(?:\+[^\s]+)?'; // Tilde Range // // Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous // version, to ensure that unstable instances of the current version are allowed. However, if a stability // suffix is added to the constraint, then a >= match on the current version is used instead. if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) { if (substr($constraint, 0, 2) === '~>') { throw new \UnexpectedValueException( 'Could not parse version constraint ' . $constraint . ': ' . 'Invalid operator "~>", you probably meant to use the "~" operator' ); } // Work out which position in the version we are operating at if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) { $position = 4; } elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { $position = 3; } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { $position = 2; } else { $position = 1; } // Calculate the stability suffix $stabilitySuffix = ''; if (empty($matches[5]) && empty($matches[7])) { $stabilitySuffix .= '-dev'; } $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); $lowerBound = new Constraint('>=', $lowVersion); // For upper bound, we increment the position of one more significance, // but highPosition = 0 would be illegal $highPosition = max(1, $position - 1); $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev'; $upperBound = new Constraint('<', $highVersion); return array( $lowerBound, $upperBound, ); } // Caret Range // // Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. // In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for // versions 0.X >=0.1.0, and no updates for versions 0.0.X if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) { // Work out which position in the version we are operating at if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) { $position = 1; } elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) { $position = 2; } else { $position = 3; } // Calculate the stability suffix $stabilitySuffix = ''; if (empty($matches[5]) && empty($matches[7])) { $stabilitySuffix .= '-dev'; } $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); $lowerBound = new Constraint('>=', $lowVersion); // For upper bound, we increment the position of one more significance, // but highPosition = 0 would be illegal $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; $upperBound = new Constraint('<', $highVersion); return array( $lowerBound, $upperBound, ); } // X Range // // Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple. // A partial version range is treated as an X-Range, so the special character is in fact optional. if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) { if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { $position = 3; } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { $position = 2; } else { $position = 1; } $lowVersion = $this->manipulateVersionString($matches, $position) . '-dev'; $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; if ($lowVersion === '0.0.0.0-dev') { return array(new Constraint('<', $highVersion)); } return array( new Constraint('>=', $lowVersion), new Constraint('<', $highVersion), ); } // Hyphen Range // // Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range, // then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in // the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but // nothing that would be greater than the provided tuple parts. if (preg_match('{^(?P' . $versionRegex . ') +- +(?P' . $versionRegex . ')($)}i', $constraint, $matches)) { // Calculate the stability suffix $lowStabilitySuffix = ''; if (empty($matches[6]) && empty($matches[8])) { $lowStabilitySuffix = '-dev'; } $lowVersion = $this->normalize($matches['from']); $lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix); $empty = function ($x) { return ($x === 0 || $x === '0') ? false : empty($x); }; if ((!$empty($matches[11]) && !$empty($matches[12])) || !empty($matches[14]) || !empty($matches[16])) { $highVersion = $this->normalize($matches['to']); $upperBound = new Constraint('<=', $highVersion); } else { $highMatch = array('', $matches[10], $matches[11], $matches[12], $matches[13]); $highVersion = $this->manipulateVersionString($highMatch, $empty($matches[11]) ? 1 : 2, 1) . '-dev'; $upperBound = new Constraint('<', $highVersion); } return array( $lowerBound, $upperBound, ); } // Basic Comparators if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) { try { $version = $this->normalize($matches[2]); if (!empty($stabilityModifier) && $this->parseStability($version) === 'stable') { $version .= '-' . $stabilityModifier; } elseif ('<' === $matches[1] || '>=' === $matches[1]) { if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) { if (substr($matches[2], 0, 4) !== 'dev-') { $version .= '-dev'; } } } return array(new Constraint($matches[1] ?: '=', $version)); } catch (\Exception $e) { } } $message = 'Could not parse version constraint ' . $constraint; if (isset($e)) { $message .= ': ' . $e->getMessage(); } throw new \UnexpectedValueException($message); } /** * Increment, decrement, or simply pad a version number. * * Support function for {@link parseConstraint()} * * @param array $matches Array with version parts in array indexes 1,2,3,4 * @param int $position 1,2,3,4 - which segment of the version to increment/decrement * @param int $increment * @param string $pad The string to pad version parts after $position * * @return string The new version */ private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0') { for ($i = 4; $i > 0; --$i) { if ($i > $position) { $matches[$i] = $pad; } elseif ($i === $position && $increment) { $matches[$i] += $increment; // If $matches[$i] was 0, carry the decrement if ($matches[$i] < 0) { $matches[$i] = $pad; --$position; // Return null on a carry overflow if ($i === 1) { return; } } } } return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4]; } /** * Expand shorthand stability string to long version. * * @param string $stability * * @return string */ private function expandStability($stability) { $stability = strtolower($stability); switch ($stability) { case 'a': return 'alpha'; case 'b': return 'beta'; case 'p': case 'pl': return 'patch'; case 'rc': return 'RC'; default: return $stability; } } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver; use Composer\Semver\Constraint\Constraint; class Semver { const SORT_ASC = 1; const SORT_DESC = -1; /** @var VersionParser */ private static $versionParser; /** * Determine if given version satisfies given constraints. * * @param string $version * @param string $constraints * * @return bool */ public static function satisfies($version, $constraints) { if (null === self::$versionParser) { self::$versionParser = new VersionParser(); } $versionParser = self::$versionParser; $provider = new Constraint('==', $versionParser->normalize($version)); $constraints = $versionParser->parseConstraints($constraints); return $constraints->matches($provider); } /** * Return all versions that satisfy given constraints. * * @param array $versions * @param string $constraints * * @return array */ public static function satisfiedBy(array $versions, $constraints) { $versions = array_filter($versions, function ($version) use ($constraints) { return Semver::satisfies($version, $constraints); }); return array_values($versions); } /** * Sort given array of versions. * * @param array $versions * * @return array */ public static function sort(array $versions) { return self::usort($versions, self::SORT_ASC); } /** * Sort given array of versions in reverse. * * @param array $versions * * @return array */ public static function rsort(array $versions) { return self::usort($versions, self::SORT_DESC); } /** * @param array $versions * @param int $direction * * @return array */ private static function usort(array $versions, $direction) { if (null === self::$versionParser) { self::$versionParser = new VersionParser(); } $versionParser = self::$versionParser; $normalized = array(); // Normalize outside of usort() scope for minor performance increase. // Creates an array of arrays: [[normalized, key], ...] foreach ($versions as $key => $version) { $normalized[] = array($versionParser->normalize($version), $key); } usort($normalized, function (array $left, array $right) use ($direction) { if ($left[0] === $right[0]) { return 0; } if (Comparator::lessThan($left[0], $right[0])) { return -$direction; } return $direction; }); // Recreate input array, using the original indexes which are now in sorted order. $sorted = array(); foreach ($normalized as $item) { $sorted[] = $versions[$item[1]]; } return $sorted; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; /** * Defines a constraint. */ class Constraint implements ConstraintInterface { /* operator integer values */ const OP_EQ = 0; const OP_LT = 1; const OP_LE = 2; const OP_GT = 3; const OP_GE = 4; const OP_NE = 5; /** * Operator to integer translation table. * * @var array */ private static $transOpStr = array( '=' => self::OP_EQ, '==' => self::OP_EQ, '<' => self::OP_LT, '<=' => self::OP_LE, '>' => self::OP_GT, '>=' => self::OP_GE, '<>' => self::OP_NE, '!=' => self::OP_NE, ); /** * Integer to operator translation table. * * @var array */ private static $transOpInt = array( self::OP_EQ => '==', self::OP_LT => '<', self::OP_LE => '<=', self::OP_GT => '>', self::OP_GE => '>=', self::OP_NE => '!=', ); /** @var string */ protected $operator; /** @var string */ protected $version; /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if ($provider instanceof $this) { return $this->matchSpecific($provider); } // turn matching around to find a match return $provider->matches($this); } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } /** * Get all supported comparison operators. * * @return array */ public static function getSupportedOperators() { return array_keys(self::$transOpStr); } /** * Sets operator and version to compare with. * * @param string $operator * @param string $version * * @throws \InvalidArgumentException if invalid operator is given. */ public function __construct($operator, $version) { if (!isset(self::$transOpStr[$operator])) { throw new \InvalidArgumentException(sprintf( 'Invalid operator "%s" given, expected one of: %s', $operator, implode(', ', self::getSupportedOperators()) )); } $this->operator = self::$transOpStr[$operator]; $this->version = $version; } /** * @param string $a * @param string $b * @param string $operator * @param bool $compareBranches * * @throws \InvalidArgumentException if invalid operator is given. * * @return bool */ public function versionCompare($a, $b, $operator, $compareBranches = false) { if (!isset(self::$transOpStr[$operator])) { throw new \InvalidArgumentException(sprintf( 'Invalid operator "%s" given, expected one of: %s', $operator, implode(', ', self::getSupportedOperators()) )); } $aIsBranch = 'dev-' === substr($a, 0, 4); $bIsBranch = 'dev-' === substr($b, 0, 4); if ($aIsBranch && $bIsBranch) { return $operator === '==' && $a === $b; } // when branches are not comparable, we make sure dev branches never match anything if (!$compareBranches && ($aIsBranch || $bIsBranch)) { return false; } return version_compare($a, $b, $operator); } /** * @param Constraint $provider * @param bool $compareBranches * * @return bool */ public function matchSpecific(Constraint $provider, $compareBranches = false) { $noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]); $providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]); $isEqualOp = self::OP_EQ === $this->operator; $isNonEqualOp = self::OP_NE === $this->operator; $isProviderEqualOp = self::OP_EQ === $provider->operator; $isProviderNonEqualOp = self::OP_NE === $provider->operator; // '!=' operator is match when other operator is not '==' operator or version is not match // these kinds of comparisons always have a solution if ($isNonEqualOp || $isProviderNonEqualOp) { return !$isEqualOp && !$isProviderEqualOp || $this->versionCompare($provider->version, $this->version, '!=', $compareBranches); } // an example for the condition is <= 2.0 & < 1.0 // these kinds of comparisons always have a solution if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) { return true; } if ($this->versionCompare($provider->version, $this->version, self::$transOpInt[$this->operator], $compareBranches)) { // special case, e.g. require >= 1.0 and provide < 1.0 // 1.0 >= 1.0 but 1.0 is outside of the provided interval if ($provider->version === $this->version && self::$transOpInt[$provider->operator] === $providerNoEqualOp && self::$transOpInt[$this->operator] !== $noEqualOp) { return false; } return true; } return false; } /** * @return string */ public function __toString() { return self::$transOpInt[$this->operator] . ' ' . $this->version; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; interface ConstraintInterface { /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider); /** * @return string */ public function getPrettyString(); /** * @return string */ public function __toString(); } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; trigger_error('The ' . __NAMESPACE__ . '\AbstractConstraint abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED); /** * Base constraint class. */ abstract class AbstractConstraint implements ConstraintInterface { /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if ($provider instanceof $this) { // see note at bottom of this class declaration return $this->matchSpecific($provider); } // turn matching around to find a match return $provider->matches($this); } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } // implementations must implement a method of this format: // not declared abstract here because type hinting violates parameter coherence (TODO right word?) // public function matchSpecific( $provider); } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; /** * Defines the absence of a constraint. */ class EmptyConstraint implements ConstraintInterface { /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { return true; } /** * @param $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } /** * @return string */ public function __toString() { return '[]'; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; /** * Defines a conjunctive or disjunctive set of constraints. */ class MultiConstraint implements ConstraintInterface { /** @var ConstraintInterface[] */ protected $constraints; /** @var string */ protected $prettyString; /** @var bool */ protected $conjunctive; /** * @param ConstraintInterface[] $constraints A set of constraints * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive */ public function __construct(array $constraints, $conjunctive = true) { $this->constraints = $constraints; $this->conjunctive = $conjunctive; } /** * @return ConstraintInterface[] */ public function getConstraints() { return $this->constraints; } /** * @return bool */ public function isConjunctive() { return $this->conjunctive; } /** * @return bool */ public function isDisjunctive() { return !$this->conjunctive; } /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if (false === $this->conjunctive) { foreach ($this->constraints as $constraint) { if ($constraint->matches($provider)) { return true; } } return false; } foreach ($this->constraints as $constraint) { if (!$constraint->matches($provider)) { return false; } } return true; } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } /** * @return string */ public function __toString() { $constraints = array(); foreach ($this->constraints as $constraint) { $constraints[] = (string) $constraint; } return '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']'; } } * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver; use Composer\Semver\Constraint\Constraint; class Comparator { /** * Evaluates the expression: $version1 > $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function greaterThan($version1, $version2) { return self::compare($version1, '>', $version2); } /** * Evaluates the expression: $version1 >= $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function greaterThanOrEqualTo($version1, $version2) { return self::compare($version1, '>=', $version2); } /** * Evaluates the expression: $version1 < $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function lessThan($version1, $version2) { return self::compare($version1, '<', $version2); } /** * Evaluates the expression: $version1 <= $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function lessThanOrEqualTo($version1, $version2) { return self::compare($version1, '<=', $version2); } /** * Evaluates the expression: $version1 == $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function equalTo($version1, $version2) { return self::compare($version1, '==', $version2); } /** * Evaluates the expression: $version1 != $version2. * * @param string $version1 * @param string $version2 * * @return bool */ public static function notEqualTo($version1, $version2) { return self::compare($version1, '!=', $version2); } /** * Evaluates the expression: $version1 $operator $version2. * * @param string $version1 * @param string $operator * @param string $version2 * * @return bool */ public static function compare($version1, $operator, $version2) { $constraint = new Constraint($operator, $version2); return $constraint->matches(new Constraint('==', $version1)); } } $vendorDir . '/jakub-onderka/php-parallel-lint/tests/skip-on-5.3/class.php', 'ExampleTrait' => $vendorDir . '/jakub-onderka/php-parallel-lint/tests/skip-on-5.3/trait.php', 'JakubOnderka\\PhpParallelLint\\ArrayIterator' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Settings.php', 'JakubOnderka\\PhpParallelLint\\Blame' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\ConsoleWriter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Error' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\ErrorFormatter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/ErrorFormatter.php', 'JakubOnderka\\PhpParallelLint\\Exception' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\FileWriter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\IWriter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\InvalidArgumentException' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\JsonOutput' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Manager' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Manager.php', 'JakubOnderka\\PhpParallelLint\\MultipleWriter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\NotExistsPathException' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\NullWriter' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\Output' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\ParallelLint' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/ParallelLint.php', 'JakubOnderka\\PhpParallelLint\\Process\\GitBlameProcess' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/GitBlameProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\LintProcess' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/LintProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\PhpExecutable' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/PhpExecutable.php', 'JakubOnderka\\PhpParallelLint\\Process\\PhpProcess' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/PhpProcess.php', 'JakubOnderka\\PhpParallelLint\\Process\\Process' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/Process.php', 'JakubOnderka\\PhpParallelLint\\Process\\SkipLintProcess' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Process/SkipLintProcess.php', 'JakubOnderka\\PhpParallelLint\\RecursiveDirectoryFilterIterator' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Manager.php', 'JakubOnderka\\PhpParallelLint\\Result' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Result.php', 'JakubOnderka\\PhpParallelLint\\RunTimeException' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/exceptions.php', 'JakubOnderka\\PhpParallelLint\\Settings' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Settings.php', 'JakubOnderka\\PhpParallelLint\\SyntaxError' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Error.php', 'JakubOnderka\\PhpParallelLint\\TextOutput' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JakubOnderka\\PhpParallelLint\\TextOutputColored' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/Output.php', 'JsonSerializable' => $vendorDir . '/jakub-onderka/php-parallel-lint/src/JsonSerializable.php', 'SebastianBergmann\\Comparator\\ArrayComparator' => $vendorDir . '/sebastian/comparator/src/ArrayComparator.php', 'SebastianBergmann\\Comparator\\Comparator' => $vendorDir . '/sebastian/comparator/src/Comparator.php', 'SebastianBergmann\\Comparator\\ComparisonFailure' => $vendorDir . '/sebastian/comparator/src/ComparisonFailure.php', 'SebastianBergmann\\Comparator\\DOMNodeComparator' => $vendorDir . '/sebastian/comparator/src/DOMNodeComparator.php', 'SebastianBergmann\\Comparator\\DateTimeComparator' => $vendorDir . '/sebastian/comparator/src/DateTimeComparator.php', 'SebastianBergmann\\Comparator\\DoubleComparator' => $vendorDir . '/sebastian/comparator/src/DoubleComparator.php', 'SebastianBergmann\\Comparator\\ExceptionComparator' => $vendorDir . '/sebastian/comparator/src/ExceptionComparator.php', 'SebastianBergmann\\Comparator\\Factory' => $vendorDir . '/sebastian/comparator/src/Factory.php', 'SebastianBergmann\\Comparator\\MockObjectComparator' => $vendorDir . '/sebastian/comparator/src/MockObjectComparator.php', 'SebastianBergmann\\Comparator\\NumericComparator' => $vendorDir . '/sebastian/comparator/src/NumericComparator.php', 'SebastianBergmann\\Comparator\\ObjectComparator' => $vendorDir . '/sebastian/comparator/src/ObjectComparator.php', 'SebastianBergmann\\Comparator\\ResourceComparator' => $vendorDir . '/sebastian/comparator/src/ResourceComparator.php', 'SebastianBergmann\\Comparator\\ScalarComparator' => $vendorDir . '/sebastian/comparator/src/ScalarComparator.php', 'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => $vendorDir . '/sebastian/comparator/src/SplObjectStorageComparator.php', 'SebastianBergmann\\Comparator\\TypeComparator' => $vendorDir . '/sebastian/comparator/src/TypeComparator.php', 'SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php', 'SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php', 'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php', 'SebastianBergmann\\Diff\\LCS\\LongestCommonSubsequence' => $vendorDir . '/sebastian/diff/src/LCS/LongestCommonSubsequence.php', 'SebastianBergmann\\Diff\\LCS\\MemoryEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php', 'SebastianBergmann\\Diff\\LCS\\TimeEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php', 'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php', 'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php', 'SebastianBergmann\\Environment\\Console' => $vendorDir . '/sebastian/environment/src/Console.php', 'SebastianBergmann\\Environment\\Runtime' => $vendorDir . '/sebastian/environment/src/Runtime.php', 'SebastianBergmann\\Exporter\\Exporter' => $vendorDir . '/sebastian/exporter/src/Exporter.php', 'SebastianBergmann\\GlobalState\\Blacklist' => $vendorDir . '/sebastian/global-state/src/Blacklist.php', 'SebastianBergmann\\GlobalState\\CodeExporter' => $vendorDir . '/sebastian/global-state/src/CodeExporter.php', 'SebastianBergmann\\GlobalState\\Exception' => $vendorDir . '/sebastian/global-state/src/Exception.php', 'SebastianBergmann\\GlobalState\\Restorer' => $vendorDir . '/sebastian/global-state/src/Restorer.php', 'SebastianBergmann\\GlobalState\\RuntimeException' => $vendorDir . '/sebastian/global-state/src/RuntimeException.php', 'SebastianBergmann\\GlobalState\\Snapshot' => $vendorDir . '/sebastian/global-state/src/Snapshot.php', 'SebastianBergmann\\RecursionContext\\Context' => $vendorDir . '/sebastian/recursion-context/src/Context.php', 'SebastianBergmann\\RecursionContext\\Exception' => $vendorDir . '/sebastian/recursion-context/src/Exception.php', 'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => $vendorDir . '/sebastian/recursion-context/src/InvalidArgumentException.php', 'SebastianBergmann\\Version' => $vendorDir . '/sebastian/version/src/Version.php', ); array($vendorDir . '/phpdocumentor/reflection-docblock/src'), 'cli' => array($vendorDir . '/wp-cli/php-cli-tools/lib'), 'WP_CLI' => array($vendorDir . '/wp-cli/wp-cli/php'), 'Requests' => array($vendorDir . '/rmccue/requests/library'), 'Oxymel' => array($vendorDir . '/nb/oxymel'), 'Mustache' => array($vendorDir . '/mustache/mustache/src'), 'Behat\\Gherkin' => array($vendorDir . '/behat/gherkin/src'), 'Behat\\Behat' => array($vendorDir . '/behat/behat/src'), ); * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Expression; @trigger_error('The '.__NAMESPACE__.'\ValueInterface interface is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon */ interface ValueInterface { /** * Renders string representation of expression. * * @return string */ public function render(); /** * Renders string representation of pattern. * * @return string */ public function renderPattern(); /** * Returns value case sensitivity. * * @return bool */ public function isCaseSensitive(); /** * Returns expression type. * * @return int */ public function getType(); /** * @param string $expr * * @return $this */ public function prepend($expr); /** * @param string $expr * * @return $this */ public function append($expr); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Expression; @trigger_error('The '.__NAMESPACE__.'\Expression class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon */ class Expression implements ValueInterface { const TYPE_REGEX = 1; const TYPE_GLOB = 2; /** * @var ValueInterface */ private $value; /** * @param string $expr * * @return self */ public static function create($expr) { return new self($expr); } /** * @param string $expr */ public function __construct($expr) { try { $this->value = Regex::create($expr); } catch (\InvalidArgumentException $e) { $this->value = new Glob($expr); } } /** * @return string */ public function __toString() { return $this->render(); } /** * {@inheritdoc} */ public function render() { return $this->value->render(); } /** * {@inheritdoc} */ public function renderPattern() { return $this->value->renderPattern(); } /** * @return bool */ public function isCaseSensitive() { return $this->value->isCaseSensitive(); } /** * @return int */ public function getType() { return $this->value->getType(); } /** * {@inheritdoc} */ public function prepend($expr) { $this->value->prepend($expr); return $this; } /** * {@inheritdoc} */ public function append($expr) { $this->value->append($expr); return $this; } /** * @return bool */ public function isRegex() { return self::TYPE_REGEX === $this->value->getType(); } /** * @return bool */ public function isGlob() { return self::TYPE_GLOB === $this->value->getType(); } /** * @return Glob * * @throws \LogicException */ public function getGlob() { if (self::TYPE_GLOB !== $this->value->getType()) { throw new \LogicException('Regex can\'t be transformed to glob.'); } return $this->value; } /** * @return Regex */ public function getRegex() { return self::TYPE_REGEX === $this->value->getType() ? $this->value : $this->value->toRegex(); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Expression; @trigger_error('The '.__NAMESPACE__.'\Regex class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon */ class Regex implements ValueInterface { const START_FLAG = '^'; const END_FLAG = '$'; const BOUNDARY = '~'; const JOKER = '.*'; const ESCAPING = '\\'; /** * @var string */ private $pattern; /** * @var string */ private $options; /** * @var bool */ private $startFlag; /** * @var bool */ private $endFlag; /** * @var bool */ private $startJoker; /** * @var bool */ private $endJoker; /** * @param string $expr * * @return self * * @throws \InvalidArgumentException */ public static function create($expr) { if (preg_match('/^(.{3,}?)([imsxuADU]*)$/', $expr, $m)) { $start = substr($m[1], 0, 1); $end = substr($m[1], -1); if ( ($start === $end && !preg_match('/[*?[:alnum:] \\\\]/', $start)) || ('{' === $start && '}' === $end) || ('(' === $start && ')' === $end) ) { return new self(substr($m[1], 1, -1), $m[2], $end); } } throw new \InvalidArgumentException('Given expression is not a regex.'); } /** * @param string $pattern * @param string $options * @param string $delimiter */ public function __construct($pattern, $options = '', $delimiter = null) { if (null !== $delimiter) { // removes delimiter escaping $pattern = str_replace('\\'.$delimiter, $delimiter, $pattern); } $this->parsePattern($pattern); $this->options = $options; } /** * @return string */ public function __toString() { return $this->render(); } /** * {@inheritdoc} */ public function render() { return self::BOUNDARY .$this->renderPattern() .self::BOUNDARY .$this->options; } /** * {@inheritdoc} */ public function renderPattern() { return ($this->startFlag ? self::START_FLAG : '') .($this->startJoker ? self::JOKER : '') .str_replace(self::BOUNDARY, '\\'.self::BOUNDARY, $this->pattern) .($this->endJoker ? self::JOKER : '') .($this->endFlag ? self::END_FLAG : ''); } /** * {@inheritdoc} */ public function isCaseSensitive() { return !$this->hasOption('i'); } /** * {@inheritdoc} */ public function getType() { return Expression::TYPE_REGEX; } /** * {@inheritdoc} */ public function prepend($expr) { $this->pattern = $expr.$this->pattern; return $this; } /** * {@inheritdoc} */ public function append($expr) { $this->pattern .= $expr; return $this; } /** * @param string $option * * @return bool */ public function hasOption($option) { return false !== strpos($this->options, $option); } /** * @param string $option * * @return $this */ public function addOption($option) { if (!$this->hasOption($option)) { $this->options .= $option; } return $this; } /** * @param string $option * * @return $this */ public function removeOption($option) { $this->options = str_replace($option, '', $this->options); return $this; } /** * @param bool $startFlag * * @return $this */ public function setStartFlag($startFlag) { $this->startFlag = $startFlag; return $this; } /** * @return bool */ public function hasStartFlag() { return $this->startFlag; } /** * @param bool $endFlag * * @return $this */ public function setEndFlag($endFlag) { $this->endFlag = (bool) $endFlag; return $this; } /** * @return bool */ public function hasEndFlag() { return $this->endFlag; } /** * @param bool $startJoker * * @return $this */ public function setStartJoker($startJoker) { $this->startJoker = $startJoker; return $this; } /** * @return bool */ public function hasStartJoker() { return $this->startJoker; } /** * @param bool $endJoker * * @return $this */ public function setEndJoker($endJoker) { $this->endJoker = (bool) $endJoker; return $this; } /** * @return bool */ public function hasEndJoker() { return $this->endJoker; } /** * @return $this */ public function replaceJokers($replacement) { $replace = function ($subject) use ($replacement) { $subject = $subject[0]; $replace = 0 === substr_count($subject, '\\') % 2; return $replace ? str_replace('.', $replacement, $subject) : $subject; }; $this->pattern = preg_replace_callback('~[\\\\]*\\.~', $replace, $this->pattern); return $this; } /** * @param string $pattern */ private function parsePattern($pattern) { if ($this->startFlag = self::START_FLAG === substr($pattern, 0, 1)) { $pattern = substr($pattern, 1); } if ($this->startJoker = self::JOKER === substr($pattern, 0, 2)) { $pattern = substr($pattern, 2); } if ($this->endFlag = (self::END_FLAG === substr($pattern, -1) && self::ESCAPING !== substr($pattern, -2, -1))) { $pattern = substr($pattern, 0, -1); } if ($this->endJoker = (self::JOKER === substr($pattern, -2) && self::ESCAPING !== substr($pattern, -3, -2))) { $pattern = substr($pattern, 0, -2); } $this->pattern = $pattern; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Expression; @trigger_error('The '.__NAMESPACE__.'\Glob class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); use Symfony\Component\Finder\Glob as FinderGlob; /** * @author Jean-François Simon */ class Glob implements ValueInterface { private $pattern; /** * @param string $pattern */ public function __construct($pattern) { $this->pattern = $pattern; } /** * {@inheritdoc} */ public function render() { return $this->pattern; } /** * {@inheritdoc} */ public function renderPattern() { return $this->pattern; } /** * {@inheritdoc} */ public function getType() { return Expression::TYPE_GLOB; } /** * {@inheritdoc} */ public function isCaseSensitive() { return true; } /** * {@inheritdoc} */ public function prepend($expr) { $this->pattern = $expr.$this->pattern; return $this; } /** * {@inheritdoc} */ public function append($expr) { $this->pattern .= $expr; return $this; } /** * Tests if glob is expandable ("*.{a,b}" syntax). * * @return bool */ public function isExpandable() { return false !== strpos($this->pattern, '{') && false !== strpos($this->pattern, '}'); } /** * @param bool $strictLeadingDot * @param bool $strictWildcardSlash * * @return Regex */ public function toRegex($strictLeadingDot = true, $strictWildcardSlash = true) { $regex = FinderGlob::toRegex($this->pattern, $strictLeadingDot, $strictWildcardSlash, ''); return new Regex($regex); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Comparator; /** * DateCompare compiles date comparisons. * * @author Fabien Potencier */ class DateComparator extends Comparator { /** * @param string $test A comparison string * * @throws \InvalidArgumentException If the test is not understood */ public function __construct($test) { if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) { throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test)); } try { $date = new \DateTime($matches[2]); $target = $date->format('U'); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2])); } $operator = isset($matches[1]) ? $matches[1] : '=='; if ('since' === $operator || 'after' === $operator) { $operator = '>'; } if ('until' === $operator || 'before' === $operator) { $operator = '<'; } $this->setOperator($operator); $this->setTarget($target); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Comparator; /** * Comparator. * * @author Fabien Potencier */ class Comparator { private $target; private $operator = '=='; /** * Gets the target value. * * @return string The target value */ public function getTarget() { return $this->target; } /** * Sets the target value. * * @param string $target The target value */ public function setTarget($target) { $this->target = $target; } /** * Gets the comparison operator. * * @return string The operator */ public function getOperator() { return $this->operator; } /** * Sets the comparison operator. * * @param string $operator A valid operator * * @throws \InvalidArgumentException */ public function setOperator($operator) { if (!$operator) { $operator = '=='; } if (!\in_array($operator, array('>', '<', '>=', '<=', '==', '!='))) { throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator)); } $this->operator = $operator; } /** * Tests against the target. * * @param mixed $test A test value * * @return bool */ public function test($test) { switch ($this->operator) { case '>': return $test > $this->target; case '>=': return $test >= $this->target; case '<': return $test < $this->target; case '<=': return $test <= $this->target; case '!=': return $test != $this->target; } return $test == $this->target; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Comparator; /** * NumberComparator compiles a simple comparison to an anonymous * subroutine, which you can call with a value to be tested again. * * Now this would be very pointless, if NumberCompare didn't understand * magnitudes. * * The target value may use magnitudes of kilobytes (k, ki), * megabytes (m, mi), or gigabytes (g, gi). Those suffixed * with an i use the appropriate 2**n version in accordance with the * IEC standard: http://physics.nist.gov/cuu/Units/binary.html * * Based on the Perl Number::Compare module. * * @author Fabien Potencier PHP port * @author Richard Clamp Perl version * @copyright 2004-2005 Fabien Potencier * @copyright 2002 Richard Clamp * * @see http://physics.nist.gov/cuu/Units/binary.html */ class NumberComparator extends Comparator { /** * @param string|int $test A comparison string or an integer * * @throws \InvalidArgumentException If the test is not understood */ public function __construct($test) { if (!preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) { throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test)); } $target = $matches[2]; if (!is_numeric($target)) { throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target)); } if (isset($matches[3])) { // magnitude switch (strtolower($matches[3])) { case 'k': $target *= 1000; break; case 'ki': $target *= 1024; break; case 'm': $target *= 1000000; break; case 'mi': $target *= 1024 * 1024; break; case 'g': $target *= 1000000000; break; case 'gi': $target *= 1024 * 1024 * 1024; break; } } $this->setTarget($target); $this->setOperator(isset($matches[1]) ? $matches[1] : '=='); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder; use Symfony\Component\Finder\Adapter\AdapterInterface; use Symfony\Component\Finder\Adapter\BsdFindAdapter; use Symfony\Component\Finder\Adapter\GnuFindAdapter; use Symfony\Component\Finder\Adapter\PhpAdapter; use Symfony\Component\Finder\Comparator\DateComparator; use Symfony\Component\Finder\Comparator\NumberComparator; use Symfony\Component\Finder\Exception\ExceptionInterface; use Symfony\Component\Finder\Iterator\CustomFilterIterator; use Symfony\Component\Finder\Iterator\DateRangeFilterIterator; use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator; use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator; use Symfony\Component\Finder\Iterator\FilecontentFilterIterator; use Symfony\Component\Finder\Iterator\FilenameFilterIterator; use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator; use Symfony\Component\Finder\Iterator\SortableIterator; /** * Finder allows to build rules to find files and directories. * * It is a thin wrapper around several specialized iterator classes. * * All rules may be invoked several times. * * All methods return the current Finder object to allow easy chaining: * * $finder = Finder::create()->files()->name('*.php')->in(__DIR__); * * @author Fabien Potencier */ class Finder implements \IteratorAggregate, \Countable { const IGNORE_VCS_FILES = 1; const IGNORE_DOT_FILES = 2; private $mode = 0; private $names = array(); private $notNames = array(); private $exclude = array(); private $filters = array(); private $depths = array(); private $sizes = array(); private $followLinks = false; private $sort = false; private $ignore = 0; private $dirs = array(); private $dates = array(); private $iterators = array(); private $contains = array(); private $notContains = array(); private $adapters = null; private $paths = array(); private $notPaths = array(); private $ignoreUnreadableDirs = false; private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'); public function __construct() { $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES; } /** * Creates a new Finder. * * @return static */ public static function create() { return new static(); } /** * Registers a finder engine implementation. * * @param AdapterInterface $adapter An adapter instance * @param int $priority Highest is selected first * * @return $this * * @deprecated since 2.8, to be removed in 3.0. */ public function addAdapter(AdapterInterface $adapter, $priority = 0) { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); $this->initDefaultAdapters(); $this->adapters[$adapter->getName()] = array( 'adapter' => $adapter, 'priority' => $priority, 'selected' => false, ); return $this->sortAdapters(); } /** * Sets the selected adapter to the best one according to the current platform the code is run on. * * @return $this * * @deprecated since 2.8, to be removed in 3.0. */ public function useBestAdapter() { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); $this->initDefaultAdapters(); $this->resetAdapterSelection(); return $this->sortAdapters(); } /** * Selects the adapter to use. * * @param string $name * * @return $this * * @throws \InvalidArgumentException * * @deprecated since 2.8, to be removed in 3.0. */ public function setAdapter($name) { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); $this->initDefaultAdapters(); if (!isset($this->adapters[$name])) { throw new \InvalidArgumentException(sprintf('Adapter "%s" does not exist.', $name)); } $this->resetAdapterSelection(); $this->adapters[$name]['selected'] = true; return $this->sortAdapters(); } /** * Removes all adapters registered in the finder. * * @return $this * * @deprecated since 2.8, to be removed in 3.0. */ public function removeAdapters() { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); $this->adapters = array(); return $this; } /** * Returns registered adapters ordered by priority without extra information. * * @return AdapterInterface[] * * @deprecated since 2.8, to be removed in 3.0. */ public function getAdapters() { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); $this->initDefaultAdapters(); return array_values(array_map(function (array $adapter) { return $adapter['adapter']; }, $this->adapters)); } /** * Restricts the matching to directories only. * * @return $this */ public function directories() { $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES; return $this; } /** * Restricts the matching to files only. * * @return $this */ public function files() { $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES; return $this; } /** * Adds tests for the directory depth. * * Usage: * * $finder->depth('> 1') // the Finder will start matching at level 1. * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point. * * @param string|int $level The depth level expression * * @return $this * * @see DepthRangeFilterIterator * @see NumberComparator */ public function depth($level) { $this->depths[] = new Comparator\NumberComparator($level); return $this; } /** * Adds tests for file dates (last modified). * * The date must be something that strtotime() is able to parse: * * $finder->date('since yesterday'); * $finder->date('until 2 days ago'); * $finder->date('> now - 2 hours'); * $finder->date('>= 2005-10-15'); * * @param string $date A date range string * * @return $this * * @see strtotime * @see DateRangeFilterIterator * @see DateComparator */ public function date($date) { $this->dates[] = new Comparator\DateComparator($date); return $this; } /** * Adds rules that files must match. * * You can use patterns (delimited with / sign), globs or simple strings. * * $finder->name('*.php') * $finder->name('/\.php$/') // same as above * $finder->name('test.php') * * @param string $pattern A pattern (a regexp, a glob, or a string) * * @return $this * * @see FilenameFilterIterator */ public function name($pattern) { $this->names[] = $pattern; return $this; } /** * Adds rules that files must not match. * * @param string $pattern A pattern (a regexp, a glob, or a string) * * @return $this * * @see FilenameFilterIterator */ public function notName($pattern) { $this->notNames[] = $pattern; return $this; } /** * Adds tests that file contents must match. * * Strings or PCRE patterns can be used: * * $finder->contains('Lorem ipsum') * $finder->contains('/Lorem ipsum/i') * * @param string $pattern A pattern (string or regexp) * * @return $this * * @see FilecontentFilterIterator */ public function contains($pattern) { $this->contains[] = $pattern; return $this; } /** * Adds tests that file contents must not match. * * Strings or PCRE patterns can be used: * * $finder->notContains('Lorem ipsum') * $finder->notContains('/Lorem ipsum/i') * * @param string $pattern A pattern (string or regexp) * * @return $this * * @see FilecontentFilterIterator */ public function notContains($pattern) { $this->notContains[] = $pattern; return $this; } /** * Adds rules that filenames must match. * * You can use patterns (delimited with / sign) or simple strings. * * $finder->path('some/special/dir') * $finder->path('/some\/special\/dir/') // same as above * * Use only / as dirname separator. * * @param string $pattern A pattern (a regexp or a string) * * @return $this * * @see FilenameFilterIterator */ public function path($pattern) { $this->paths[] = $pattern; return $this; } /** * Adds rules that filenames must not match. * * You can use patterns (delimited with / sign) or simple strings. * * $finder->notPath('some/special/dir') * $finder->notPath('/some\/special\/dir/') // same as above * * Use only / as dirname separator. * * @param string $pattern A pattern (a regexp or a string) * * @return $this * * @see FilenameFilterIterator */ public function notPath($pattern) { $this->notPaths[] = $pattern; return $this; } /** * Adds tests for file sizes. * * $finder->size('> 10K'); * $finder->size('<= 1Ki'); * $finder->size(4); * * @param string|int $size A size range string or an integer * * @return $this * * @see SizeRangeFilterIterator * @see NumberComparator */ public function size($size) { $this->sizes[] = new Comparator\NumberComparator($size); return $this; } /** * Excludes directories. * * Directories passed as argument must be relative to the ones defined with the `in()` method. For example: * * $finder->in(__DIR__)->exclude('ruby'); * * @param string|array $dirs A directory path or an array of directories * * @return $this * * @see ExcludeDirectoryFilterIterator */ public function exclude($dirs) { $this->exclude = array_merge($this->exclude, (array) $dirs); return $this; } /** * Excludes "hidden" directories and files (starting with a dot). * * This option is enabled by default. * * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not * * @return $this * * @see ExcludeDirectoryFilterIterator */ public function ignoreDotFiles($ignoreDotFiles) { if ($ignoreDotFiles) { $this->ignore |= static::IGNORE_DOT_FILES; } else { $this->ignore &= ~static::IGNORE_DOT_FILES; } return $this; } /** * Forces the finder to ignore version control directories. * * This option is enabled by default. * * @param bool $ignoreVCS Whether to exclude VCS files or not * * @return $this * * @see ExcludeDirectoryFilterIterator */ public function ignoreVCS($ignoreVCS) { if ($ignoreVCS) { $this->ignore |= static::IGNORE_VCS_FILES; } else { $this->ignore &= ~static::IGNORE_VCS_FILES; } return $this; } /** * Adds VCS patterns. * * @see ignoreVCS() * * @param string|string[] $pattern VCS patterns to ignore */ public static function addVCSPattern($pattern) { foreach ((array) $pattern as $p) { self::$vcsPatterns[] = $p; } self::$vcsPatterns = array_unique(self::$vcsPatterns); } /** * Sorts files and directories by an anonymous function. * * The anonymous function receives two \SplFileInfo instances to compare. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sort(\Closure $closure) { $this->sort = $closure; return $this; } /** * Sorts files and directories by name. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sortByName() { $this->sort = Iterator\SortableIterator::SORT_BY_NAME; return $this; } /** * Sorts files and directories by type (directories before files), then by name. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sortByType() { $this->sort = Iterator\SortableIterator::SORT_BY_TYPE; return $this; } /** * Sorts files and directories by the last accessed time. * * This is the time that the file was last accessed, read or written to. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sortByAccessedTime() { $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME; return $this; } /** * Sorts files and directories by the last inode changed time. * * This is the time that the inode information was last modified (permissions, owner, group or other metadata). * * On Windows, since inode is not available, changed time is actually the file creation time. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sortByChangedTime() { $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME; return $this; } /** * Sorts files and directories by the last modified time. * * This is the last time the actual contents of the file were last modified. * * This can be slow as all the matching files and directories must be retrieved for comparison. * * @return $this * * @see SortableIterator */ public function sortByModifiedTime() { $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME; return $this; } /** * Filters the iterator with an anonymous function. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @return $this * * @see CustomFilterIterator */ public function filter(\Closure $closure) { $this->filters[] = $closure; return $this; } /** * Forces the following of symlinks. * * @return $this */ public function followLinks() { $this->followLinks = true; return $this; } /** * Tells finder to ignore unreadable directories. * * By default, scanning unreadable directories content throws an AccessDeniedException. * * @param bool $ignore * * @return $this */ public function ignoreUnreadableDirs($ignore = true) { $this->ignoreUnreadableDirs = (bool) $ignore; return $this; } /** * Searches files and directories which match defined rules. * * @param string|array $dirs A directory path or an array of directories * * @return $this * * @throws \InvalidArgumentException if one of the directories does not exist */ public function in($dirs) { $resolvedDirs = array(); foreach ((array) $dirs as $dir) { if (is_dir($dir)) { $resolvedDirs[] = $this->normalizeDir($dir); } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) { $resolvedDirs = array_merge($resolvedDirs, array_map(array($this, 'normalizeDir'), $glob)); } else { throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir)); } } $this->dirs = array_merge($this->dirs, $resolvedDirs); return $this; } /** * Returns an Iterator for the current Finder configuration. * * This method implements the IteratorAggregate interface. * * @return \Iterator|SplFileInfo[] An iterator * * @throws \LogicException if the in() method has not been called */ public function getIterator() { if (0 === \count($this->dirs) && 0 === \count($this->iterators)) { throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.'); } if (1 === \count($this->dirs) && 0 === \count($this->iterators)) { return $this->searchInDirectory($this->dirs[0]); } $iterator = new \AppendIterator(); foreach ($this->dirs as $dir) { $iterator->append($this->searchInDirectory($dir)); } foreach ($this->iterators as $it) { $iterator->append($it); } return $iterator; } /** * Appends an existing set of files/directories to the finder. * * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array. * * @param iterable $iterator * * @return $this * * @throws \InvalidArgumentException when the given argument is not iterable */ public function append($iterator) { if ($iterator instanceof \IteratorAggregate) { $this->iterators[] = $iterator->getIterator(); } elseif ($iterator instanceof \Iterator) { $this->iterators[] = $iterator; } elseif ($iterator instanceof \Traversable || \is_array($iterator)) { $it = new \ArrayIterator(); foreach ($iterator as $file) { $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file)); } $this->iterators[] = $it; } else { throw new \InvalidArgumentException('Finder::append() method wrong argument type.'); } return $this; } /** * Counts all the results collected by the iterators. * * @return int */ public function count() { return iterator_count($this->getIterator()); } /** * @return $this */ private function sortAdapters() { uasort($this->adapters, function (array $a, array $b) { if ($a['selected'] || $b['selected']) { return $a['selected'] ? -1 : 1; } return $a['priority'] > $b['priority'] ? -1 : 1; }); return $this; } /** * @param string $dir * * @return \Iterator */ private function searchInDirectory($dir) { if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) { $this->exclude = array_merge($this->exclude, self::$vcsPatterns); } if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) { $this->notPaths[] = '#(^|/)\..+(/|$)#'; } if ($this->adapters) { foreach ($this->adapters as $adapter) { if ($adapter['adapter']->isSupported()) { try { return $this ->buildAdapter($adapter['adapter']) ->searchInDirectory($dir); } catch (ExceptionInterface $e) { } } } } $minDepth = 0; $maxDepth = PHP_INT_MAX; foreach ($this->depths as $comparator) { switch ($comparator->getOperator()) { case '>': $minDepth = $comparator->getTarget() + 1; break; case '>=': $minDepth = $comparator->getTarget(); break; case '<': $maxDepth = $comparator->getTarget() - 1; break; case '<=': $maxDepth = $comparator->getTarget(); break; default: $minDepth = $maxDepth = $comparator->getTarget(); } } $flags = \RecursiveDirectoryIterator::SKIP_DOTS; if ($this->followLinks) { $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS; } $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs); if ($this->exclude) { $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude); } $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) { $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth); } if ($this->mode) { $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode); } if ($this->names || $this->notNames) { $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames); } if ($this->contains || $this->notContains) { $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains); } if ($this->sizes) { $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes); } if ($this->dates) { $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates); } if ($this->filters) { $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); } if ($this->paths || $this->notPaths) { $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths); } if ($this->sort) { $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort); $iterator = $iteratorAggregate->getIterator(); } return $iterator; } /** * @return AdapterInterface */ private function buildAdapter(AdapterInterface $adapter) { return $adapter ->setFollowLinks($this->followLinks) ->setDepths($this->depths) ->setMode($this->mode) ->setExclude($this->exclude) ->setNames($this->names) ->setNotNames($this->notNames) ->setContains($this->contains) ->setNotContains($this->notContains) ->setSizes($this->sizes) ->setDates($this->dates) ->setFilters($this->filters) ->setSort($this->sort) ->setPath($this->paths) ->setNotPath($this->notPaths) ->ignoreUnreadableDirs($this->ignoreUnreadableDirs); } /** * Unselects all adapters. */ private function resetAdapterSelection() { $this->adapters = array_map(function (array $properties) { $properties['selected'] = false; return $properties; }, $this->adapters); } private function initDefaultAdapters() { if (null === $this->adapters) { $this->adapters = array(); $this ->addAdapter(new GnuFindAdapter()) ->addAdapter(new BsdFindAdapter()) ->addAdapter(new PhpAdapter(), -50) ->setAdapter('php') ; } } /** * Normalizes given directory names by removing trailing slashes. * * @param string $dir * * @return string */ private function normalizeDir($dir) { return rtrim($dir, '/'.\DIRECTORY_SEPARATOR); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder; /** * Extends \SplFileInfo to support relative paths. * * @author Fabien Potencier */ class SplFileInfo extends \SplFileInfo { private $relativePath; private $relativePathname; /** * @param string $file The file name * @param string $relativePath The relative path * @param string $relativePathname The relative path name */ public function __construct($file, $relativePath, $relativePathname) { parent::__construct($file); $this->relativePath = $relativePath; $this->relativePathname = $relativePathname; } /** * Returns the relative path. * * This path does not contain the file name. * * @return string the relative path */ public function getRelativePath() { return $this->relativePath; } /** * Returns the relative path name. * * This path contains the file name. * * @return string the relative path name */ public function getRelativePathname() { return $this->relativePathname; } /** * Returns the contents of the file. * * @return string the contents of the file * * @throws \RuntimeException */ public function getContents() { set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); $content = file_get_contents($this->getPathname()); restore_error_handler(); if (false === $content) { throw new \RuntimeException($error); } return $content; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Shell; @trigger_error('The '.__NAMESPACE__.'\Shell class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class Shell { const TYPE_UNIX = 1; const TYPE_DARWIN = 2; const TYPE_CYGWIN = 3; const TYPE_WINDOWS = 4; const TYPE_BSD = 5; /** * @var string|null */ private $type; /** * Returns guessed OS type. * * @return int */ public function getType() { if (null === $this->type) { $this->type = $this->guessType(); } return $this->type; } /** * Tests if a command is available. * * @param string $command * * @return bool */ public function testCommand($command) { if (!\function_exists('exec')) { return false; } // todo: find a better way (command could not be available) $testCommand = 'which '; if (self::TYPE_WINDOWS === $this->type) { $testCommand = 'where '; } $command = escapeshellcmd($command); exec($testCommand.$command, $output, $code); return 0 === $code && \count($output) > 0; } /** * Guesses OS type. * * @return int */ private function guessType() { $os = strtolower(PHP_OS); if (false !== strpos($os, 'cygwin')) { return self::TYPE_CYGWIN; } if (false !== strpos($os, 'darwin')) { return self::TYPE_DARWIN; } if (false !== strpos($os, 'bsd')) { return self::TYPE_BSD; } if (0 === strpos($os, 'win')) { return self::TYPE_WINDOWS; } return self::TYPE_UNIX; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Shell; @trigger_error('The '.__NAMESPACE__.'\Command class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class Command { private $parent; private $bits = array(); private $labels = array(); /** * @var \Closure|null */ private $errorHandler; public function __construct(Command $parent = null) { $this->parent = $parent; } /** * Returns command as string. * * @return string */ public function __toString() { return $this->join(); } /** * Creates a new Command instance. * * @return self */ public static function create(Command $parent = null) { return new self($parent); } /** * Escapes special chars from input. * * @param string $input A string to escape * * @return string The escaped string */ public static function escape($input) { return escapeshellcmd($input); } /** * Quotes input. * * @param string $input An argument string * * @return string The quoted string */ public static function quote($input) { return escapeshellarg($input); } /** * Appends a string or a Command instance. * * @param string|Command $bit * * @return $this */ public function add($bit) { $this->bits[] = $bit; return $this; } /** * Prepends a string or a command instance. * * @param string|Command $bit * * @return $this */ public function top($bit) { array_unshift($this->bits, $bit); foreach ($this->labels as $label => $index) { ++$this->labels[$label]; } return $this; } /** * Appends an argument, will be quoted. * * @param string $arg * * @return $this */ public function arg($arg) { $this->bits[] = self::quote($arg); return $this; } /** * Appends escaped special command chars. * * @param string $esc * * @return $this */ public function cmd($esc) { $this->bits[] = self::escape($esc); return $this; } /** * Inserts a labeled command to feed later. * * @param string $label The unique label * * @return self|string * * @throws \RuntimeException If label already exists */ public function ins($label) { if (isset($this->labels[$label])) { throw new \RuntimeException(sprintf('Label "%s" already exists.', $label)); } $this->bits[] = self::create($this); $this->labels[$label] = \count($this->bits) - 1; return $this->bits[$this->labels[$label]]; } /** * Retrieves a previously labeled command. * * @param string $label * * @return self|string * * @throws \RuntimeException */ public function get($label) { if (!isset($this->labels[$label])) { throw new \RuntimeException(sprintf('Label "%s" does not exist.', $label)); } return $this->bits[$this->labels[$label]]; } /** * Returns parent command (if any). * * @return self * * @throws \RuntimeException If command has no parent */ public function end() { if (null === $this->parent) { throw new \RuntimeException('Calling end on root command doesn\'t make sense.'); } return $this->parent; } /** * Counts bits stored in command. * * @return int The bits count */ public function length() { return \count($this->bits); } /** * @return $this */ public function setErrorHandler(\Closure $errorHandler) { $this->errorHandler = $errorHandler; return $this; } /** * @return \Closure|null */ public function getErrorHandler() { return $this->errorHandler; } /** * Executes current command. * * @return array The command result * * @throws \RuntimeException */ public function execute() { if (null === $errorHandler = $this->errorHandler) { exec($this->join(), $output); } else { $process = proc_open($this->join(), array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes); $output = preg_split('~(\r\n|\r|\n)~', stream_get_contents($pipes[1]), -1, PREG_SPLIT_NO_EMPTY); if ($error = stream_get_contents($pipes[2])) { $errorHandler($error); } proc_close($process); } return $output ?: array(); } /** * Joins bits. * * @return string */ public function join() { return implode(' ', array_filter( array_map(function ($bit) { return $bit instanceof Command ? $bit->join() : ($bit ?: null); }, $this->bits), function ($bit) { return null !== $bit; } )); } /** * Insert a string or a Command instance before the bit at given position $index (index starts from 0). * * @param string|Command $bit * @param int $index * * @return $this */ public function addAtIndex($bit, $index) { array_splice($this->bits, $index, 0, $bit instanceof self ? array($bit) : $bit); return $this; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; @trigger_error('The '.__NAMESPACE__.'\AbstractAdapter class is deprecated since Symfony 2.8 and will be removed in 3.0. Use directly the Finder class instead.', E_USER_DEPRECATED); /** * Interface for finder engine implementations. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. Use Finder instead. */ abstract class AbstractAdapter implements AdapterInterface { protected $followLinks = false; protected $mode = 0; protected $minDepth = 0; protected $maxDepth = PHP_INT_MAX; protected $exclude = array(); protected $names = array(); protected $notNames = array(); protected $contains = array(); protected $notContains = array(); protected $sizes = array(); protected $dates = array(); protected $filters = array(); protected $sort = false; protected $paths = array(); protected $notPaths = array(); protected $ignoreUnreadableDirs = false; private static $areSupported = array(); /** * {@inheritdoc} */ public function isSupported() { $name = $this->getName(); if (!array_key_exists($name, self::$areSupported)) { self::$areSupported[$name] = $this->canBeUsed(); } return self::$areSupported[$name]; } /** * {@inheritdoc} */ public function setFollowLinks($followLinks) { $this->followLinks = $followLinks; return $this; } /** * {@inheritdoc} */ public function setMode($mode) { $this->mode = $mode; return $this; } /** * {@inheritdoc} */ public function setDepths(array $depths) { $this->minDepth = 0; $this->maxDepth = PHP_INT_MAX; foreach ($depths as $comparator) { switch ($comparator->getOperator()) { case '>': $this->minDepth = $comparator->getTarget() + 1; break; case '>=': $this->minDepth = $comparator->getTarget(); break; case '<': $this->maxDepth = $comparator->getTarget() - 1; break; case '<=': $this->maxDepth = $comparator->getTarget(); break; default: $this->minDepth = $this->maxDepth = $comparator->getTarget(); } } return $this; } /** * {@inheritdoc} */ public function setExclude(array $exclude) { $this->exclude = $exclude; return $this; } /** * {@inheritdoc} */ public function setNames(array $names) { $this->names = $names; return $this; } /** * {@inheritdoc} */ public function setNotNames(array $notNames) { $this->notNames = $notNames; return $this; } /** * {@inheritdoc} */ public function setContains(array $contains) { $this->contains = $contains; return $this; } /** * {@inheritdoc} */ public function setNotContains(array $notContains) { $this->notContains = $notContains; return $this; } /** * {@inheritdoc} */ public function setSizes(array $sizes) { $this->sizes = $sizes; return $this; } /** * {@inheritdoc} */ public function setDates(array $dates) { $this->dates = $dates; return $this; } /** * {@inheritdoc} */ public function setFilters(array $filters) { $this->filters = $filters; return $this; } /** * {@inheritdoc} */ public function setSort($sort) { $this->sort = $sort; return $this; } /** * {@inheritdoc} */ public function setPath(array $paths) { $this->paths = $paths; return $this; } /** * {@inheritdoc} */ public function setNotPath(array $notPaths) { $this->notPaths = $notPaths; return $this; } /** * {@inheritdoc} */ public function ignoreUnreadableDirs($ignore = true) { $this->ignoreUnreadableDirs = (bool) $ignore; return $this; } /** * Returns whether the adapter is supported in the current environment. * * This method should be implemented in all adapters. Do not implement * isSupported in the adapters as the generic implementation provides a cache * layer. * * @see isSupported() * * @return bool Whether the adapter is supported */ abstract protected function canBeUsed(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; /** * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ interface AdapterInterface { /** * @param bool $followLinks * * @return $this */ public function setFollowLinks($followLinks); /** * @param int $mode * * @return $this */ public function setMode($mode); /** * @return $this */ public function setExclude(array $exclude); /** * @return $this */ public function setDepths(array $depths); /** * @return $this */ public function setNames(array $names); /** * @return $this */ public function setNotNames(array $notNames); /** * @return $this */ public function setContains(array $contains); /** * @return $this */ public function setNotContains(array $notContains); /** * @return $this */ public function setSizes(array $sizes); /** * @return $this */ public function setDates(array $dates); /** * @return $this */ public function setFilters(array $filters); /** * @param \Closure|int $sort * * @return $this */ public function setSort($sort); /** * @return $this */ public function setPath(array $paths); /** * @return $this */ public function setNotPath(array $notPaths); /** * @param bool $ignore * * @return $this */ public function ignoreUnreadableDirs($ignore = true); /** * @param string $dir * * @return \Iterator Result iterator */ public function searchInDirectory($dir); /** * Tests adapter support for current platform. * * @return bool */ public function isSupported(); /** * Returns adapter name. * * @return string */ public function getName(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; @trigger_error('The '.__NAMESPACE__.'\BsdFindAdapter class is deprecated since Symfony 2.8 and will be removed in 3.0. Use directly the Finder class instead.', E_USER_DEPRECATED); use Symfony\Component\Finder\Expression\Expression; use Symfony\Component\Finder\Iterator\SortableIterator; use Symfony\Component\Finder\Shell\Command; use Symfony\Component\Finder\Shell\Shell; /** * Shell engine implementation using BSD find command. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. Use Finder instead. */ class BsdFindAdapter extends AbstractFindAdapter { /** * {@inheritdoc} */ public function getName() { return 'bsd_find'; } /** * {@inheritdoc} */ protected function canBeUsed() { return \in_array($this->shell->getType(), array(Shell::TYPE_BSD, Shell::TYPE_DARWIN)) && parent::canBeUsed(); } /** * {@inheritdoc} */ protected function buildFormatSorting(Command $command, $sort) { switch ($sort) { case SortableIterator::SORT_BY_NAME: $command->ins('sort')->add('| sort'); return; case SortableIterator::SORT_BY_TYPE: $format = '%HT'; break; case SortableIterator::SORT_BY_ACCESSED_TIME: $format = '%a'; break; case SortableIterator::SORT_BY_CHANGED_TIME: $format = '%c'; break; case SortableIterator::SORT_BY_MODIFIED_TIME: $format = '%m'; break; default: throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort)); } $command ->add('-print0 | xargs -0 stat -f') ->arg($format.'%t%N') ->add('| sort | cut -f 2'); } /** * {@inheritdoc} */ protected function buildFindCommand(Command $command, $dir) { parent::buildFindCommand($command, $dir)->addAtIndex('-E', 1); return $command; } /** * {@inheritdoc} */ protected function buildContentFiltering(Command $command, array $contains, $not = false) { foreach ($contains as $contain) { $expr = Expression::create($contain); // todo: avoid forking process for each $pattern by using multiple -e options $command ->add('| grep -v \'^$\'') ->add('| xargs -I{} grep -I') ->add($expr->isCaseSensitive() ? null : '-i') ->add($not ? '-L' : '-l') ->add('-Ee')->arg($expr->renderPattern()) ->add('{}') ; } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; @trigger_error('The '.__NAMESPACE__.'\AbstractFindAdapter class is deprecated since Symfony 2.8 and will be removed in 3.0. Use directly the Finder class instead.', E_USER_DEPRECATED); use Symfony\Component\Finder\Comparator\DateComparator; use Symfony\Component\Finder\Comparator\NumberComparator; use Symfony\Component\Finder\Exception\AccessDeniedException; use Symfony\Component\Finder\Expression\Expression; use Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Shell\Command; use Symfony\Component\Finder\Shell\Shell; /** * Shell engine implementation using GNU find command. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. Use Finder instead. */ abstract class AbstractFindAdapter extends AbstractAdapter { protected $shell; public function __construct() { $this->shell = new Shell(); } /** * {@inheritdoc} */ public function searchInDirectory($dir) { // having "/../" in path make find fail $dir = realpath($dir); // searching directories containing or not containing strings leads to no result if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode && ($this->contains || $this->notContains)) { return new Iterator\FilePathsIterator(array(), $dir); } $command = Command::create(); $find = $this->buildFindCommand($command, $dir); if ($this->followLinks) { $find->add('-follow'); } $find->add('-mindepth')->add($this->minDepth + 1); if (PHP_INT_MAX !== $this->maxDepth) { $find->add('-maxdepth')->add($this->maxDepth + 1); } if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode) { $find->add('-type d'); } elseif (Iterator\FileTypeFilterIterator::ONLY_FILES === $this->mode) { $find->add('-type f'); } $this->buildNamesFiltering($find, $this->names); $this->buildNamesFiltering($find, $this->notNames, true); $this->buildPathsFiltering($find, $dir, $this->paths); $this->buildPathsFiltering($find, $dir, $this->notPaths, true); $this->buildSizesFiltering($find, $this->sizes); $this->buildDatesFiltering($find, $this->dates); $useGrep = $this->shell->testCommand('grep') && $this->shell->testCommand('xargs'); $useSort = \is_int($this->sort) && $this->shell->testCommand('sort') && $this->shell->testCommand('cut'); if ($useGrep && ($this->contains || $this->notContains)) { $grep = $command->ins('grep'); $this->buildContentFiltering($grep, $this->contains); $this->buildContentFiltering($grep, $this->notContains, true); } if ($useSort) { $this->buildSorting($command, $this->sort); } $command->setErrorHandler( $this->ignoreUnreadableDirs // If directory is unreadable and finder is set to ignore it, `stderr` is ignored. ? function ($stderr) { } : function ($stderr) { throw new AccessDeniedException($stderr); } ); $paths = $this->shell->testCommand('uniq') ? $command->add('| uniq')->execute() : array_unique($command->execute()); $iterator = new Iterator\FilePathsIterator($paths, $dir); if ($this->exclude) { $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude); } if (!$useGrep && ($this->contains || $this->notContains)) { $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains); } if ($this->filters) { $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); } if (!$useSort && $this->sort) { $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort); $iterator = $iteratorAggregate->getIterator(); } return $iterator; } /** * {@inheritdoc} */ protected function canBeUsed() { return $this->shell->testCommand('find'); } /** * @param Command $command * @param string $dir * * @return Command */ protected function buildFindCommand(Command $command, $dir) { return $command ->ins('find') ->add('find ') ->arg($dir) ->add('-noleaf'); // the -noleaf option is required for filesystems that don't follow the '.' and '..' conventions } /** * @param Command $command * @param string[] $names * @param bool $not */ private function buildNamesFiltering(Command $command, array $names, $not = false) { if (0 === \count($names)) { return; } $command->add($not ? '-not' : null)->cmd('('); foreach ($names as $i => $name) { $expr = Expression::create($name); // Find does not support expandable globs ("*.{a,b}" syntax). if ($expr->isGlob() && $expr->getGlob()->isExpandable()) { $expr = Expression::create($expr->getGlob()->toRegex(false)); } // Fixes 'not search' and 'full path matching' regex problems. // - Jokers '.' are replaced by [^/]. // - We add '[^/]*' before and after regex (if no ^|$ flags are present). if ($expr->isRegex()) { $regex = $expr->getRegex(); $regex->prepend($regex->hasStartFlag() ? '/' : '/[^/]*') ->setStartFlag(false) ->setStartJoker(true) ->replaceJokers('[^/]'); if (!$regex->hasEndFlag() || $regex->hasEndJoker()) { $regex->setEndJoker(false)->append('[^/]*'); } } $command ->add($i > 0 ? '-or' : null) ->add($expr->isRegex() ? ($expr->isCaseSensitive() ? '-regex' : '-iregex') : ($expr->isCaseSensitive() ? '-name' : '-iname') ) ->arg($expr->renderPattern()); } $command->cmd(')'); } /** * @param Command $command * @param string $dir * @param string[] $paths * @param bool $not */ private function buildPathsFiltering(Command $command, $dir, array $paths, $not = false) { if (0 === \count($paths)) { return; } $command->add($not ? '-not' : null)->cmd('('); foreach ($paths as $i => $path) { $expr = Expression::create($path); // Find does not support expandable globs ("*.{a,b}" syntax). if ($expr->isGlob() && $expr->getGlob()->isExpandable()) { $expr = Expression::create($expr->getGlob()->toRegex(false)); } // Fixes 'not search' regex problems. if ($expr->isRegex()) { $regex = $expr->getRegex(); $regex->prepend($regex->hasStartFlag() ? preg_quote($dir).\DIRECTORY_SEPARATOR : '.*')->setEndJoker(!$regex->hasEndFlag()); } else { $expr->prepend('*')->append('*'); } $command ->add($i > 0 ? '-or' : null) ->add($expr->isRegex() ? ($expr->isCaseSensitive() ? '-regex' : '-iregex') : ($expr->isCaseSensitive() ? '-path' : '-ipath') ) ->arg($expr->renderPattern()); } $command->cmd(')'); } /** * @param Command $command * @param NumberComparator[] $sizes */ private function buildSizesFiltering(Command $command, array $sizes) { foreach ($sizes as $i => $size) { $command->add($i > 0 ? '-and' : null); switch ($size->getOperator()) { case '<=': $command->add('-size -'.($size->getTarget() + 1).'c'); break; case '>=': $command->add('-size +'.($size->getTarget() - 1).'c'); break; case '>': $command->add('-size +'.$size->getTarget().'c'); break; case '!=': $command->add('-size -'.$size->getTarget().'c'); $command->add('-size +'.$size->getTarget().'c'); break; case '<': default: $command->add('-size -'.$size->getTarget().'c'); } } } /** * @param Command $command * @param DateComparator[] $dates */ private function buildDatesFiltering(Command $command, array $dates) { foreach ($dates as $i => $date) { $command->add($i > 0 ? '-and' : null); $mins = (int) round((time() - $date->getTarget()) / 60); if (0 > $mins) { // mtime is in the future $command->add(' -mmin -0'); // we will have no result so we don't need to continue return; } switch ($date->getOperator()) { case '<=': $command->add('-mmin +'.($mins - 1)); break; case '>=': $command->add('-mmin -'.($mins + 1)); break; case '>': $command->add('-mmin -'.$mins); break; case '!=': $command->add('-mmin +'.$mins.' -or -mmin -'.$mins); break; case '<': default: $command->add('-mmin +'.$mins); } } } /** * @param Command $command * @param string $sort * * @throws \InvalidArgumentException */ private function buildSorting(Command $command, $sort) { $this->buildFormatSorting($command, $sort); } /** * @param Command $command * @param string $sort */ abstract protected function buildFormatSorting(Command $command, $sort); /** * @param Command $command * @param array $contains * @param bool $not */ abstract protected function buildContentFiltering(Command $command, array $contains, $not = false); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; @trigger_error('The '.__NAMESPACE__.'\GnuFindAdapter class is deprecated since Symfony 2.8 and will be removed in 3.0. Use directly the Finder class instead.', E_USER_DEPRECATED); use Symfony\Component\Finder\Expression\Expression; use Symfony\Component\Finder\Iterator\SortableIterator; use Symfony\Component\Finder\Shell\Command; use Symfony\Component\Finder\Shell\Shell; /** * Shell engine implementation using GNU find command. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. Use Finder instead. */ class GnuFindAdapter extends AbstractFindAdapter { /** * {@inheritdoc} */ public function getName() { return 'gnu_find'; } /** * {@inheritdoc} */ protected function buildFormatSorting(Command $command, $sort) { switch ($sort) { case SortableIterator::SORT_BY_NAME: $command->ins('sort')->add('| sort'); return; case SortableIterator::SORT_BY_TYPE: $format = '%y'; break; case SortableIterator::SORT_BY_ACCESSED_TIME: $format = '%A@'; break; case SortableIterator::SORT_BY_CHANGED_TIME: $format = '%C@'; break; case SortableIterator::SORT_BY_MODIFIED_TIME: $format = '%T@'; break; default: throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort)); } $command ->get('find') ->add('-printf') ->arg($format.' %h/%f\\n') ->add('| sort | cut') ->arg('-d ') ->arg('-f2-') ; } /** * {@inheritdoc} */ protected function canBeUsed() { return Shell::TYPE_UNIX === $this->shell->getType() && parent::canBeUsed(); } /** * {@inheritdoc} */ protected function buildFindCommand(Command $command, $dir) { return parent::buildFindCommand($command, $dir)->add('-regextype posix-extended'); } /** * {@inheritdoc} */ protected function buildContentFiltering(Command $command, array $contains, $not = false) { foreach ($contains as $contain) { $expr = Expression::create($contain); // todo: avoid forking process for each $pattern by using multiple -e options $command ->add('| xargs -I{} -r grep -I') ->add($expr->isCaseSensitive() ? null : '-i') ->add($not ? '-L' : '-l') ->add('-Ee')->arg($expr->renderPattern()) ->add('{}') ; } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Adapter; @trigger_error('The '.__NAMESPACE__.'\PhpAdapter class is deprecated since Symfony 2.8 and will be removed in 3.0. Use directly the Finder class instead.', E_USER_DEPRECATED); use Symfony\Component\Finder\Iterator; /** * PHP finder engine implementation. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. Use Finder instead. */ class PhpAdapter extends AbstractAdapter { /** * {@inheritdoc} */ public function searchInDirectory($dir) { $flags = \RecursiveDirectoryIterator::SKIP_DOTS; if ($this->followLinks) { $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS; } $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs); if ($this->exclude) { $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude); } $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); if ($this->minDepth > 0 || $this->maxDepth < PHP_INT_MAX) { $iterator = new Iterator\DepthRangeFilterIterator($iterator, $this->minDepth, $this->maxDepth); } if ($this->mode) { $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode); } if ($this->names || $this->notNames) { $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames); } if ($this->contains || $this->notContains) { $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains); } if ($this->sizes) { $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes); } if ($this->dates) { $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates); } if ($this->filters) { $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); } if ($this->paths || $this->notPaths) { $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths); } if ($this->sort) { $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort); $iterator = $iteratorAggregate->getIterator(); } return $iterator; } /** * {@inheritdoc} */ public function getName() { return 'php'; } /** * {@inheritdoc} */ protected function canBeUsed() { return true; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Glob; /** * FilenameFilterIterator filters files by patterns (a regexp, a glob, or a string). * * @author Fabien Potencier */ class FilenameFilterIterator extends MultiplePcreFilterIterator { /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { return $this->isAccepted($this->current()->getFilename()); } /** * Converts glob to regexp. * * PCRE patterns are left unchanged. * Glob strings are transformed with Glob::toRegex(). * * @param string $str Pattern: glob or regexp * * @return string regexp corresponding to a given glob or regexp */ protected function toRegex($str) { return $this->isRegex($str) ? $str : Glob::toRegex($str); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * FilecontentFilterIterator filters files by their contents using patterns (regexps or strings). * * @author Fabien Potencier * @author Włodzimierz Gajda */ class FilecontentFilterIterator extends MultiplePcreFilterIterator { /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { if (!$this->matchRegexps && !$this->noMatchRegexps) { return true; } $fileinfo = $this->current(); if ($fileinfo->isDir() || !$fileinfo->isReadable()) { return false; } $content = $fileinfo->getContents(); if (!$content) { return false; } return $this->isAccepted($content); } /** * Converts string to regexp if necessary. * * @param string $str Pattern: string or regexp * * @return string regexp corresponding to a given string or regexp */ protected function toRegex($str) { return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * DepthRangeFilterIterator limits the directory depth. * * @author Fabien Potencier */ class DepthRangeFilterIterator extends FilterIterator { private $minDepth = 0; /** * @param \RecursiveIteratorIterator $iterator The Iterator to filter * @param int $minDepth The min depth * @param int $maxDepth The max depth */ public function __construct(\RecursiveIteratorIterator $iterator, $minDepth = 0, $maxDepth = PHP_INT_MAX) { $this->minDepth = $minDepth; $iterator->setMaxDepth(PHP_INT_MAX === $maxDepth ? -1 : $maxDepth); parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { return $this->getInnerIterator()->getDepth() >= $this->minDepth; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; @trigger_error('The '.__NAMESPACE__.'\FilePathsIterator class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); use Symfony\Component\Finder\SplFileInfo; /** * Iterate over shell command result. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class FilePathsIterator extends \ArrayIterator { /** * @var string */ private $baseDir; /** * @var int */ private $baseDirLength; /** * @var string */ private $subPath; /** * @var string */ private $subPathname; /** * @var SplFileInfo */ private $current; /** * @param array $paths List of paths returned by shell command * @param string $baseDir Base dir for relative path building */ public function __construct(array $paths, $baseDir) { $this->baseDir = $baseDir; $this->baseDirLength = \strlen($baseDir); parent::__construct($paths); } /** * @param string $name * @param array $arguments * * @return mixed */ public function __call($name, array $arguments) { return \call_user_func_array(array($this->current(), $name), $arguments); } /** * Return an instance of SplFileInfo with support for relative paths. * * @return SplFileInfo File information */ public function current() { return $this->current; } /** * @return string */ public function key() { return $this->current->getPathname(); } public function next() { parent::next(); $this->buildProperties(); } public function rewind() { parent::rewind(); $this->buildProperties(); } /** * @return string */ public function getSubPath() { return $this->subPath; } /** * @return string */ public function getSubPathname() { return $this->subPathname; } private function buildProperties() { $absolutePath = parent::current(); if ($this->baseDir === substr($absolutePath, 0, $this->baseDirLength)) { $this->subPathname = ltrim(substr($absolutePath, $this->baseDirLength), '/\\'); $dir = \dirname($this->subPathname); $this->subPath = '.' === $dir ? '' : $dir; } else { $this->subPath = $this->subPathname = ''; } $this->current = new SplFileInfo(parent::current(), $this->subPath, $this->subPathname); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * ExcludeDirectoryFilterIterator filters out directories. * * @author Fabien Potencier */ class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator { private $iterator; private $isRecursive; private $excludedDirs = array(); private $excludedPattern; /** * @param \Iterator $iterator The Iterator to filter * @param array $directories An array of directories to exclude */ public function __construct(\Iterator $iterator, array $directories) { $this->iterator = $iterator; $this->isRecursive = $iterator instanceof \RecursiveIterator; $patterns = array(); foreach ($directories as $directory) { $directory = rtrim($directory, '/'); if (!$this->isRecursive || false !== strpos($directory, '/')) { $patterns[] = preg_quote($directory, '#'); } else { $this->excludedDirs[$directory] = true; } } if ($patterns) { $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#'; } parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool True if the value should be kept, false otherwise */ public function accept() { if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) { return false; } if ($this->excludedPattern) { $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath(); $path = str_replace('\\', '/', $path); return !preg_match($this->excludedPattern, $path); } return true; } public function hasChildren() { return $this->isRecursive && $this->iterator->hasChildren(); } public function getChildren() { $children = new self($this->iterator->getChildren(), array()); $children->excludedDirs = $this->excludedDirs; $children->excludedPattern = $this->excludedPattern; return $children; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * FileTypeFilterIterator only keeps files, directories, or both. * * @author Fabien Potencier */ class FileTypeFilterIterator extends FilterIterator { const ONLY_FILES = 1; const ONLY_DIRECTORIES = 2; private $mode; /** * @param \Iterator $iterator The Iterator to filter * @param int $mode The mode (self::ONLY_FILES or self::ONLY_DIRECTORIES) */ public function __construct(\Iterator $iterator, $mode) { $this->mode = $mode; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) { return false; } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) { return false; } return true; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * SortableIterator applies a sort on a given Iterator. * * @author Fabien Potencier */ class SortableIterator implements \IteratorAggregate { const SORT_BY_NAME = 1; const SORT_BY_TYPE = 2; const SORT_BY_ACCESSED_TIME = 3; const SORT_BY_CHANGED_TIME = 4; const SORT_BY_MODIFIED_TIME = 5; private $iterator; private $sort; /** * @param \Traversable $iterator The Iterator to filter * @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback) * * @throws \InvalidArgumentException */ public function __construct(\Traversable $iterator, $sort) { $this->iterator = $iterator; if (self::SORT_BY_NAME === $sort) { $this->sort = function ($a, $b) { return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname()); }; } elseif (self::SORT_BY_TYPE === $sort) { $this->sort = function ($a, $b) { if ($a->isDir() && $b->isFile()) { return -1; } elseif ($a->isFile() && $b->isDir()) { return 1; } return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname()); }; } elseif (self::SORT_BY_ACCESSED_TIME === $sort) { $this->sort = function ($a, $b) { return $a->getATime() - $b->getATime(); }; } elseif (self::SORT_BY_CHANGED_TIME === $sort) { $this->sort = function ($a, $b) { return $a->getCTime() - $b->getCTime(); }; } elseif (self::SORT_BY_MODIFIED_TIME === $sort) { $this->sort = function ($a, $b) { return $a->getMTime() - $b->getMTime(); }; } elseif (\is_callable($sort)) { $this->sort = $sort; } else { throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.'); } } public function getIterator() { $array = iterator_to_array($this->iterator, true); uasort($array, $this->sort); return new \ArrayIterator($array); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Exception\AccessDeniedException; use Symfony\Component\Finder\SplFileInfo; /** * Extends the \RecursiveDirectoryIterator to support relative paths. * * @author Victor Berchet */ class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator { /** * @var bool */ private $ignoreUnreadableDirs; /** * @var bool */ private $rewindable; // these 3 properties take part of the performance optimization to avoid redoing the same work in all iterations private $rootPath; private $subPath; private $directorySeparator = '/'; /** * @param string $path * @param int $flags * @param bool $ignoreUnreadableDirs * * @throws \RuntimeException */ public function __construct($path, $flags, $ignoreUnreadableDirs = false) { if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) { throw new \RuntimeException('This iterator only support returning current as fileinfo.'); } parent::__construct($path, $flags); $this->ignoreUnreadableDirs = $ignoreUnreadableDirs; $this->rootPath = (string) $path; if ('/' !== \DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) { $this->directorySeparator = \DIRECTORY_SEPARATOR; } } /** * Return an instance of SplFileInfo with support for relative paths. * * @return SplFileInfo File information */ public function current() { // the logic here avoids redoing the same work in all iterations if (null === $subPathname = $this->subPath) { $subPathname = $this->subPath = (string) $this->getSubPath(); } if ('' !== $subPathname) { $subPathname .= $this->directorySeparator; } $subPathname .= $this->getFilename(); return new SplFileInfo($this->rootPath.$this->directorySeparator.$subPathname, $this->subPath, $subPathname); } /** * @return \RecursiveIterator * * @throws AccessDeniedException */ public function getChildren() { try { $children = parent::getChildren(); if ($children instanceof self) { // parent method will call the constructor with default arguments, so unreadable dirs won't be ignored anymore $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs; // performance optimization to avoid redoing the same work in all children $children->rewindable = &$this->rewindable; $children->rootPath = $this->rootPath; } return $children; } catch (\UnexpectedValueException $e) { if ($this->ignoreUnreadableDirs) { // If directory is unreadable and finder is set to ignore it, a fake empty content is returned. return new \RecursiveArrayIterator(array()); } else { throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e); } } } /** * Do nothing for non rewindable stream. */ public function rewind() { if (false === $this->isRewindable()) { return; } // @see https://bugs.php.net/68557 if (\PHP_VERSION_ID < 50523 || \PHP_VERSION_ID >= 50600 && \PHP_VERSION_ID < 50607) { parent::next(); } parent::rewind(); } /** * Checks if the stream is rewindable. * * @return bool true when the stream is rewindable, false otherwise */ public function isRewindable() { if (null !== $this->rewindable) { return $this->rewindable; } // workaround for an HHVM bug, should be removed when https://github.com/facebook/hhvm/issues/7281 is fixed if ('' === $this->getPath()) { return $this->rewindable = false; } if (false !== $stream = @opendir($this->getPath())) { $infos = stream_get_meta_data($stream); closedir($stream); if ($infos['seekable']) { return $this->rewindable = true; } } return $this->rewindable = false; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * PathFilterIterator filters files by path patterns (e.g. some/special/dir). * * @author Fabien Potencier * @author Włodzimierz Gajda */ class PathFilterIterator extends MultiplePcreFilterIterator { /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $filename = $this->current()->getRelativePathname(); if ('\\' === \DIRECTORY_SEPARATOR) { $filename = str_replace('\\', '/', $filename); } return $this->isAccepted($filename); } /** * Converts strings to regexp. * * PCRE patterns are left unchanged. * * Default conversion: * 'lorem/ipsum/dolor' ==> 'lorem\/ipsum\/dolor/' * * Use only / as directory separator (on Windows also). * * @param string $str Pattern: regexp or dirname * * @return string regexp corresponding to a given string or regexp */ protected function toRegex($str) { return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * CustomFilterIterator filters files by applying anonymous functions. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @author Fabien Potencier */ class CustomFilterIterator extends FilterIterator { private $filters = array(); /** * @param \Iterator $iterator The Iterator to filter * @param callable[] $filters An array of PHP callbacks * * @throws \InvalidArgumentException */ public function __construct(\Iterator $iterator, array $filters) { foreach ($filters as $filter) { if (!\is_callable($filter)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } } $this->filters = $filters; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); foreach ($this->filters as $filter) { if (false === \call_user_func($filter, $fileinfo)) { return false; } } return true; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * This iterator just overrides the rewind method in order to correct a PHP bug, * which existed before version 5.5.23/5.6.7. * * @see https://bugs.php.net/68557 * * @author Alex Bogomazov */ abstract class FilterIterator extends \FilterIterator { /** * This is a workaround for the problem with \FilterIterator leaving inner \FilesystemIterator in wrong state after * rewind in some cases. * * @see FilterIterator::rewind() */ public function rewind() { if (\PHP_VERSION_ID > 50607 || (\PHP_VERSION_ID > 50523 && \PHP_VERSION_ID < 50600)) { parent::rewind(); return; } $iterator = $this; while ($iterator instanceof \OuterIterator) { $innerIterator = $iterator->getInnerIterator(); if ($innerIterator instanceof RecursiveDirectoryIterator) { // this condition is necessary for iterators to work properly with non-local filesystems like ftp if ($innerIterator->isRewindable()) { $innerIterator->next(); $innerIterator->rewind(); } } elseif ($innerIterator instanceof \FilesystemIterator) { $innerIterator->next(); $innerIterator->rewind(); } $iterator = $innerIterator; } parent::rewind(); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * MultiplePcreFilterIterator filters files using patterns (regexps, globs or strings). * * @author Fabien Potencier */ abstract class MultiplePcreFilterIterator extends FilterIterator { protected $matchRegexps = array(); protected $noMatchRegexps = array(); /** * @param \Iterator $iterator The Iterator to filter * @param array $matchPatterns An array of patterns that need to match * @param array $noMatchPatterns An array of patterns that need to not match */ public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns) { foreach ($matchPatterns as $pattern) { $this->matchRegexps[] = $this->toRegex($pattern); } foreach ($noMatchPatterns as $pattern) { $this->noMatchRegexps[] = $this->toRegex($pattern); } parent::__construct($iterator); } /** * Checks whether the string is accepted by the regex filters. * * If there is no regexps defined in the class, this method will accept the string. * Such case can be handled by child classes before calling the method if they want to * apply a different behavior. * * @param string $string The string to be matched against filters * * @return bool */ protected function isAccepted($string) { // should at least not match one rule to exclude foreach ($this->noMatchRegexps as $regex) { if (preg_match($regex, $string)) { return false; } } // should at least match one rule if ($this->matchRegexps) { foreach ($this->matchRegexps as $regex) { if (preg_match($regex, $string)) { return true; } } return false; } // If there is no match rules, the file is accepted return true; } /** * Checks whether the string is a regex. * * @param string $str * * @return bool Whether the given string is a regex */ protected function isRegex($str) { if (preg_match('/^(.{3,}?)[imsxuADU]*$/', $str, $m)) { $start = substr($m[1], 0, 1); $end = substr($m[1], -1); if ($start === $end) { return !preg_match('/[*?[:alnum:] \\\\]/', $start); } foreach (array(array('{', '}'), array('(', ')'), array('[', ']'), array('<', '>')) as $delimiters) { if ($start === $delimiters[0] && $end === $delimiters[1]) { return true; } } } return false; } /** * Converts string into regexp. * * @param string $str Pattern * * @return string regexp corresponding to a given string */ abstract protected function toRegex($str); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Comparator\DateComparator; /** * DateRangeFilterIterator filters out files that are not in the given date range (last modified dates). * * @author Fabien Potencier */ class DateRangeFilterIterator extends FilterIterator { private $comparators = array(); /** * @param \Iterator $iterator The Iterator to filter * @param DateComparator[] $comparators An array of DateComparator instances */ public function __construct(\Iterator $iterator, array $comparators) { $this->comparators = $comparators; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); if (!file_exists($fileinfo->getPathname())) { return false; } $filedate = $fileinfo->getMTime(); foreach ($this->comparators as $compare) { if (!$compare->test($filedate)) { return false; } } return true; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Comparator\NumberComparator; /** * SizeRangeFilterIterator filters out files that are not in the given size range. * * @author Fabien Potencier */ class SizeRangeFilterIterator extends FilterIterator { private $comparators = array(); /** * @param \Iterator $iterator The Iterator to filter * @param NumberComparator[] $comparators An array of NumberComparator instances */ public function __construct(\Iterator $iterator, array $comparators) { $this->comparators = $comparators; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); if (!$fileinfo->isFile()) { return true; } $filesize = $fileinfo->getSize(); foreach ($this->comparators as $compare) { if (!$compare->test($filesize)) { return false; } } return true; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Exception; /** * @author Jean-François Simon */ interface ExceptionInterface { /** * @return \Symfony\Component\Finder\Adapter\AdapterInterface */ public function getAdapter(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Exception; /** * @author Jean-François Simon */ class AccessDeniedException extends \UnexpectedValueException { } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Exception; @trigger_error('The '.__NAMESPACE__.'\OperationNotPermitedException class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); /** * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class OperationNotPermitedException extends AdapterFailureException { } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Exception; @trigger_error('The '.__NAMESPACE__.'\AdapterFailureException class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); use Symfony\Component\Finder\Adapter\AdapterInterface; /** * Base exception for all adapter failures. * * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class AdapterFailureException extends \RuntimeException implements ExceptionInterface { private $adapter; /** * @param AdapterInterface $adapter * @param string|null $message * @param \Exception|null $previous */ public function __construct(AdapterInterface $adapter, $message = null, \Exception $previous = null) { $this->adapter = $adapter; parent::__construct($message ?: 'Search failed with "'.$adapter->getName().'" adapter.', $previous); } /** * {@inheritdoc} */ public function getAdapter() { return $this->adapter; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Exception; @trigger_error('The '.__NAMESPACE__.'\ShellCommandFailureException class is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED); use Symfony\Component\Finder\Adapter\AdapterInterface; use Symfony\Component\Finder\Shell\Command; /** * @author Jean-François Simon * * @deprecated since 2.8, to be removed in 3.0. */ class ShellCommandFailureException extends AdapterFailureException { private $command; public function __construct(AdapterInterface $adapter, Command $command, \Exception $previous = null) { $this->command = $command; parent::__construct($adapter, 'Shell command failed: "'.$command->join().'".', $previous); } /** * @return Command */ public function getCommand() { return $this->command; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder; /** * Glob matches globbing patterns against text. * * if match_glob("foo.*", "foo.bar") echo "matched\n"; * * // prints foo.bar and foo.baz * $regex = glob_to_regex("foo.*"); * for (array('foo.bar', 'foo.baz', 'foo', 'bar') as $t) * { * if (/$regex/) echo "matched: $car\n"; * } * * Glob implements glob(3) style matching that can be used to match * against text, rather than fetching names from a filesystem. * * Based on the Perl Text::Glob module. * * @author Fabien Potencier PHP port * @author Richard Clamp Perl version * @copyright 2004-2005 Fabien Potencier * @copyright 2002 Richard Clamp */ class Glob { /** * Returns a regexp which is the equivalent of the glob pattern. * * @param string $glob The glob pattern * @param bool $strictLeadingDot * @param bool $strictWildcardSlash * @param string $delimiter Optional delimiter * * @return string regex The regexp */ public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true, $delimiter = '#') { $firstByte = true; $escaping = false; $inCurlies = 0; $regex = ''; $sizeGlob = \strlen($glob); for ($i = 0; $i < $sizeGlob; ++$i) { $car = $glob[$i]; if ($firstByte) { if ($strictLeadingDot && '.' !== $car) { $regex .= '(?=[^\.])'; } $firstByte = false; } if ('/' === $car) { $firstByte = true; } if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) { $regex .= "\\$car"; } elseif ('*' === $car) { $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); } elseif ('?' === $car) { $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); } elseif ('{' === $car) { $regex .= $escaping ? '\\{' : '('; if (!$escaping) { ++$inCurlies; } } elseif ('}' === $car && $inCurlies) { $regex .= $escaping ? '}' : ')'; if (!$escaping) { --$inCurlies; } } elseif (',' === $car && $inCurlies) { $regex .= $escaping ? ',' : '|'; } elseif ('\\' === $car) { if ($escaping) { $regex .= '\\\\'; $escaping = false; } else { $escaping = true; } continue; } else { $regex .= $car; } $escaping = false; } return $delimiter.'^'.$regex.'$'.$delimiter; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Ctype; /** * Ctype implementation through regex. * * @internal * * @author Gert de Pagter */ final class Ctype { /** * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. * * @see https://php.net/ctype-alnum * * @param string|int $text * * @return bool */ public static function ctype_alnum($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); } /** * Returns TRUE if every character in text is a letter, FALSE otherwise. * * @see https://php.net/ctype-alpha * * @param string|int $text * * @return bool */ public static function ctype_alpha($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); } /** * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. * * @see https://php.net/ctype-cntrl * * @param string|int $text * * @return bool */ public static function ctype_cntrl($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); } /** * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. * * @see https://php.net/ctype-digit * * @param string|int $text * * @return bool */ public static function ctype_digit($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); } /** * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. * * @see https://php.net/ctype-graph * * @param string|int $text * * @return bool */ public static function ctype_graph($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); } /** * Returns TRUE if every character in text is a lowercase letter. * * @see https://php.net/ctype-lower * * @param string|int $text * * @return bool */ public static function ctype_lower($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); } /** * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. * * @see https://php.net/ctype-print * * @param string|int $text * * @return bool */ public static function ctype_print($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); } /** * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. * * @see https://php.net/ctype-punct * * @param string|int $text * * @return bool */ public static function ctype_punct($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); } /** * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. * * @see https://php.net/ctype-space * * @param string|int $text * * @return bool */ public static function ctype_space($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); } /** * Returns TRUE if every character in text is an uppercase letter. * * @see https://php.net/ctype-upper * * @param string|int $text * * @return bool */ public static function ctype_upper($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); } /** * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. * * @see https://php.net/ctype-xdigit * * @param string|int $text * * @return bool */ public static function ctype_xdigit($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); } /** * Converts integers to their char versions according to normal ctype behaviour, if needed. * * If an integer between -128 and 255 inclusive is provided, * it is interpreted as the ASCII value of a single character * (negative values have 256 added in order to allow characters in the Extended ASCII range). * Any other integer is interpreted as a string containing the decimal digits of the integer. * * @param string|int $int * * @return mixed */ private static function convert_int_to_char_for_ctype($int) { if (!\is_int($int)) { return $int; } if ($int < -128 || $int > 255) { return (string) $int; } if ($int < 0) { $int += 256; } return \chr($int); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Ctype as p; if (!function_exists('ctype_alnum')) { function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } function ctype_digit($text) { return p\Ctype::ctype_digit($text); } function ctype_graph($text) { return p\Ctype::ctype_graph($text); } function ctype_lower($text) { return p\Ctype::ctype_lower($text); } function ctype_print($text) { return p\Ctype::ctype_print($text); } function ctype_punct($text) { return p\Ctype::ctype_punct($text); } function ctype_space($text) { return p\Ctype::ctype_space($text); } function ctype_upper($text) { return p\Ctype::ctype_upper($text); } function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Mbstring; /** * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. * * Implemented: * - mb_chr - Returns a specific character from its Unicode code point * - mb_convert_encoding - Convert character encoding * - mb_convert_variables - Convert character code in variable(s) * - mb_decode_mimeheader - Decode string in MIME header field * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED * - mb_decode_numericentity - Decode HTML numeric string reference to character * - mb_encode_numericentity - Encode character to HTML numeric string reference * - mb_convert_case - Perform case folding on a string * - mb_detect_encoding - Detect character encoding * - mb_get_info - Get internal settings of mbstring * - mb_http_input - Detect HTTP input character encoding * - mb_http_output - Set/Get HTTP output character encoding * - mb_internal_encoding - Set/Get internal character encoding * - mb_list_encodings - Returns an array of all supported encodings * - mb_ord - Returns the Unicode code point of a character * - mb_output_handler - Callback function converts character encoding in output buffer * - mb_scrub - Replaces ill-formed byte sequences with substitute characters * - mb_strlen - Get string length * - mb_strpos - Find position of first occurrence of string in a string * - mb_strrpos - Find position of last occurrence of a string in a string * - mb_str_split - Convert a string to an array * - mb_strtolower - Make a string lowercase * - mb_strtoupper - Make a string uppercase * - mb_substitute_character - Set/Get substitution character * - mb_substr - Get part of string * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive * - mb_stristr - Finds first occurrence of a string within another, case insensitive * - mb_strrchr - Finds the last occurrence of a character in a string within another * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive * - mb_strstr - Finds first occurrence of a string within another * - mb_strwidth - Return width of string * - mb_substr_count - Count the number of substring occurrences * * Not implemented: * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) * - mb_ereg_* - Regular expression with multibyte support * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable * - mb_preferred_mime_name - Get MIME charset string * - mb_regex_encoding - Returns current encoding for multibyte regex as string * - mb_regex_set_options - Set/Get the default options for mbregex functions * - mb_send_mail - Send encoded mail * - mb_split - Split multibyte string using regular expression * - mb_strcut - Get part of string * - mb_strimwidth - Get truncated string with specified width * * @author Nicolas Grekas * * @internal */ final class Mbstring { const MB_CASE_FOLD = PHP_INT_MAX; private static $encodingList = array('ASCII', 'UTF-8'); private static $language = 'neutral'; private static $internalEncoding = 'UTF-8'; private static $caseFold = array( array('µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"), array('μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'), ); public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) { if (\is_array($fromEncoding) || false !== strpos($fromEncoding, ',')) { $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); } else { $fromEncoding = self::getEncoding($fromEncoding); } $toEncoding = self::getEncoding($toEncoding); if ('BASE64' === $fromEncoding) { $s = base64_decode($s); $fromEncoding = $toEncoding; } if ('BASE64' === $toEncoding) { return base64_encode($s); } if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { $fromEncoding = 'Windows-1252'; } if ('UTF-8' !== $fromEncoding) { $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s); } return preg_replace_callback('/[\x80-\xFF]+/', array(__CLASS__, 'html_encoding_callback'), $s); } if ('HTML-ENTITIES' === $fromEncoding) { $s = html_entity_decode($s, ENT_COMPAT, 'UTF-8'); $fromEncoding = 'UTF-8'; } return iconv($fromEncoding, $toEncoding.'//IGNORE', $s); } public static function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null) { $vars = array(&$a, &$b, &$c, &$d, &$e, &$f); $ok = true; array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) { if (false === $v = Mbstring::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { $ok = false; } }); return $ok ? $fromEncoding : false; } public static function mb_decode_mimeheader($s) { return iconv_mime_decode($s, 2, self::$internalEncoding); } public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) { trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', E_USER_WARNING); } public static function mb_decode_numericentity($s, $convmap, $encoding = null) { if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) { trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING); return null; } if (!\is_array($convmap) || !$convmap) { return false; } if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING); return ''; // Instead of null (cf. mb_encode_numericentity). } $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $cnt = floor(\count($convmap) / 4) * 4; for ($i = 0; $i < $cnt; $i += 4) { // collector_decode_htmlnumericentity ignores $convmap[$i + 3] $convmap[$i] += $convmap[$i + 2]; $convmap[$i + 1] += $convmap[$i + 2]; } $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) { $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; for ($i = 0; $i < $cnt; $i += 4) { if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { return Mbstring::mb_chr($c - $convmap[$i + 2]); } } return $m[0]; }, $s); if (null === $encoding) { return $s; } return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) { if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) { trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING); return null; } if (!\is_array($convmap) || !$convmap) { return false; } if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING); return null; // Instead of '' (cf. mb_decode_numericentity). } if (null !== $is_hex && !\is_scalar($is_hex)) { trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', E_USER_WARNING); return null; } $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4); $cnt = floor(\count($convmap) / 4) * 4; $i = 0; $len = \strlen($s); $result = ''; while ($i < $len) { $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; $uchr = substr($s, $i, $ulen); $i += $ulen; $c = self::mb_ord($uchr); for ($j = 0; $j < $cnt; $j += 4) { if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; continue 2; } } $result .= $uchr; } if (null === $encoding) { return $result; } return iconv('UTF-8', $encoding.'//IGNORE', $result); } public static function mb_convert_case($s, $mode, $encoding = null) { $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } if (MB_CASE_TITLE == $mode) { static $titleRegexp = null; if (null === $titleRegexp) { $titleRegexp = self::getData('titleCaseRegexp'); } $s = preg_replace_callback($titleRegexp, array(__CLASS__, 'title_case'), $s); } else { if (MB_CASE_UPPER == $mode) { static $upper = null; if (null === $upper) { $upper = self::getData('upperCase'); } $map = $upper; } else { if (self::MB_CASE_FOLD === $mode) { $s = str_replace(self::$caseFold[0], self::$caseFold[1], $s); } static $lower = null; if (null === $lower) { $lower = self::getData('lowerCase'); } $map = $lower; } static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4); $i = 0; $len = \strlen($s); while ($i < $len) { $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; $uchr = substr($s, $i, $ulen); $i += $ulen; if (isset($map[$uchr])) { $uchr = $map[$uchr]; $nlen = \strlen($uchr); if ($nlen == $ulen) { $nlen = $i; do { $s[--$nlen] = $uchr[--$ulen]; } while ($ulen); } else { $s = substr_replace($s, $uchr, $i - $ulen, $ulen); $len += $nlen - $ulen; $i += $nlen - $ulen; } } } } if (null === $encoding) { return $s; } return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_internal_encoding($encoding = null) { if (null === $encoding) { return self::$internalEncoding; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding || false !== @iconv($encoding, $encoding, ' ')) { self::$internalEncoding = $encoding; return true; } return false; } public static function mb_language($lang = null) { if (null === $lang) { return self::$language; } switch ($lang = strtolower($lang)) { case 'uni': case 'neutral': self::$language = $lang; return true; } return false; } public static function mb_list_encodings() { return array('UTF-8'); } public static function mb_encoding_aliases($encoding) { switch (strtoupper($encoding)) { case 'UTF8': case 'UTF-8': return array('utf8'); } return false; } public static function mb_check_encoding($var = null, $encoding = null) { if (null === $encoding) { if (null === $var) { return false; } $encoding = self::$internalEncoding; } return self::mb_detect_encoding($var, array($encoding)) || false !== @iconv($encoding, $encoding, $var); } public static function mb_detect_encoding($str, $encodingList = null, $strict = false) { if (null === $encodingList) { $encodingList = self::$encodingList; } else { if (!\is_array($encodingList)) { $encodingList = array_map('trim', explode(',', $encodingList)); } $encodingList = array_map('strtoupper', $encodingList); } foreach ($encodingList as $enc) { switch ($enc) { case 'ASCII': if (!preg_match('/[\x80-\xFF]/', $str)) { return $enc; } break; case 'UTF8': case 'UTF-8': if (preg_match('//u', $str)) { return 'UTF-8'; } break; default: if (0 === strncmp($enc, 'ISO-8859-', 9)) { return $enc; } } } return false; } public static function mb_detect_order($encodingList = null) { if (null === $encodingList) { return self::$encodingList; } if (!\is_array($encodingList)) { $encodingList = array_map('trim', explode(',', $encodingList)); } $encodingList = array_map('strtoupper', $encodingList); foreach ($encodingList as $enc) { switch ($enc) { default: if (strncmp($enc, 'ISO-8859-', 9)) { return false; } // no break case 'ASCII': case 'UTF8': case 'UTF-8': } } self::$encodingList = $encodingList; return true; } public static function mb_strlen($s, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return \strlen($s); } return @iconv_strlen($s, $encoding); } public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return strpos($haystack, $needle, $offset); } $needle = (string) $needle; if ('' === $needle) { trigger_error(__METHOD__.': Empty delimiter', E_USER_WARNING); return false; } return iconv_strpos($haystack, $needle, $offset, $encoding); } public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return strrpos($haystack, $needle, $offset); } if ($offset != (int) $offset) { $offset = 0; } elseif ($offset = (int) $offset) { if ($offset < 0) { $haystack = self::mb_substr($haystack, 0, $offset, $encoding); $offset = 0; } else { $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding); } } $pos = iconv_strrpos($haystack, $needle, $encoding); return false !== $pos ? $offset + $pos : false; } public static function mb_str_split($string, $split_length = 1, $encoding = null) { if (null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) { trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', E_USER_WARNING); return null; } if ($split_length < 1) { trigger_error('The length of each segment must be greater than zero', E_USER_WARNING); return false; } if (null === $encoding) { $encoding = mb_internal_encoding(); } $result = array(); $length = mb_strlen($string, $encoding); for ($i = 0; $i < $length; $i += $split_length) { $result[] = mb_substr($string, $i, $split_length, $encoding); } return $result; } public static function mb_strtolower($s, $encoding = null) { return self::mb_convert_case($s, MB_CASE_LOWER, $encoding); } public static function mb_strtoupper($s, $encoding = null) { return self::mb_convert_case($s, MB_CASE_UPPER, $encoding); } public static function mb_substitute_character($c = null) { if (0 === strcasecmp($c, 'none')) { return true; } return null !== $c ? false : 'none'; } public static function mb_substr($s, $start, $length = null, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return (string) substr($s, $start, null === $length ? 2147483647 : $length); } if ($start < 0) { $start = iconv_strlen($s, $encoding) + $start; if ($start < 0) { $start = 0; } } if (null === $length) { $length = 2147483647; } elseif ($length < 0) { $length = iconv_strlen($s, $encoding) + $length - $start; if ($length < 0) { return ''; } } return (string) iconv_substr($s, $start, $length, $encoding); } public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); return self::mb_strpos($haystack, $needle, $offset, $encoding); } public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) { $pos = self::mb_stripos($haystack, $needle, 0, $encoding); return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return strrchr($haystack, $needle, $part); } $needle = self::mb_substr($needle, 0, 1, $encoding); $pos = iconv_strrpos($haystack, $needle, $encoding); return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) { $needle = self::mb_substr($needle, 0, 1, $encoding); $pos = self::mb_strripos($haystack, $needle, $encoding); return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); return self::mb_strrpos($haystack, $needle, $offset, $encoding); } public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) { $pos = strpos($haystack, $needle); if (false === $pos) { return false; } if ($part) { return substr($haystack, 0, $pos); } return substr($haystack, $pos); } public static function mb_get_info($type = 'all') { $info = array( 'internal_encoding' => self::$internalEncoding, 'http_output' => 'pass', 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', 'func_overload' => 0, 'func_overload_list' => 'no overload', 'mail_charset' => 'UTF-8', 'mail_header_encoding' => 'BASE64', 'mail_body_encoding' => 'BASE64', 'illegal_chars' => 0, 'encoding_translation' => 'Off', 'language' => self::$language, 'detect_order' => self::$encodingList, 'substitute_character' => 'none', 'strict_detection' => 'Off', ); if ('all' === $type) { return $info; } if (isset($info[$type])) { return $info[$type]; } return false; } public static function mb_http_input($type = '') { return false; } public static function mb_http_output($encoding = null) { return null !== $encoding ? 'pass' === $encoding : 'pass'; } public static function mb_strwidth($s, $encoding = null) { $encoding = self::getEncoding($encoding); if ('UTF-8' !== $encoding) { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); return ($wide << 1) + iconv_strlen($s, 'UTF-8'); } public static function mb_substr_count($haystack, $needle, $encoding = null) { return substr_count($haystack, $needle); } public static function mb_output_handler($contents, $status) { return $contents; } public static function mb_chr($code, $encoding = null) { if (0x80 > $code %= 0x200000) { $s = \chr($code); } elseif (0x800 > $code) { $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); } elseif (0x10000 > $code) { $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); } else { $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); } if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { $s = mb_convert_encoding($s, $encoding, 'UTF-8'); } return $s; } public static function mb_ord($s, $encoding = null) { if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { $s = mb_convert_encoding($s, 'UTF-8', $encoding); } if (1 === \strlen($s)) { return \ord($s); } $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; if (0xF0 <= $code) { return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; } if (0xE0 <= $code) { return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; } if (0xC0 <= $code) { return (($code - 0xC0) << 6) + $s[2] - 0x80; } return $code; } private static function getSubpart($pos, $part, $haystack, $encoding) { if (false === $pos) { return false; } if ($part) { return self::mb_substr($haystack, 0, $pos, $encoding); } return self::mb_substr($haystack, $pos, null, $encoding); } private static function html_encoding_callback(array $m) { $i = 1; $entities = ''; $m = unpack('C*', htmlentities($m[0], ENT_COMPAT, 'UTF-8')); while (isset($m[$i])) { if (0x80 > $m[$i]) { $entities .= \chr($m[$i++]); continue; } if (0xF0 <= $m[$i]) { $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; } elseif (0xE0 <= $m[$i]) { $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; } else { $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; } $entities .= '&#'.$c.';'; } return $entities; } private static function title_case(array $s) { return self::mb_convert_case($s[1], MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], MB_CASE_LOWER, 'UTF-8'); } private static function getData($file) { if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { return require $file; } return false; } private static function getEncoding($encoding) { if (null === $encoding) { return self::$internalEncoding; } $encoding = strtoupper($encoding); if ('8BIT' === $encoding || 'BINARY' === $encoding) { return 'CP850'; } if ('UTF8' === $encoding) { return 'UTF-8'; } return $encoding; } } 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G', 'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K', 'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O', 'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S', 't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W', 'x' => 'X', 'y' => 'Y', 'z' => 'Z', 'µ' => 'Μ', 'à' => 'À', 'á' => 'Á', 'â' => 'Â', 'ã' => 'Ã', 'ä' => 'Ä', 'å' => 'Å', 'æ' => 'Æ', 'ç' => 'Ç', 'è' => 'È', 'é' => 'É', 'ê' => 'Ê', 'ë' => 'Ë', 'ì' => 'Ì', 'í' => 'Í', 'î' => 'Î', 'ï' => 'Ï', 'ð' => 'Ð', 'ñ' => 'Ñ', 'ò' => 'Ò', 'ó' => 'Ó', 'ô' => 'Ô', 'õ' => 'Õ', 'ö' => 'Ö', 'ø' => 'Ø', 'ù' => 'Ù', 'ú' => 'Ú', 'û' => 'Û', 'ü' => 'Ü', 'ý' => 'Ý', 'þ' => 'Þ', 'ÿ' => 'Ÿ', 'ā' => 'Ā', 'ă' => 'Ă', 'ą' => 'Ą', 'ć' => 'Ć', 'ĉ' => 'Ĉ', 'ċ' => 'Ċ', 'č' => 'Č', 'ď' => 'Ď', 'đ' => 'Đ', 'ē' => 'Ē', 'ĕ' => 'Ĕ', 'ė' => 'Ė', 'ę' => 'Ę', 'ě' => 'Ě', 'ĝ' => 'Ĝ', 'ğ' => 'Ğ', 'ġ' => 'Ġ', 'ģ' => 'Ģ', 'ĥ' => 'Ĥ', 'ħ' => 'Ħ', 'ĩ' => 'Ĩ', 'ī' => 'Ī', 'ĭ' => 'Ĭ', 'į' => 'Į', 'ı' => 'I', 'ij' => 'IJ', 'ĵ' => 'Ĵ', 'ķ' => 'Ķ', 'ĺ' => 'Ĺ', 'ļ' => 'Ļ', 'ľ' => 'Ľ', 'ŀ' => 'Ŀ', 'ł' => 'Ł', 'ń' => 'Ń', 'ņ' => 'Ņ', 'ň' => 'Ň', 'ŋ' => 'Ŋ', 'ō' => 'Ō', 'ŏ' => 'Ŏ', 'ő' => 'Ő', 'œ' => 'Œ', 'ŕ' => 'Ŕ', 'ŗ' => 'Ŗ', 'ř' => 'Ř', 'ś' => 'Ś', 'ŝ' => 'Ŝ', 'ş' => 'Ş', 'š' => 'Š', 'ţ' => 'Ţ', 'ť' => 'Ť', 'ŧ' => 'Ŧ', 'ũ' => 'Ũ', 'ū' => 'Ū', 'ŭ' => 'Ŭ', 'ů' => 'Ů', 'ű' => 'Ű', 'ų' => 'Ų', 'ŵ' => 'Ŵ', 'ŷ' => 'Ŷ', 'ź' => 'Ź', 'ż' => 'Ż', 'ž' => 'Ž', 'ſ' => 'S', 'ƀ' => 'Ƀ', 'ƃ' => 'Ƃ', 'ƅ' => 'Ƅ', 'ƈ' => 'Ƈ', 'ƌ' => 'Ƌ', 'ƒ' => 'Ƒ', 'ƕ' => 'Ƕ', 'ƙ' => 'Ƙ', 'ƚ' => 'Ƚ', 'ƞ' => 'Ƞ', 'ơ' => 'Ơ', 'ƣ' => 'Ƣ', 'ƥ' => 'Ƥ', 'ƨ' => 'Ƨ', 'ƭ' => 'Ƭ', 'ư' => 'Ư', 'ƴ' => 'Ƴ', 'ƶ' => 'Ƶ', 'ƹ' => 'Ƹ', 'ƽ' => 'Ƽ', 'ƿ' => 'Ƿ', 'Dž' => 'DŽ', 'dž' => 'DŽ', 'Lj' => 'LJ', 'lj' => 'LJ', 'Nj' => 'NJ', 'nj' => 'NJ', 'ǎ' => 'Ǎ', 'ǐ' => 'Ǐ', 'ǒ' => 'Ǒ', 'ǔ' => 'Ǔ', 'ǖ' => 'Ǖ', 'ǘ' => 'Ǘ', 'ǚ' => 'Ǚ', 'ǜ' => 'Ǜ', 'ǝ' => 'Ǝ', 'ǟ' => 'Ǟ', 'ǡ' => 'Ǡ', 'ǣ' => 'Ǣ', 'ǥ' => 'Ǥ', 'ǧ' => 'Ǧ', 'ǩ' => 'Ǩ', 'ǫ' => 'Ǫ', 'ǭ' => 'Ǭ', 'ǯ' => 'Ǯ', 'Dz' => 'DZ', 'dz' => 'DZ', 'ǵ' => 'Ǵ', 'ǹ' => 'Ǹ', 'ǻ' => 'Ǻ', 'ǽ' => 'Ǽ', 'ǿ' => 'Ǿ', 'ȁ' => 'Ȁ', 'ȃ' => 'Ȃ', 'ȅ' => 'Ȅ', 'ȇ' => 'Ȇ', 'ȉ' => 'Ȉ', 'ȋ' => 'Ȋ', 'ȍ' => 'Ȍ', 'ȏ' => 'Ȏ', 'ȑ' => 'Ȑ', 'ȓ' => 'Ȓ', 'ȕ' => 'Ȕ', 'ȗ' => 'Ȗ', 'ș' => 'Ș', 'ț' => 'Ț', 'ȝ' => 'Ȝ', 'ȟ' => 'Ȟ', 'ȣ' => 'Ȣ', 'ȥ' => 'Ȥ', 'ȧ' => 'Ȧ', 'ȩ' => 'Ȩ', 'ȫ' => 'Ȫ', 'ȭ' => 'Ȭ', 'ȯ' => 'Ȯ', 'ȱ' => 'Ȱ', 'ȳ' => 'Ȳ', 'ȼ' => 'Ȼ', 'ȿ' => 'Ȿ', 'ɀ' => 'Ɀ', 'ɂ' => 'Ɂ', 'ɇ' => 'Ɇ', 'ɉ' => 'Ɉ', 'ɋ' => 'Ɋ', 'ɍ' => 'Ɍ', 'ɏ' => 'Ɏ', 'ɐ' => 'Ɐ', 'ɑ' => 'Ɑ', 'ɒ' => 'Ɒ', 'ɓ' => 'Ɓ', 'ɔ' => 'Ɔ', 'ɖ' => 'Ɖ', 'ɗ' => 'Ɗ', 'ə' => 'Ə', 'ɛ' => 'Ɛ', 'ɜ' => 'Ɜ', 'ɠ' => 'Ɠ', 'ɡ' => 'Ɡ', 'ɣ' => 'Ɣ', 'ɥ' => 'Ɥ', 'ɦ' => 'Ɦ', 'ɨ' => 'Ɨ', 'ɩ' => 'Ɩ', 'ɫ' => 'Ɫ', 'ɬ' => 'Ɬ', 'ɯ' => 'Ɯ', 'ɱ' => 'Ɱ', 'ɲ' => 'Ɲ', 'ɵ' => 'Ɵ', 'ɽ' => 'Ɽ', 'ʀ' => 'Ʀ', 'ʃ' => 'Ʃ', 'ʇ' => 'Ʇ', 'ʈ' => 'Ʈ', 'ʉ' => 'Ʉ', 'ʊ' => 'Ʊ', 'ʋ' => 'Ʋ', 'ʌ' => 'Ʌ', 'ʒ' => 'Ʒ', 'ʞ' => 'Ʞ', 'ͅ' => 'Ι', 'ͱ' => 'Ͱ', 'ͳ' => 'Ͳ', 'ͷ' => 'Ͷ', 'ͻ' => 'Ͻ', 'ͼ' => 'Ͼ', 'ͽ' => 'Ͽ', 'ά' => 'Ά', 'έ' => 'Έ', 'ή' => 'Ή', 'ί' => 'Ί', 'α' => 'Α', 'β' => 'Β', 'γ' => 'Γ', 'δ' => 'Δ', 'ε' => 'Ε', 'ζ' => 'Ζ', 'η' => 'Η', 'θ' => 'Θ', 'ι' => 'Ι', 'κ' => 'Κ', 'λ' => 'Λ', 'μ' => 'Μ', 'ν' => 'Ν', 'ξ' => 'Ξ', 'ο' => 'Ο', 'π' => 'Π', 'ρ' => 'Ρ', 'ς' => 'Σ', 'σ' => 'Σ', 'τ' => 'Τ', 'υ' => 'Υ', 'φ' => 'Φ', 'χ' => 'Χ', 'ψ' => 'Ψ', 'ω' => 'Ω', 'ϊ' => 'Ϊ', 'ϋ' => 'Ϋ', 'ό' => 'Ό', 'ύ' => 'Ύ', 'ώ' => 'Ώ', 'ϐ' => 'Β', 'ϑ' => 'Θ', 'ϕ' => 'Φ', 'ϖ' => 'Π', 'ϗ' => 'Ϗ', 'ϙ' => 'Ϙ', 'ϛ' => 'Ϛ', 'ϝ' => 'Ϝ', 'ϟ' => 'Ϟ', 'ϡ' => 'Ϡ', 'ϣ' => 'Ϣ', 'ϥ' => 'Ϥ', 'ϧ' => 'Ϧ', 'ϩ' => 'Ϩ', 'ϫ' => 'Ϫ', 'ϭ' => 'Ϭ', 'ϯ' => 'Ϯ', 'ϰ' => 'Κ', 'ϱ' => 'Ρ', 'ϲ' => 'Ϲ', 'ϳ' => 'Ϳ', 'ϵ' => 'Ε', 'ϸ' => 'Ϸ', 'ϻ' => 'Ϻ', 'а' => 'А', 'б' => 'Б', 'в' => 'В', 'г' => 'Г', 'д' => 'Д', 'е' => 'Е', 'ж' => 'Ж', 'з' => 'З', 'и' => 'И', 'й' => 'Й', 'к' => 'К', 'л' => 'Л', 'м' => 'М', 'н' => 'Н', 'о' => 'О', 'п' => 'П', 'р' => 'Р', 'с' => 'С', 'т' => 'Т', 'у' => 'У', 'ф' => 'Ф', 'х' => 'Х', 'ц' => 'Ц', 'ч' => 'Ч', 'ш' => 'Ш', 'щ' => 'Щ', 'ъ' => 'Ъ', 'ы' => 'Ы', 'ь' => 'Ь', 'э' => 'Э', 'ю' => 'Ю', 'я' => 'Я', 'ѐ' => 'Ѐ', 'ё' => 'Ё', 'ђ' => 'Ђ', 'ѓ' => 'Ѓ', 'є' => 'Є', 'ѕ' => 'Ѕ', 'і' => 'І', 'ї' => 'Ї', 'ј' => 'Ј', 'љ' => 'Љ', 'њ' => 'Њ', 'ћ' => 'Ћ', 'ќ' => 'Ќ', 'ѝ' => 'Ѝ', 'ў' => 'Ў', 'џ' => 'Џ', 'ѡ' => 'Ѡ', 'ѣ' => 'Ѣ', 'ѥ' => 'Ѥ', 'ѧ' => 'Ѧ', 'ѩ' => 'Ѩ', 'ѫ' => 'Ѫ', 'ѭ' => 'Ѭ', 'ѯ' => 'Ѯ', 'ѱ' => 'Ѱ', 'ѳ' => 'Ѳ', 'ѵ' => 'Ѵ', 'ѷ' => 'Ѷ', 'ѹ' => 'Ѹ', 'ѻ' => 'Ѻ', 'ѽ' => 'Ѽ', 'ѿ' => 'Ѿ', 'ҁ' => 'Ҁ', 'ҋ' => 'Ҋ', 'ҍ' => 'Ҍ', 'ҏ' => 'Ҏ', 'ґ' => 'Ґ', 'ғ' => 'Ғ', 'ҕ' => 'Ҕ', 'җ' => 'Җ', 'ҙ' => 'Ҙ', 'қ' => 'Қ', 'ҝ' => 'Ҝ', 'ҟ' => 'Ҟ', 'ҡ' => 'Ҡ', 'ң' => 'Ң', 'ҥ' => 'Ҥ', 'ҧ' => 'Ҧ', 'ҩ' => 'Ҩ', 'ҫ' => 'Ҫ', 'ҭ' => 'Ҭ', 'ү' => 'Ү', 'ұ' => 'Ұ', 'ҳ' => 'Ҳ', 'ҵ' => 'Ҵ', 'ҷ' => 'Ҷ', 'ҹ' => 'Ҹ', 'һ' => 'Һ', 'ҽ' => 'Ҽ', 'ҿ' => 'Ҿ', 'ӂ' => 'Ӂ', 'ӄ' => 'Ӄ', 'ӆ' => 'Ӆ', 'ӈ' => 'Ӈ', 'ӊ' => 'Ӊ', 'ӌ' => 'Ӌ', 'ӎ' => 'Ӎ', 'ӏ' => 'Ӏ', 'ӑ' => 'Ӑ', 'ӓ' => 'Ӓ', 'ӕ' => 'Ӕ', 'ӗ' => 'Ӗ', 'ә' => 'Ә', 'ӛ' => 'Ӛ', 'ӝ' => 'Ӝ', 'ӟ' => 'Ӟ', 'ӡ' => 'Ӡ', 'ӣ' => 'Ӣ', 'ӥ' => 'Ӥ', 'ӧ' => 'Ӧ', 'ө' => 'Ө', 'ӫ' => 'Ӫ', 'ӭ' => 'Ӭ', 'ӯ' => 'Ӯ', 'ӱ' => 'Ӱ', 'ӳ' => 'Ӳ', 'ӵ' => 'Ӵ', 'ӷ' => 'Ӷ', 'ӹ' => 'Ӹ', 'ӻ' => 'Ӻ', 'ӽ' => 'Ӽ', 'ӿ' => 'Ӿ', 'ԁ' => 'Ԁ', 'ԃ' => 'Ԃ', 'ԅ' => 'Ԅ', 'ԇ' => 'Ԇ', 'ԉ' => 'Ԉ', 'ԋ' => 'Ԋ', 'ԍ' => 'Ԍ', 'ԏ' => 'Ԏ', 'ԑ' => 'Ԑ', 'ԓ' => 'Ԓ', 'ԕ' => 'Ԕ', 'ԗ' => 'Ԗ', 'ԙ' => 'Ԙ', 'ԛ' => 'Ԛ', 'ԝ' => 'Ԝ', 'ԟ' => 'Ԟ', 'ԡ' => 'Ԡ', 'ԣ' => 'Ԣ', 'ԥ' => 'Ԥ', 'ԧ' => 'Ԧ', 'ԩ' => 'Ԩ', 'ԫ' => 'Ԫ', 'ԭ' => 'Ԭ', 'ԯ' => 'Ԯ', 'ա' => 'Ա', 'բ' => 'Բ', 'գ' => 'Գ', 'դ' => 'Դ', 'ե' => 'Ե', 'զ' => 'Զ', 'է' => 'Է', 'ը' => 'Ը', 'թ' => 'Թ', 'ժ' => 'Ժ', 'ի' => 'Ի', 'լ' => 'Լ', 'խ' => 'Խ', 'ծ' => 'Ծ', 'կ' => 'Կ', 'հ' => 'Հ', 'ձ' => 'Ձ', 'ղ' => 'Ղ', 'ճ' => 'Ճ', 'մ' => 'Մ', 'յ' => 'Յ', 'ն' => 'Ն', 'շ' => 'Շ', 'ո' => 'Ո', 'չ' => 'Չ', 'պ' => 'Պ', 'ջ' => 'Ջ', 'ռ' => 'Ռ', 'ս' => 'Ս', 'վ' => 'Վ', 'տ' => 'Տ', 'ր' => 'Ր', 'ց' => 'Ց', 'ւ' => 'Ւ', 'փ' => 'Փ', 'ք' => 'Ք', 'օ' => 'Օ', 'ֆ' => 'Ֆ', 'ᵹ' => 'Ᵹ', 'ᵽ' => 'Ᵽ', 'ḁ' => 'Ḁ', 'ḃ' => 'Ḃ', 'ḅ' => 'Ḅ', 'ḇ' => 'Ḇ', 'ḉ' => 'Ḉ', 'ḋ' => 'Ḋ', 'ḍ' => 'Ḍ', 'ḏ' => 'Ḏ', 'ḑ' => 'Ḑ', 'ḓ' => 'Ḓ', 'ḕ' => 'Ḕ', 'ḗ' => 'Ḗ', 'ḙ' => 'Ḙ', 'ḛ' => 'Ḛ', 'ḝ' => 'Ḝ', 'ḟ' => 'Ḟ', 'ḡ' => 'Ḡ', 'ḣ' => 'Ḣ', 'ḥ' => 'Ḥ', 'ḧ' => 'Ḧ', 'ḩ' => 'Ḩ', 'ḫ' => 'Ḫ', 'ḭ' => 'Ḭ', 'ḯ' => 'Ḯ', 'ḱ' => 'Ḱ', 'ḳ' => 'Ḳ', 'ḵ' => 'Ḵ', 'ḷ' => 'Ḷ', 'ḹ' => 'Ḹ', 'ḻ' => 'Ḻ', 'ḽ' => 'Ḽ', 'ḿ' => 'Ḿ', 'ṁ' => 'Ṁ', 'ṃ' => 'Ṃ', 'ṅ' => 'Ṅ', 'ṇ' => 'Ṇ', 'ṉ' => 'Ṉ', 'ṋ' => 'Ṋ', 'ṍ' => 'Ṍ', 'ṏ' => 'Ṏ', 'ṑ' => 'Ṑ', 'ṓ' => 'Ṓ', 'ṕ' => 'Ṕ', 'ṗ' => 'Ṗ', 'ṙ' => 'Ṙ', 'ṛ' => 'Ṛ', 'ṝ' => 'Ṝ', 'ṟ' => 'Ṟ', 'ṡ' => 'Ṡ', 'ṣ' => 'Ṣ', 'ṥ' => 'Ṥ', 'ṧ' => 'Ṧ', 'ṩ' => 'Ṩ', 'ṫ' => 'Ṫ', 'ṭ' => 'Ṭ', 'ṯ' => 'Ṯ', 'ṱ' => 'Ṱ', 'ṳ' => 'Ṳ', 'ṵ' => 'Ṵ', 'ṷ' => 'Ṷ', 'ṹ' => 'Ṹ', 'ṻ' => 'Ṻ', 'ṽ' => 'Ṽ', 'ṿ' => 'Ṿ', 'ẁ' => 'Ẁ', 'ẃ' => 'Ẃ', 'ẅ' => 'Ẅ', 'ẇ' => 'Ẇ', 'ẉ' => 'Ẉ', 'ẋ' => 'Ẋ', 'ẍ' => 'Ẍ', 'ẏ' => 'Ẏ', 'ẑ' => 'Ẑ', 'ẓ' => 'Ẓ', 'ẕ' => 'Ẕ', 'ẛ' => 'Ṡ', 'ạ' => 'Ạ', 'ả' => 'Ả', 'ấ' => 'Ấ', 'ầ' => 'Ầ', 'ẩ' => 'Ẩ', 'ẫ' => 'Ẫ', 'ậ' => 'Ậ', 'ắ' => 'Ắ', 'ằ' => 'Ằ', 'ẳ' => 'Ẳ', 'ẵ' => 'Ẵ', 'ặ' => 'Ặ', 'ẹ' => 'Ẹ', 'ẻ' => 'Ẻ', 'ẽ' => 'Ẽ', 'ế' => 'Ế', 'ề' => 'Ề', 'ể' => 'Ể', 'ễ' => 'Ễ', 'ệ' => 'Ệ', 'ỉ' => 'Ỉ', 'ị' => 'Ị', 'ọ' => 'Ọ', 'ỏ' => 'Ỏ', 'ố' => 'Ố', 'ồ' => 'Ồ', 'ổ' => 'Ổ', 'ỗ' => 'Ỗ', 'ộ' => 'Ộ', 'ớ' => 'Ớ', 'ờ' => 'Ờ', 'ở' => 'Ở', 'ỡ' => 'Ỡ', 'ợ' => 'Ợ', 'ụ' => 'Ụ', 'ủ' => 'Ủ', 'ứ' => 'Ứ', 'ừ' => 'Ừ', 'ử' => 'Ử', 'ữ' => 'Ữ', 'ự' => 'Ự', 'ỳ' => 'Ỳ', 'ỵ' => 'Ỵ', 'ỷ' => 'Ỷ', 'ỹ' => 'Ỹ', 'ỻ' => 'Ỻ', 'ỽ' => 'Ỽ', 'ỿ' => 'Ỿ', 'ἀ' => 'Ἀ', 'ἁ' => 'Ἁ', 'ἂ' => 'Ἂ', 'ἃ' => 'Ἃ', 'ἄ' => 'Ἄ', 'ἅ' => 'Ἅ', 'ἆ' => 'Ἆ', 'ἇ' => 'Ἇ', 'ἐ' => 'Ἐ', 'ἑ' => 'Ἑ', 'ἒ' => 'Ἒ', 'ἓ' => 'Ἓ', 'ἔ' => 'Ἔ', 'ἕ' => 'Ἕ', 'ἠ' => 'Ἠ', 'ἡ' => 'Ἡ', 'ἢ' => 'Ἢ', 'ἣ' => 'Ἣ', 'ἤ' => 'Ἤ', 'ἥ' => 'Ἥ', 'ἦ' => 'Ἦ', 'ἧ' => 'Ἧ', 'ἰ' => 'Ἰ', 'ἱ' => 'Ἱ', 'ἲ' => 'Ἲ', 'ἳ' => 'Ἳ', 'ἴ' => 'Ἴ', 'ἵ' => 'Ἵ', 'ἶ' => 'Ἶ', 'ἷ' => 'Ἷ', 'ὀ' => 'Ὀ', 'ὁ' => 'Ὁ', 'ὂ' => 'Ὂ', 'ὃ' => 'Ὃ', 'ὄ' => 'Ὄ', 'ὅ' => 'Ὅ', 'ὑ' => 'Ὑ', 'ὓ' => 'Ὓ', 'ὕ' => 'Ὕ', 'ὗ' => 'Ὗ', 'ὠ' => 'Ὠ', 'ὡ' => 'Ὡ', 'ὢ' => 'Ὢ', 'ὣ' => 'Ὣ', 'ὤ' => 'Ὤ', 'ὥ' => 'Ὥ', 'ὦ' => 'Ὦ', 'ὧ' => 'Ὧ', 'ὰ' => 'Ὰ', 'ά' => 'Ά', 'ὲ' => 'Ὲ', 'έ' => 'Έ', 'ὴ' => 'Ὴ', 'ή' => 'Ή', 'ὶ' => 'Ὶ', 'ί' => 'Ί', 'ὸ' => 'Ὸ', 'ό' => 'Ό', 'ὺ' => 'Ὺ', 'ύ' => 'Ύ', 'ὼ' => 'Ὼ', 'ώ' => 'Ώ', 'ᾀ' => 'ᾈ', 'ᾁ' => 'ᾉ', 'ᾂ' => 'ᾊ', 'ᾃ' => 'ᾋ', 'ᾄ' => 'ᾌ', 'ᾅ' => 'ᾍ', 'ᾆ' => 'ᾎ', 'ᾇ' => 'ᾏ', 'ᾐ' => 'ᾘ', 'ᾑ' => 'ᾙ', 'ᾒ' => 'ᾚ', 'ᾓ' => 'ᾛ', 'ᾔ' => 'ᾜ', 'ᾕ' => 'ᾝ', 'ᾖ' => 'ᾞ', 'ᾗ' => 'ᾟ', 'ᾠ' => 'ᾨ', 'ᾡ' => 'ᾩ', 'ᾢ' => 'ᾪ', 'ᾣ' => 'ᾫ', 'ᾤ' => 'ᾬ', 'ᾥ' => 'ᾭ', 'ᾦ' => 'ᾮ', 'ᾧ' => 'ᾯ', 'ᾰ' => 'Ᾰ', 'ᾱ' => 'Ᾱ', 'ᾳ' => 'ᾼ', 'ι' => 'Ι', 'ῃ' => 'ῌ', 'ῐ' => 'Ῐ', 'ῑ' => 'Ῑ', 'ῠ' => 'Ῠ', 'ῡ' => 'Ῡ', 'ῥ' => 'Ῥ', 'ῳ' => 'ῼ', 'ⅎ' => 'Ⅎ', 'ⅰ' => 'Ⅰ', 'ⅱ' => 'Ⅱ', 'ⅲ' => 'Ⅲ', 'ⅳ' => 'Ⅳ', 'ⅴ' => 'Ⅴ', 'ⅵ' => 'Ⅵ', 'ⅶ' => 'Ⅶ', 'ⅷ' => 'Ⅷ', 'ⅸ' => 'Ⅸ', 'ⅹ' => 'Ⅹ', 'ⅺ' => 'Ⅺ', 'ⅻ' => 'Ⅻ', 'ⅼ' => 'Ⅼ', 'ⅽ' => 'Ⅽ', 'ⅾ' => 'Ⅾ', 'ⅿ' => 'Ⅿ', 'ↄ' => 'Ↄ', 'ⓐ' => 'Ⓐ', 'ⓑ' => 'Ⓑ', 'ⓒ' => 'Ⓒ', 'ⓓ' => 'Ⓓ', 'ⓔ' => 'Ⓔ', 'ⓕ' => 'Ⓕ', 'ⓖ' => 'Ⓖ', 'ⓗ' => 'Ⓗ', 'ⓘ' => 'Ⓘ', 'ⓙ' => 'Ⓙ', 'ⓚ' => 'Ⓚ', 'ⓛ' => 'Ⓛ', 'ⓜ' => 'Ⓜ', 'ⓝ' => 'Ⓝ', 'ⓞ' => 'Ⓞ', 'ⓟ' => 'Ⓟ', 'ⓠ' => 'Ⓠ', 'ⓡ' => 'Ⓡ', 'ⓢ' => 'Ⓢ', 'ⓣ' => 'Ⓣ', 'ⓤ' => 'Ⓤ', 'ⓥ' => 'Ⓥ', 'ⓦ' => 'Ⓦ', 'ⓧ' => 'Ⓧ', 'ⓨ' => 'Ⓨ', 'ⓩ' => 'Ⓩ', 'ⰰ' => 'Ⰰ', 'ⰱ' => 'Ⰱ', 'ⰲ' => 'Ⰲ', 'ⰳ' => 'Ⰳ', 'ⰴ' => 'Ⰴ', 'ⰵ' => 'Ⰵ', 'ⰶ' => 'Ⰶ', 'ⰷ' => 'Ⰷ', 'ⰸ' => 'Ⰸ', 'ⰹ' => 'Ⰹ', 'ⰺ' => 'Ⰺ', 'ⰻ' => 'Ⰻ', 'ⰼ' => 'Ⰼ', 'ⰽ' => 'Ⰽ', 'ⰾ' => 'Ⰾ', 'ⰿ' => 'Ⰿ', 'ⱀ' => 'Ⱀ', 'ⱁ' => 'Ⱁ', 'ⱂ' => 'Ⱂ', 'ⱃ' => 'Ⱃ', 'ⱄ' => 'Ⱄ', 'ⱅ' => 'Ⱅ', 'ⱆ' => 'Ⱆ', 'ⱇ' => 'Ⱇ', 'ⱈ' => 'Ⱈ', 'ⱉ' => 'Ⱉ', 'ⱊ' => 'Ⱊ', 'ⱋ' => 'Ⱋ', 'ⱌ' => 'Ⱌ', 'ⱍ' => 'Ⱍ', 'ⱎ' => 'Ⱎ', 'ⱏ' => 'Ⱏ', 'ⱐ' => 'Ⱐ', 'ⱑ' => 'Ⱑ', 'ⱒ' => 'Ⱒ', 'ⱓ' => 'Ⱓ', 'ⱔ' => 'Ⱔ', 'ⱕ' => 'Ⱕ', 'ⱖ' => 'Ⱖ', 'ⱗ' => 'Ⱗ', 'ⱘ' => 'Ⱘ', 'ⱙ' => 'Ⱙ', 'ⱚ' => 'Ⱚ', 'ⱛ' => 'Ⱛ', 'ⱜ' => 'Ⱜ', 'ⱝ' => 'Ⱝ', 'ⱞ' => 'Ⱞ', 'ⱡ' => 'Ⱡ', 'ⱥ' => 'Ⱥ', 'ⱦ' => 'Ⱦ', 'ⱨ' => 'Ⱨ', 'ⱪ' => 'Ⱪ', 'ⱬ' => 'Ⱬ', 'ⱳ' => 'Ⱳ', 'ⱶ' => 'Ⱶ', 'ⲁ' => 'Ⲁ', 'ⲃ' => 'Ⲃ', 'ⲅ' => 'Ⲅ', 'ⲇ' => 'Ⲇ', 'ⲉ' => 'Ⲉ', 'ⲋ' => 'Ⲋ', 'ⲍ' => 'Ⲍ', 'ⲏ' => 'Ⲏ', 'ⲑ' => 'Ⲑ', 'ⲓ' => 'Ⲓ', 'ⲕ' => 'Ⲕ', 'ⲗ' => 'Ⲗ', 'ⲙ' => 'Ⲙ', 'ⲛ' => 'Ⲛ', 'ⲝ' => 'Ⲝ', 'ⲟ' => 'Ⲟ', 'ⲡ' => 'Ⲡ', 'ⲣ' => 'Ⲣ', 'ⲥ' => 'Ⲥ', 'ⲧ' => 'Ⲧ', 'ⲩ' => 'Ⲩ', 'ⲫ' => 'Ⲫ', 'ⲭ' => 'Ⲭ', 'ⲯ' => 'Ⲯ', 'ⲱ' => 'Ⲱ', 'ⲳ' => 'Ⲳ', 'ⲵ' => 'Ⲵ', 'ⲷ' => 'Ⲷ', 'ⲹ' => 'Ⲹ', 'ⲻ' => 'Ⲻ', 'ⲽ' => 'Ⲽ', 'ⲿ' => 'Ⲿ', 'ⳁ' => 'Ⳁ', 'ⳃ' => 'Ⳃ', 'ⳅ' => 'Ⳅ', 'ⳇ' => 'Ⳇ', 'ⳉ' => 'Ⳉ', 'ⳋ' => 'Ⳋ', 'ⳍ' => 'Ⳍ', 'ⳏ' => 'Ⳏ', 'ⳑ' => 'Ⳑ', 'ⳓ' => 'Ⳓ', 'ⳕ' => 'Ⳕ', 'ⳗ' => 'Ⳗ', 'ⳙ' => 'Ⳙ', 'ⳛ' => 'Ⳛ', 'ⳝ' => 'Ⳝ', 'ⳟ' => 'Ⳟ', 'ⳡ' => 'Ⳡ', 'ⳣ' => 'Ⳣ', 'ⳬ' => 'Ⳬ', 'ⳮ' => 'Ⳮ', 'ⳳ' => 'Ⳳ', 'ⴀ' => 'Ⴀ', 'ⴁ' => 'Ⴁ', 'ⴂ' => 'Ⴂ', 'ⴃ' => 'Ⴃ', 'ⴄ' => 'Ⴄ', 'ⴅ' => 'Ⴅ', 'ⴆ' => 'Ⴆ', 'ⴇ' => 'Ⴇ', 'ⴈ' => 'Ⴈ', 'ⴉ' => 'Ⴉ', 'ⴊ' => 'Ⴊ', 'ⴋ' => 'Ⴋ', 'ⴌ' => 'Ⴌ', 'ⴍ' => 'Ⴍ', 'ⴎ' => 'Ⴎ', 'ⴏ' => 'Ⴏ', 'ⴐ' => 'Ⴐ', 'ⴑ' => 'Ⴑ', 'ⴒ' => 'Ⴒ', 'ⴓ' => 'Ⴓ', 'ⴔ' => 'Ⴔ', 'ⴕ' => 'Ⴕ', 'ⴖ' => 'Ⴖ', 'ⴗ' => 'Ⴗ', 'ⴘ' => 'Ⴘ', 'ⴙ' => 'Ⴙ', 'ⴚ' => 'Ⴚ', 'ⴛ' => 'Ⴛ', 'ⴜ' => 'Ⴜ', 'ⴝ' => 'Ⴝ', 'ⴞ' => 'Ⴞ', 'ⴟ' => 'Ⴟ', 'ⴠ' => 'Ⴠ', 'ⴡ' => 'Ⴡ', 'ⴢ' => 'Ⴢ', 'ⴣ' => 'Ⴣ', 'ⴤ' => 'Ⴤ', 'ⴥ' => 'Ⴥ', 'ⴧ' => 'Ⴧ', 'ⴭ' => 'Ⴭ', 'ꙁ' => 'Ꙁ', 'ꙃ' => 'Ꙃ', 'ꙅ' => 'Ꙅ', 'ꙇ' => 'Ꙇ', 'ꙉ' => 'Ꙉ', 'ꙋ' => 'Ꙋ', 'ꙍ' => 'Ꙍ', 'ꙏ' => 'Ꙏ', 'ꙑ' => 'Ꙑ', 'ꙓ' => 'Ꙓ', 'ꙕ' => 'Ꙕ', 'ꙗ' => 'Ꙗ', 'ꙙ' => 'Ꙙ', 'ꙛ' => 'Ꙛ', 'ꙝ' => 'Ꙝ', 'ꙟ' => 'Ꙟ', 'ꙡ' => 'Ꙡ', 'ꙣ' => 'Ꙣ', 'ꙥ' => 'Ꙥ', 'ꙧ' => 'Ꙧ', 'ꙩ' => 'Ꙩ', 'ꙫ' => 'Ꙫ', 'ꙭ' => 'Ꙭ', 'ꚁ' => 'Ꚁ', 'ꚃ' => 'Ꚃ', 'ꚅ' => 'Ꚅ', 'ꚇ' => 'Ꚇ', 'ꚉ' => 'Ꚉ', 'ꚋ' => 'Ꚋ', 'ꚍ' => 'Ꚍ', 'ꚏ' => 'Ꚏ', 'ꚑ' => 'Ꚑ', 'ꚓ' => 'Ꚓ', 'ꚕ' => 'Ꚕ', 'ꚗ' => 'Ꚗ', 'ꚙ' => 'Ꚙ', 'ꚛ' => 'Ꚛ', 'ꜣ' => 'Ꜣ', 'ꜥ' => 'Ꜥ', 'ꜧ' => 'Ꜧ', 'ꜩ' => 'Ꜩ', 'ꜫ' => 'Ꜫ', 'ꜭ' => 'Ꜭ', 'ꜯ' => 'Ꜯ', 'ꜳ' => 'Ꜳ', 'ꜵ' => 'Ꜵ', 'ꜷ' => 'Ꜷ', 'ꜹ' => 'Ꜹ', 'ꜻ' => 'Ꜻ', 'ꜽ' => 'Ꜽ', 'ꜿ' => 'Ꜿ', 'ꝁ' => 'Ꝁ', 'ꝃ' => 'Ꝃ', 'ꝅ' => 'Ꝅ', 'ꝇ' => 'Ꝇ', 'ꝉ' => 'Ꝉ', 'ꝋ' => 'Ꝋ', 'ꝍ' => 'Ꝍ', 'ꝏ' => 'Ꝏ', 'ꝑ' => 'Ꝑ', 'ꝓ' => 'Ꝓ', 'ꝕ' => 'Ꝕ', 'ꝗ' => 'Ꝗ', 'ꝙ' => 'Ꝙ', 'ꝛ' => 'Ꝛ', 'ꝝ' => 'Ꝝ', 'ꝟ' => 'Ꝟ', 'ꝡ' => 'Ꝡ', 'ꝣ' => 'Ꝣ', 'ꝥ' => 'Ꝥ', 'ꝧ' => 'Ꝧ', 'ꝩ' => 'Ꝩ', 'ꝫ' => 'Ꝫ', 'ꝭ' => 'Ꝭ', 'ꝯ' => 'Ꝯ', 'ꝺ' => 'Ꝺ', 'ꝼ' => 'Ꝼ', 'ꝿ' => 'Ꝿ', 'ꞁ' => 'Ꞁ', 'ꞃ' => 'Ꞃ', 'ꞅ' => 'Ꞅ', 'ꞇ' => 'Ꞇ', 'ꞌ' => 'Ꞌ', 'ꞑ' => 'Ꞑ', 'ꞓ' => 'Ꞓ', 'ꞗ' => 'Ꞗ', 'ꞙ' => 'Ꞙ', 'ꞛ' => 'Ꞛ', 'ꞝ' => 'Ꞝ', 'ꞟ' => 'Ꞟ', 'ꞡ' => 'Ꞡ', 'ꞣ' => 'Ꞣ', 'ꞥ' => 'Ꞥ', 'ꞧ' => 'Ꞧ', 'ꞩ' => 'Ꞩ', 'a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G', 'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K', 'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O', 'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S', 't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W', 'x' => 'X', 'y' => 'Y', 'z' => 'Z', '𐐨' => '𐐀', '𐐩' => '𐐁', '𐐪' => '𐐂', '𐐫' => '𐐃', '𐐬' => '𐐄', '𐐭' => '𐐅', '𐐮' => '𐐆', '𐐯' => '𐐇', '𐐰' => '𐐈', '𐐱' => '𐐉', '𐐲' => '𐐊', '𐐳' => '𐐋', '𐐴' => '𐐌', '𐐵' => '𐐍', '𐐶' => '𐐎', '𐐷' => '𐐏', '𐐸' => '𐐐', '𐐹' => '𐐑', '𐐺' => '𐐒', '𐐻' => '𐐓', '𐐼' => '𐐔', '𐐽' => '𐐕', '𐐾' => '𐐖', '𐐿' => '𐐗', '𐑀' => '𐐘', '𐑁' => '𐐙', '𐑂' => '𐐚', '𐑃' => '𐐛', '𐑄' => '𐐜', '𐑅' => '𐐝', '𐑆' => '𐐞', '𐑇' => '𐐟', '𐑈' => '𐐠', '𐑉' => '𐐡', '𐑊' => '𐐢', '𐑋' => '𐐣', '𐑌' => '𐐤', '𐑍' => '𐐥', '𐑎' => '𐐦', '𐑏' => '𐐧', '𑣀' => '𑢠', '𑣁' => '𑢡', '𑣂' => '𑢢', '𑣃' => '𑢣', '𑣄' => '𑢤', '𑣅' => '𑢥', '𑣆' => '𑢦', '𑣇' => '𑢧', '𑣈' => '𑢨', '𑣉' => '𑢩', '𑣊' => '𑢪', '𑣋' => '𑢫', '𑣌' => '𑢬', '𑣍' => '𑢭', '𑣎' => '𑢮', '𑣏' => '𑢯', '𑣐' => '𑢰', '𑣑' => '𑢱', '𑣒' => '𑢲', '𑣓' => '𑢳', '𑣔' => '𑢴', '𑣕' => '𑢵', '𑣖' => '𑢶', '𑣗' => '𑢷', '𑣘' => '𑢸', '𑣙' => '𑢹', '𑣚' => '𑢺', '𑣛' => '𑢻', '𑣜' => '𑢼', '𑣝' => '𑢽', '𑣞' => '𑢾', '𑣟' => '𑢿', ); 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z', 'À' => 'à', 'Á' => 'á', 'Â' => 'â', 'Ã' => 'ã', 'Ä' => 'ä', 'Å' => 'å', 'Æ' => 'æ', 'Ç' => 'ç', 'È' => 'è', 'É' => 'é', 'Ê' => 'ê', 'Ë' => 'ë', 'Ì' => 'ì', 'Í' => 'í', 'Î' => 'î', 'Ï' => 'ï', 'Ð' => 'ð', 'Ñ' => 'ñ', 'Ò' => 'ò', 'Ó' => 'ó', 'Ô' => 'ô', 'Õ' => 'õ', 'Ö' => 'ö', 'Ø' => 'ø', 'Ù' => 'ù', 'Ú' => 'ú', 'Û' => 'û', 'Ü' => 'ü', 'Ý' => 'ý', 'Þ' => 'þ', 'Ā' => 'ā', 'Ă' => 'ă', 'Ą' => 'ą', 'Ć' => 'ć', 'Ĉ' => 'ĉ', 'Ċ' => 'ċ', 'Č' => 'č', 'Ď' => 'ď', 'Đ' => 'đ', 'Ē' => 'ē', 'Ĕ' => 'ĕ', 'Ė' => 'ė', 'Ę' => 'ę', 'Ě' => 'ě', 'Ĝ' => 'ĝ', 'Ğ' => 'ğ', 'Ġ' => 'ġ', 'Ģ' => 'ģ', 'Ĥ' => 'ĥ', 'Ħ' => 'ħ', 'Ĩ' => 'ĩ', 'Ī' => 'ī', 'Ĭ' => 'ĭ', 'Į' => 'į', 'İ' => 'i', 'IJ' => 'ij', 'Ĵ' => 'ĵ', 'Ķ' => 'ķ', 'Ĺ' => 'ĺ', 'Ļ' => 'ļ', 'Ľ' => 'ľ', 'Ŀ' => 'ŀ', 'Ł' => 'ł', 'Ń' => 'ń', 'Ņ' => 'ņ', 'Ň' => 'ň', 'Ŋ' => 'ŋ', 'Ō' => 'ō', 'Ŏ' => 'ŏ', 'Ő' => 'ő', 'Œ' => 'œ', 'Ŕ' => 'ŕ', 'Ŗ' => 'ŗ', 'Ř' => 'ř', 'Ś' => 'ś', 'Ŝ' => 'ŝ', 'Ş' => 'ş', 'Š' => 'š', 'Ţ' => 'ţ', 'Ť' => 'ť', 'Ŧ' => 'ŧ', 'Ũ' => 'ũ', 'Ū' => 'ū', 'Ŭ' => 'ŭ', 'Ů' => 'ů', 'Ű' => 'ű', 'Ų' => 'ų', 'Ŵ' => 'ŵ', 'Ŷ' => 'ŷ', 'Ÿ' => 'ÿ', 'Ź' => 'ź', 'Ż' => 'ż', 'Ž' => 'ž', 'Ɓ' => 'ɓ', 'Ƃ' => 'ƃ', 'Ƅ' => 'ƅ', 'Ɔ' => 'ɔ', 'Ƈ' => 'ƈ', 'Ɖ' => 'ɖ', 'Ɗ' => 'ɗ', 'Ƌ' => 'ƌ', 'Ǝ' => 'ǝ', 'Ə' => 'ə', 'Ɛ' => 'ɛ', 'Ƒ' => 'ƒ', 'Ɠ' => 'ɠ', 'Ɣ' => 'ɣ', 'Ɩ' => 'ɩ', 'Ɨ' => 'ɨ', 'Ƙ' => 'ƙ', 'Ɯ' => 'ɯ', 'Ɲ' => 'ɲ', 'Ɵ' => 'ɵ', 'Ơ' => 'ơ', 'Ƣ' => 'ƣ', 'Ƥ' => 'ƥ', 'Ʀ' => 'ʀ', 'Ƨ' => 'ƨ', 'Ʃ' => 'ʃ', 'Ƭ' => 'ƭ', 'Ʈ' => 'ʈ', 'Ư' => 'ư', 'Ʊ' => 'ʊ', 'Ʋ' => 'ʋ', 'Ƴ' => 'ƴ', 'Ƶ' => 'ƶ', 'Ʒ' => 'ʒ', 'Ƹ' => 'ƹ', 'Ƽ' => 'ƽ', 'DŽ' => 'dž', 'Dž' => 'dž', 'LJ' => 'lj', 'Lj' => 'lj', 'NJ' => 'nj', 'Nj' => 'nj', 'Ǎ' => 'ǎ', 'Ǐ' => 'ǐ', 'Ǒ' => 'ǒ', 'Ǔ' => 'ǔ', 'Ǖ' => 'ǖ', 'Ǘ' => 'ǘ', 'Ǚ' => 'ǚ', 'Ǜ' => 'ǜ', 'Ǟ' => 'ǟ', 'Ǡ' => 'ǡ', 'Ǣ' => 'ǣ', 'Ǥ' => 'ǥ', 'Ǧ' => 'ǧ', 'Ǩ' => 'ǩ', 'Ǫ' => 'ǫ', 'Ǭ' => 'ǭ', 'Ǯ' => 'ǯ', 'DZ' => 'dz', 'Dz' => 'dz', 'Ǵ' => 'ǵ', 'Ƕ' => 'ƕ', 'Ƿ' => 'ƿ', 'Ǹ' => 'ǹ', 'Ǻ' => 'ǻ', 'Ǽ' => 'ǽ', 'Ǿ' => 'ǿ', 'Ȁ' => 'ȁ', 'Ȃ' => 'ȃ', 'Ȅ' => 'ȅ', 'Ȇ' => 'ȇ', 'Ȉ' => 'ȉ', 'Ȋ' => 'ȋ', 'Ȍ' => 'ȍ', 'Ȏ' => 'ȏ', 'Ȑ' => 'ȑ', 'Ȓ' => 'ȓ', 'Ȕ' => 'ȕ', 'Ȗ' => 'ȗ', 'Ș' => 'ș', 'Ț' => 'ț', 'Ȝ' => 'ȝ', 'Ȟ' => 'ȟ', 'Ƞ' => 'ƞ', 'Ȣ' => 'ȣ', 'Ȥ' => 'ȥ', 'Ȧ' => 'ȧ', 'Ȩ' => 'ȩ', 'Ȫ' => 'ȫ', 'Ȭ' => 'ȭ', 'Ȯ' => 'ȯ', 'Ȱ' => 'ȱ', 'Ȳ' => 'ȳ', 'Ⱥ' => 'ⱥ', 'Ȼ' => 'ȼ', 'Ƚ' => 'ƚ', 'Ⱦ' => 'ⱦ', 'Ɂ' => 'ɂ', 'Ƀ' => 'ƀ', 'Ʉ' => 'ʉ', 'Ʌ' => 'ʌ', 'Ɇ' => 'ɇ', 'Ɉ' => 'ɉ', 'Ɋ' => 'ɋ', 'Ɍ' => 'ɍ', 'Ɏ' => 'ɏ', 'Ͱ' => 'ͱ', 'Ͳ' => 'ͳ', 'Ͷ' => 'ͷ', 'Ϳ' => 'ϳ', 'Ά' => 'ά', 'Έ' => 'έ', 'Ή' => 'ή', 'Ί' => 'ί', 'Ό' => 'ό', 'Ύ' => 'ύ', 'Ώ' => 'ώ', 'Α' => 'α', 'Β' => 'β', 'Γ' => 'γ', 'Δ' => 'δ', 'Ε' => 'ε', 'Ζ' => 'ζ', 'Η' => 'η', 'Θ' => 'θ', 'Ι' => 'ι', 'Κ' => 'κ', 'Λ' => 'λ', 'Μ' => 'μ', 'Ν' => 'ν', 'Ξ' => 'ξ', 'Ο' => 'ο', 'Π' => 'π', 'Ρ' => 'ρ', 'Σ' => 'σ', 'Τ' => 'τ', 'Υ' => 'υ', 'Φ' => 'φ', 'Χ' => 'χ', 'Ψ' => 'ψ', 'Ω' => 'ω', 'Ϊ' => 'ϊ', 'Ϋ' => 'ϋ', 'Ϗ' => 'ϗ', 'Ϙ' => 'ϙ', 'Ϛ' => 'ϛ', 'Ϝ' => 'ϝ', 'Ϟ' => 'ϟ', 'Ϡ' => 'ϡ', 'Ϣ' => 'ϣ', 'Ϥ' => 'ϥ', 'Ϧ' => 'ϧ', 'Ϩ' => 'ϩ', 'Ϫ' => 'ϫ', 'Ϭ' => 'ϭ', 'Ϯ' => 'ϯ', 'ϴ' => 'θ', 'Ϸ' => 'ϸ', 'Ϲ' => 'ϲ', 'Ϻ' => 'ϻ', 'Ͻ' => 'ͻ', 'Ͼ' => 'ͼ', 'Ͽ' => 'ͽ', 'Ѐ' => 'ѐ', 'Ё' => 'ё', 'Ђ' => 'ђ', 'Ѓ' => 'ѓ', 'Є' => 'є', 'Ѕ' => 'ѕ', 'І' => 'і', 'Ї' => 'ї', 'Ј' => 'ј', 'Љ' => 'љ', 'Њ' => 'њ', 'Ћ' => 'ћ', 'Ќ' => 'ќ', 'Ѝ' => 'ѝ', 'Ў' => 'ў', 'Џ' => 'џ', 'А' => 'а', 'Б' => 'б', 'В' => 'в', 'Г' => 'г', 'Д' => 'д', 'Е' => 'е', 'Ж' => 'ж', 'З' => 'з', 'И' => 'и', 'Й' => 'й', 'К' => 'к', 'Л' => 'л', 'М' => 'м', 'Н' => 'н', 'О' => 'о', 'П' => 'п', 'Р' => 'р', 'С' => 'с', 'Т' => 'т', 'У' => 'у', 'Ф' => 'ф', 'Х' => 'х', 'Ц' => 'ц', 'Ч' => 'ч', 'Ш' => 'ш', 'Щ' => 'щ', 'Ъ' => 'ъ', 'Ы' => 'ы', 'Ь' => 'ь', 'Э' => 'э', 'Ю' => 'ю', 'Я' => 'я', 'Ѡ' => 'ѡ', 'Ѣ' => 'ѣ', 'Ѥ' => 'ѥ', 'Ѧ' => 'ѧ', 'Ѩ' => 'ѩ', 'Ѫ' => 'ѫ', 'Ѭ' => 'ѭ', 'Ѯ' => 'ѯ', 'Ѱ' => 'ѱ', 'Ѳ' => 'ѳ', 'Ѵ' => 'ѵ', 'Ѷ' => 'ѷ', 'Ѹ' => 'ѹ', 'Ѻ' => 'ѻ', 'Ѽ' => 'ѽ', 'Ѿ' => 'ѿ', 'Ҁ' => 'ҁ', 'Ҋ' => 'ҋ', 'Ҍ' => 'ҍ', 'Ҏ' => 'ҏ', 'Ґ' => 'ґ', 'Ғ' => 'ғ', 'Ҕ' => 'ҕ', 'Җ' => 'җ', 'Ҙ' => 'ҙ', 'Қ' => 'қ', 'Ҝ' => 'ҝ', 'Ҟ' => 'ҟ', 'Ҡ' => 'ҡ', 'Ң' => 'ң', 'Ҥ' => 'ҥ', 'Ҧ' => 'ҧ', 'Ҩ' => 'ҩ', 'Ҫ' => 'ҫ', 'Ҭ' => 'ҭ', 'Ү' => 'ү', 'Ұ' => 'ұ', 'Ҳ' => 'ҳ', 'Ҵ' => 'ҵ', 'Ҷ' => 'ҷ', 'Ҹ' => 'ҹ', 'Һ' => 'һ', 'Ҽ' => 'ҽ', 'Ҿ' => 'ҿ', 'Ӏ' => 'ӏ', 'Ӂ' => 'ӂ', 'Ӄ' => 'ӄ', 'Ӆ' => 'ӆ', 'Ӈ' => 'ӈ', 'Ӊ' => 'ӊ', 'Ӌ' => 'ӌ', 'Ӎ' => 'ӎ', 'Ӑ' => 'ӑ', 'Ӓ' => 'ӓ', 'Ӕ' => 'ӕ', 'Ӗ' => 'ӗ', 'Ә' => 'ә', 'Ӛ' => 'ӛ', 'Ӝ' => 'ӝ', 'Ӟ' => 'ӟ', 'Ӡ' => 'ӡ', 'Ӣ' => 'ӣ', 'Ӥ' => 'ӥ', 'Ӧ' => 'ӧ', 'Ө' => 'ө', 'Ӫ' => 'ӫ', 'Ӭ' => 'ӭ', 'Ӯ' => 'ӯ', 'Ӱ' => 'ӱ', 'Ӳ' => 'ӳ', 'Ӵ' => 'ӵ', 'Ӷ' => 'ӷ', 'Ӹ' => 'ӹ', 'Ӻ' => 'ӻ', 'Ӽ' => 'ӽ', 'Ӿ' => 'ӿ', 'Ԁ' => 'ԁ', 'Ԃ' => 'ԃ', 'Ԅ' => 'ԅ', 'Ԇ' => 'ԇ', 'Ԉ' => 'ԉ', 'Ԋ' => 'ԋ', 'Ԍ' => 'ԍ', 'Ԏ' => 'ԏ', 'Ԑ' => 'ԑ', 'Ԓ' => 'ԓ', 'Ԕ' => 'ԕ', 'Ԗ' => 'ԗ', 'Ԙ' => 'ԙ', 'Ԛ' => 'ԛ', 'Ԝ' => 'ԝ', 'Ԟ' => 'ԟ', 'Ԡ' => 'ԡ', 'Ԣ' => 'ԣ', 'Ԥ' => 'ԥ', 'Ԧ' => 'ԧ', 'Ԩ' => 'ԩ', 'Ԫ' => 'ԫ', 'Ԭ' => 'ԭ', 'Ԯ' => 'ԯ', 'Ա' => 'ա', 'Բ' => 'բ', 'Գ' => 'գ', 'Դ' => 'դ', 'Ե' => 'ե', 'Զ' => 'զ', 'Է' => 'է', 'Ը' => 'ը', 'Թ' => 'թ', 'Ժ' => 'ժ', 'Ի' => 'ի', 'Լ' => 'լ', 'Խ' => 'խ', 'Ծ' => 'ծ', 'Կ' => 'կ', 'Հ' => 'հ', 'Ձ' => 'ձ', 'Ղ' => 'ղ', 'Ճ' => 'ճ', 'Մ' => 'մ', 'Յ' => 'յ', 'Ն' => 'ն', 'Շ' => 'շ', 'Ո' => 'ո', 'Չ' => 'չ', 'Պ' => 'պ', 'Ջ' => 'ջ', 'Ռ' => 'ռ', 'Ս' => 'ս', 'Վ' => 'վ', 'Տ' => 'տ', 'Ր' => 'ր', 'Ց' => 'ց', 'Ւ' => 'ւ', 'Փ' => 'փ', 'Ք' => 'ք', 'Օ' => 'օ', 'Ֆ' => 'ֆ', 'Ⴀ' => 'ⴀ', 'Ⴁ' => 'ⴁ', 'Ⴂ' => 'ⴂ', 'Ⴃ' => 'ⴃ', 'Ⴄ' => 'ⴄ', 'Ⴅ' => 'ⴅ', 'Ⴆ' => 'ⴆ', 'Ⴇ' => 'ⴇ', 'Ⴈ' => 'ⴈ', 'Ⴉ' => 'ⴉ', 'Ⴊ' => 'ⴊ', 'Ⴋ' => 'ⴋ', 'Ⴌ' => 'ⴌ', 'Ⴍ' => 'ⴍ', 'Ⴎ' => 'ⴎ', 'Ⴏ' => 'ⴏ', 'Ⴐ' => 'ⴐ', 'Ⴑ' => 'ⴑ', 'Ⴒ' => 'ⴒ', 'Ⴓ' => 'ⴓ', 'Ⴔ' => 'ⴔ', 'Ⴕ' => 'ⴕ', 'Ⴖ' => 'ⴖ', 'Ⴗ' => 'ⴗ', 'Ⴘ' => 'ⴘ', 'Ⴙ' => 'ⴙ', 'Ⴚ' => 'ⴚ', 'Ⴛ' => 'ⴛ', 'Ⴜ' => 'ⴜ', 'Ⴝ' => 'ⴝ', 'Ⴞ' => 'ⴞ', 'Ⴟ' => 'ⴟ', 'Ⴠ' => 'ⴠ', 'Ⴡ' => 'ⴡ', 'Ⴢ' => 'ⴢ', 'Ⴣ' => 'ⴣ', 'Ⴤ' => 'ⴤ', 'Ⴥ' => 'ⴥ', 'Ⴧ' => 'ⴧ', 'Ⴭ' => 'ⴭ', 'Ḁ' => 'ḁ', 'Ḃ' => 'ḃ', 'Ḅ' => 'ḅ', 'Ḇ' => 'ḇ', 'Ḉ' => 'ḉ', 'Ḋ' => 'ḋ', 'Ḍ' => 'ḍ', 'Ḏ' => 'ḏ', 'Ḑ' => 'ḑ', 'Ḓ' => 'ḓ', 'Ḕ' => 'ḕ', 'Ḗ' => 'ḗ', 'Ḙ' => 'ḙ', 'Ḛ' => 'ḛ', 'Ḝ' => 'ḝ', 'Ḟ' => 'ḟ', 'Ḡ' => 'ḡ', 'Ḣ' => 'ḣ', 'Ḥ' => 'ḥ', 'Ḧ' => 'ḧ', 'Ḩ' => 'ḩ', 'Ḫ' => 'ḫ', 'Ḭ' => 'ḭ', 'Ḯ' => 'ḯ', 'Ḱ' => 'ḱ', 'Ḳ' => 'ḳ', 'Ḵ' => 'ḵ', 'Ḷ' => 'ḷ', 'Ḹ' => 'ḹ', 'Ḻ' => 'ḻ', 'Ḽ' => 'ḽ', 'Ḿ' => 'ḿ', 'Ṁ' => 'ṁ', 'Ṃ' => 'ṃ', 'Ṅ' => 'ṅ', 'Ṇ' => 'ṇ', 'Ṉ' => 'ṉ', 'Ṋ' => 'ṋ', 'Ṍ' => 'ṍ', 'Ṏ' => 'ṏ', 'Ṑ' => 'ṑ', 'Ṓ' => 'ṓ', 'Ṕ' => 'ṕ', 'Ṗ' => 'ṗ', 'Ṙ' => 'ṙ', 'Ṛ' => 'ṛ', 'Ṝ' => 'ṝ', 'Ṟ' => 'ṟ', 'Ṡ' => 'ṡ', 'Ṣ' => 'ṣ', 'Ṥ' => 'ṥ', 'Ṧ' => 'ṧ', 'Ṩ' => 'ṩ', 'Ṫ' => 'ṫ', 'Ṭ' => 'ṭ', 'Ṯ' => 'ṯ', 'Ṱ' => 'ṱ', 'Ṳ' => 'ṳ', 'Ṵ' => 'ṵ', 'Ṷ' => 'ṷ', 'Ṹ' => 'ṹ', 'Ṻ' => 'ṻ', 'Ṽ' => 'ṽ', 'Ṿ' => 'ṿ', 'Ẁ' => 'ẁ', 'Ẃ' => 'ẃ', 'Ẅ' => 'ẅ', 'Ẇ' => 'ẇ', 'Ẉ' => 'ẉ', 'Ẋ' => 'ẋ', 'Ẍ' => 'ẍ', 'Ẏ' => 'ẏ', 'Ẑ' => 'ẑ', 'Ẓ' => 'ẓ', 'Ẕ' => 'ẕ', 'ẞ' => 'ß', 'Ạ' => 'ạ', 'Ả' => 'ả', 'Ấ' => 'ấ', 'Ầ' => 'ầ', 'Ẩ' => 'ẩ', 'Ẫ' => 'ẫ', 'Ậ' => 'ậ', 'Ắ' => 'ắ', 'Ằ' => 'ằ', 'Ẳ' => 'ẳ', 'Ẵ' => 'ẵ', 'Ặ' => 'ặ', 'Ẹ' => 'ẹ', 'Ẻ' => 'ẻ', 'Ẽ' => 'ẽ', 'Ế' => 'ế', 'Ề' => 'ề', 'Ể' => 'ể', 'Ễ' => 'ễ', 'Ệ' => 'ệ', 'Ỉ' => 'ỉ', 'Ị' => 'ị', 'Ọ' => 'ọ', 'Ỏ' => 'ỏ', 'Ố' => 'ố', 'Ồ' => 'ồ', 'Ổ' => 'ổ', 'Ỗ' => 'ỗ', 'Ộ' => 'ộ', 'Ớ' => 'ớ', 'Ờ' => 'ờ', 'Ở' => 'ở', 'Ỡ' => 'ỡ', 'Ợ' => 'ợ', 'Ụ' => 'ụ', 'Ủ' => 'ủ', 'Ứ' => 'ứ', 'Ừ' => 'ừ', 'Ử' => 'ử', 'Ữ' => 'ữ', 'Ự' => 'ự', 'Ỳ' => 'ỳ', 'Ỵ' => 'ỵ', 'Ỷ' => 'ỷ', 'Ỹ' => 'ỹ', 'Ỻ' => 'ỻ', 'Ỽ' => 'ỽ', 'Ỿ' => 'ỿ', 'Ἀ' => 'ἀ', 'Ἁ' => 'ἁ', 'Ἂ' => 'ἂ', 'Ἃ' => 'ἃ', 'Ἄ' => 'ἄ', 'Ἅ' => 'ἅ', 'Ἆ' => 'ἆ', 'Ἇ' => 'ἇ', 'Ἐ' => 'ἐ', 'Ἑ' => 'ἑ', 'Ἒ' => 'ἒ', 'Ἓ' => 'ἓ', 'Ἔ' => 'ἔ', 'Ἕ' => 'ἕ', 'Ἠ' => 'ἠ', 'Ἡ' => 'ἡ', 'Ἢ' => 'ἢ', 'Ἣ' => 'ἣ', 'Ἤ' => 'ἤ', 'Ἥ' => 'ἥ', 'Ἦ' => 'ἦ', 'Ἧ' => 'ἧ', 'Ἰ' => 'ἰ', 'Ἱ' => 'ἱ', 'Ἲ' => 'ἲ', 'Ἳ' => 'ἳ', 'Ἴ' => 'ἴ', 'Ἵ' => 'ἵ', 'Ἶ' => 'ἶ', 'Ἷ' => 'ἷ', 'Ὀ' => 'ὀ', 'Ὁ' => 'ὁ', 'Ὂ' => 'ὂ', 'Ὃ' => 'ὃ', 'Ὄ' => 'ὄ', 'Ὅ' => 'ὅ', 'Ὑ' => 'ὑ', 'Ὓ' => 'ὓ', 'Ὕ' => 'ὕ', 'Ὗ' => 'ὗ', 'Ὠ' => 'ὠ', 'Ὡ' => 'ὡ', 'Ὢ' => 'ὢ', 'Ὣ' => 'ὣ', 'Ὤ' => 'ὤ', 'Ὥ' => 'ὥ', 'Ὦ' => 'ὦ', 'Ὧ' => 'ὧ', 'ᾈ' => 'ᾀ', 'ᾉ' => 'ᾁ', 'ᾊ' => 'ᾂ', 'ᾋ' => 'ᾃ', 'ᾌ' => 'ᾄ', 'ᾍ' => 'ᾅ', 'ᾎ' => 'ᾆ', 'ᾏ' => 'ᾇ', 'ᾘ' => 'ᾐ', 'ᾙ' => 'ᾑ', 'ᾚ' => 'ᾒ', 'ᾛ' => 'ᾓ', 'ᾜ' => 'ᾔ', 'ᾝ' => 'ᾕ', 'ᾞ' => 'ᾖ', 'ᾟ' => 'ᾗ', 'ᾨ' => 'ᾠ', 'ᾩ' => 'ᾡ', 'ᾪ' => 'ᾢ', 'ᾫ' => 'ᾣ', 'ᾬ' => 'ᾤ', 'ᾭ' => 'ᾥ', 'ᾮ' => 'ᾦ', 'ᾯ' => 'ᾧ', 'Ᾰ' => 'ᾰ', 'Ᾱ' => 'ᾱ', 'Ὰ' => 'ὰ', 'Ά' => 'ά', 'ᾼ' => 'ᾳ', 'Ὲ' => 'ὲ', 'Έ' => 'έ', 'Ὴ' => 'ὴ', 'Ή' => 'ή', 'ῌ' => 'ῃ', 'Ῐ' => 'ῐ', 'Ῑ' => 'ῑ', 'Ὶ' => 'ὶ', 'Ί' => 'ί', 'Ῠ' => 'ῠ', 'Ῡ' => 'ῡ', 'Ὺ' => 'ὺ', 'Ύ' => 'ύ', 'Ῥ' => 'ῥ', 'Ὸ' => 'ὸ', 'Ό' => 'ό', 'Ὼ' => 'ὼ', 'Ώ' => 'ώ', 'ῼ' => 'ῳ', 'Ω' => 'ω', 'K' => 'k', 'Å' => 'å', 'Ⅎ' => 'ⅎ', 'Ⅰ' => 'ⅰ', 'Ⅱ' => 'ⅱ', 'Ⅲ' => 'ⅲ', 'Ⅳ' => 'ⅳ', 'Ⅴ' => 'ⅴ', 'Ⅵ' => 'ⅵ', 'Ⅶ' => 'ⅶ', 'Ⅷ' => 'ⅷ', 'Ⅸ' => 'ⅸ', 'Ⅹ' => 'ⅹ', 'Ⅺ' => 'ⅺ', 'Ⅻ' => 'ⅻ', 'Ⅼ' => 'ⅼ', 'Ⅽ' => 'ⅽ', 'Ⅾ' => 'ⅾ', 'Ⅿ' => 'ⅿ', 'Ↄ' => 'ↄ', 'Ⓐ' => 'ⓐ', 'Ⓑ' => 'ⓑ', 'Ⓒ' => 'ⓒ', 'Ⓓ' => 'ⓓ', 'Ⓔ' => 'ⓔ', 'Ⓕ' => 'ⓕ', 'Ⓖ' => 'ⓖ', 'Ⓗ' => 'ⓗ', 'Ⓘ' => 'ⓘ', 'Ⓙ' => 'ⓙ', 'Ⓚ' => 'ⓚ', 'Ⓛ' => 'ⓛ', 'Ⓜ' => 'ⓜ', 'Ⓝ' => 'ⓝ', 'Ⓞ' => 'ⓞ', 'Ⓟ' => 'ⓟ', 'Ⓠ' => 'ⓠ', 'Ⓡ' => 'ⓡ', 'Ⓢ' => 'ⓢ', 'Ⓣ' => 'ⓣ', 'Ⓤ' => 'ⓤ', 'Ⓥ' => 'ⓥ', 'Ⓦ' => 'ⓦ', 'Ⓧ' => 'ⓧ', 'Ⓨ' => 'ⓨ', 'Ⓩ' => 'ⓩ', 'Ⰰ' => 'ⰰ', 'Ⰱ' => 'ⰱ', 'Ⰲ' => 'ⰲ', 'Ⰳ' => 'ⰳ', 'Ⰴ' => 'ⰴ', 'Ⰵ' => 'ⰵ', 'Ⰶ' => 'ⰶ', 'Ⰷ' => 'ⰷ', 'Ⰸ' => 'ⰸ', 'Ⰹ' => 'ⰹ', 'Ⰺ' => 'ⰺ', 'Ⰻ' => 'ⰻ', 'Ⰼ' => 'ⰼ', 'Ⰽ' => 'ⰽ', 'Ⰾ' => 'ⰾ', 'Ⰿ' => 'ⰿ', 'Ⱀ' => 'ⱀ', 'Ⱁ' => 'ⱁ', 'Ⱂ' => 'ⱂ', 'Ⱃ' => 'ⱃ', 'Ⱄ' => 'ⱄ', 'Ⱅ' => 'ⱅ', 'Ⱆ' => 'ⱆ', 'Ⱇ' => 'ⱇ', 'Ⱈ' => 'ⱈ', 'Ⱉ' => 'ⱉ', 'Ⱊ' => 'ⱊ', 'Ⱋ' => 'ⱋ', 'Ⱌ' => 'ⱌ', 'Ⱍ' => 'ⱍ', 'Ⱎ' => 'ⱎ', 'Ⱏ' => 'ⱏ', 'Ⱐ' => 'ⱐ', 'Ⱑ' => 'ⱑ', 'Ⱒ' => 'ⱒ', 'Ⱓ' => 'ⱓ', 'Ⱔ' => 'ⱔ', 'Ⱕ' => 'ⱕ', 'Ⱖ' => 'ⱖ', 'Ⱗ' => 'ⱗ', 'Ⱘ' => 'ⱘ', 'Ⱙ' => 'ⱙ', 'Ⱚ' => 'ⱚ', 'Ⱛ' => 'ⱛ', 'Ⱜ' => 'ⱜ', 'Ⱝ' => 'ⱝ', 'Ⱞ' => 'ⱞ', 'Ⱡ' => 'ⱡ', 'Ɫ' => 'ɫ', 'Ᵽ' => 'ᵽ', 'Ɽ' => 'ɽ', 'Ⱨ' => 'ⱨ', 'Ⱪ' => 'ⱪ', 'Ⱬ' => 'ⱬ', 'Ɑ' => 'ɑ', 'Ɱ' => 'ɱ', 'Ɐ' => 'ɐ', 'Ɒ' => 'ɒ', 'Ⱳ' => 'ⱳ', 'Ⱶ' => 'ⱶ', 'Ȿ' => 'ȿ', 'Ɀ' => 'ɀ', 'Ⲁ' => 'ⲁ', 'Ⲃ' => 'ⲃ', 'Ⲅ' => 'ⲅ', 'Ⲇ' => 'ⲇ', 'Ⲉ' => 'ⲉ', 'Ⲋ' => 'ⲋ', 'Ⲍ' => 'ⲍ', 'Ⲏ' => 'ⲏ', 'Ⲑ' => 'ⲑ', 'Ⲓ' => 'ⲓ', 'Ⲕ' => 'ⲕ', 'Ⲗ' => 'ⲗ', 'Ⲙ' => 'ⲙ', 'Ⲛ' => 'ⲛ', 'Ⲝ' => 'ⲝ', 'Ⲟ' => 'ⲟ', 'Ⲡ' => 'ⲡ', 'Ⲣ' => 'ⲣ', 'Ⲥ' => 'ⲥ', 'Ⲧ' => 'ⲧ', 'Ⲩ' => 'ⲩ', 'Ⲫ' => 'ⲫ', 'Ⲭ' => 'ⲭ', 'Ⲯ' => 'ⲯ', 'Ⲱ' => 'ⲱ', 'Ⲳ' => 'ⲳ', 'Ⲵ' => 'ⲵ', 'Ⲷ' => 'ⲷ', 'Ⲹ' => 'ⲹ', 'Ⲻ' => 'ⲻ', 'Ⲽ' => 'ⲽ', 'Ⲿ' => 'ⲿ', 'Ⳁ' => 'ⳁ', 'Ⳃ' => 'ⳃ', 'Ⳅ' => 'ⳅ', 'Ⳇ' => 'ⳇ', 'Ⳉ' => 'ⳉ', 'Ⳋ' => 'ⳋ', 'Ⳍ' => 'ⳍ', 'Ⳏ' => 'ⳏ', 'Ⳑ' => 'ⳑ', 'Ⳓ' => 'ⳓ', 'Ⳕ' => 'ⳕ', 'Ⳗ' => 'ⳗ', 'Ⳙ' => 'ⳙ', 'Ⳛ' => 'ⳛ', 'Ⳝ' => 'ⳝ', 'Ⳟ' => 'ⳟ', 'Ⳡ' => 'ⳡ', 'Ⳣ' => 'ⳣ', 'Ⳬ' => 'ⳬ', 'Ⳮ' => 'ⳮ', 'Ⳳ' => 'ⳳ', 'Ꙁ' => 'ꙁ', 'Ꙃ' => 'ꙃ', 'Ꙅ' => 'ꙅ', 'Ꙇ' => 'ꙇ', 'Ꙉ' => 'ꙉ', 'Ꙋ' => 'ꙋ', 'Ꙍ' => 'ꙍ', 'Ꙏ' => 'ꙏ', 'Ꙑ' => 'ꙑ', 'Ꙓ' => 'ꙓ', 'Ꙕ' => 'ꙕ', 'Ꙗ' => 'ꙗ', 'Ꙙ' => 'ꙙ', 'Ꙛ' => 'ꙛ', 'Ꙝ' => 'ꙝ', 'Ꙟ' => 'ꙟ', 'Ꙡ' => 'ꙡ', 'Ꙣ' => 'ꙣ', 'Ꙥ' => 'ꙥ', 'Ꙧ' => 'ꙧ', 'Ꙩ' => 'ꙩ', 'Ꙫ' => 'ꙫ', 'Ꙭ' => 'ꙭ', 'Ꚁ' => 'ꚁ', 'Ꚃ' => 'ꚃ', 'Ꚅ' => 'ꚅ', 'Ꚇ' => 'ꚇ', 'Ꚉ' => 'ꚉ', 'Ꚋ' => 'ꚋ', 'Ꚍ' => 'ꚍ', 'Ꚏ' => 'ꚏ', 'Ꚑ' => 'ꚑ', 'Ꚓ' => 'ꚓ', 'Ꚕ' => 'ꚕ', 'Ꚗ' => 'ꚗ', 'Ꚙ' => 'ꚙ', 'Ꚛ' => 'ꚛ', 'Ꜣ' => 'ꜣ', 'Ꜥ' => 'ꜥ', 'Ꜧ' => 'ꜧ', 'Ꜩ' => 'ꜩ', 'Ꜫ' => 'ꜫ', 'Ꜭ' => 'ꜭ', 'Ꜯ' => 'ꜯ', 'Ꜳ' => 'ꜳ', 'Ꜵ' => 'ꜵ', 'Ꜷ' => 'ꜷ', 'Ꜹ' => 'ꜹ', 'Ꜻ' => 'ꜻ', 'Ꜽ' => 'ꜽ', 'Ꜿ' => 'ꜿ', 'Ꝁ' => 'ꝁ', 'Ꝃ' => 'ꝃ', 'Ꝅ' => 'ꝅ', 'Ꝇ' => 'ꝇ', 'Ꝉ' => 'ꝉ', 'Ꝋ' => 'ꝋ', 'Ꝍ' => 'ꝍ', 'Ꝏ' => 'ꝏ', 'Ꝑ' => 'ꝑ', 'Ꝓ' => 'ꝓ', 'Ꝕ' => 'ꝕ', 'Ꝗ' => 'ꝗ', 'Ꝙ' => 'ꝙ', 'Ꝛ' => 'ꝛ', 'Ꝝ' => 'ꝝ', 'Ꝟ' => 'ꝟ', 'Ꝡ' => 'ꝡ', 'Ꝣ' => 'ꝣ', 'Ꝥ' => 'ꝥ', 'Ꝧ' => 'ꝧ', 'Ꝩ' => 'ꝩ', 'Ꝫ' => 'ꝫ', 'Ꝭ' => 'ꝭ', 'Ꝯ' => 'ꝯ', 'Ꝺ' => 'ꝺ', 'Ꝼ' => 'ꝼ', 'Ᵹ' => 'ᵹ', 'Ꝿ' => 'ꝿ', 'Ꞁ' => 'ꞁ', 'Ꞃ' => 'ꞃ', 'Ꞅ' => 'ꞅ', 'Ꞇ' => 'ꞇ', 'Ꞌ' => 'ꞌ', 'Ɥ' => 'ɥ', 'Ꞑ' => 'ꞑ', 'Ꞓ' => 'ꞓ', 'Ꞗ' => 'ꞗ', 'Ꞙ' => 'ꞙ', 'Ꞛ' => 'ꞛ', 'Ꞝ' => 'ꞝ', 'Ꞟ' => 'ꞟ', 'Ꞡ' => 'ꞡ', 'Ꞣ' => 'ꞣ', 'Ꞥ' => 'ꞥ', 'Ꞧ' => 'ꞧ', 'Ꞩ' => 'ꞩ', 'Ɦ' => 'ɦ', 'Ɜ' => 'ɜ', 'Ɡ' => 'ɡ', 'Ɬ' => 'ɬ', 'Ʞ' => 'ʞ', 'Ʇ' => 'ʇ', 'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z', '𐐀' => '𐐨', '𐐁' => '𐐩', '𐐂' => '𐐪', '𐐃' => '𐐫', '𐐄' => '𐐬', '𐐅' => '𐐭', '𐐆' => '𐐮', '𐐇' => '𐐯', '𐐈' => '𐐰', '𐐉' => '𐐱', '𐐊' => '𐐲', '𐐋' => '𐐳', '𐐌' => '𐐴', '𐐍' => '𐐵', '𐐎' => '𐐶', '𐐏' => '𐐷', '𐐐' => '𐐸', '𐐑' => '𐐹', '𐐒' => '𐐺', '𐐓' => '𐐻', '𐐔' => '𐐼', '𐐕' => '𐐽', '𐐖' => '𐐾', '𐐗' => '𐐿', '𐐘' => '𐑀', '𐐙' => '𐑁', '𐐚' => '𐑂', '𐐛' => '𐑃', '𐐜' => '𐑄', '𐐝' => '𐑅', '𐐞' => '𐑆', '𐐟' => '𐑇', '𐐠' => '𐑈', '𐐡' => '𐑉', '𐐢' => '𐑊', '𐐣' => '𐑋', '𐐤' => '𐑌', '𐐥' => '𐑍', '𐐦' => '𐑎', '𐐧' => '𐑏', '𑢠' => '𑣀', '𑢡' => '𑣁', '𑢢' => '𑣂', '𑢣' => '𑣃', '𑢤' => '𑣄', '𑢥' => '𑣅', '𑢦' => '𑣆', '𑢧' => '𑣇', '𑢨' => '𑣈', '𑢩' => '𑣉', '𑢪' => '𑣊', '𑢫' => '𑣋', '𑢬' => '𑣌', '𑢭' => '𑣍', '𑢮' => '𑣎', '𑢯' => '𑣏', '𑢰' => '𑣐', '𑢱' => '𑣑', '𑢲' => '𑣒', '𑢳' => '𑣓', '𑢴' => '𑣔', '𑢵' => '𑣕', '𑢶' => '𑣖', '𑢷' => '𑣗', '𑢸' => '𑣘', '𑢹' => '𑣙', '𑢺' => '𑣚', '𑢻' => '𑣛', '𑢼' => '𑣜', '𑢽' => '𑣝', '𑢾' => '𑣞', '𑢿' => '𑣟', ); * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Mbstring as p; if (!function_exists('mb_strlen')) { define('MB_CASE_UPPER', 0); define('MB_CASE_LOWER', 1); define('MB_CASE_TITLE', 2); function mb_convert_encoding($s, $to, $from = null) { return p\Mbstring::mb_convert_encoding($s, $to, $from); } function mb_decode_mimeheader($s) { return p\Mbstring::mb_decode_mimeheader($s); } function mb_encode_mimeheader($s, $charset = null, $transferEnc = null, $lf = null, $indent = null) { return p\Mbstring::mb_encode_mimeheader($s, $charset, $transferEnc, $lf, $indent); } function mb_decode_numericentity($s, $convmap, $enc = null) { return p\Mbstring::mb_decode_numericentity($s, $convmap, $enc); } function mb_encode_numericentity($s, $convmap, $enc = null, $is_hex = false) { return p\Mbstring::mb_encode_numericentity($s, $convmap, $enc, $is_hex); } function mb_convert_case($s, $mode, $enc = null) { return p\Mbstring::mb_convert_case($s, $mode, $enc); } function mb_internal_encoding($enc = null) { return p\Mbstring::mb_internal_encoding($enc); } function mb_language($lang = null) { return p\Mbstring::mb_language($lang); } function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } function mb_check_encoding($var = null, $encoding = null) { return p\Mbstring::mb_check_encoding($var, $encoding); } function mb_detect_encoding($str, $encodingList = null, $strict = false) { return p\Mbstring::mb_detect_encoding($str, $encodingList, $strict); } function mb_detect_order($encodingList = null) { return p\Mbstring::mb_detect_order($encodingList); } function mb_parse_str($s, &$result = array()) { parse_str($s, $result); } function mb_strlen($s, $enc = null) { return p\Mbstring::mb_strlen($s, $enc); } function mb_strpos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strpos($s, $needle, $offset, $enc); } function mb_strtolower($s, $enc = null) { return p\Mbstring::mb_strtolower($s, $enc); } function mb_strtoupper($s, $enc = null) { return p\Mbstring::mb_strtoupper($s, $enc); } function mb_substitute_character($char = null) { return p\Mbstring::mb_substitute_character($char); } function mb_substr($s, $start, $length = 2147483647, $enc = null) { return p\Mbstring::mb_substr($s, $start, $length, $enc); } function mb_stripos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_stripos($s, $needle, $offset, $enc); } function mb_stristr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_stristr($s, $needle, $part, $enc); } function mb_strrchr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strrchr($s, $needle, $part, $enc); } function mb_strrichr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strrichr($s, $needle, $part, $enc); } function mb_strripos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strripos($s, $needle, $offset, $enc); } function mb_strrpos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strrpos($s, $needle, $offset, $enc); } function mb_strstr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strstr($s, $needle, $part, $enc); } function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } function mb_http_output($enc = null) { return p\Mbstring::mb_http_output($enc); } function mb_strwidth($s, $enc = null) { return p\Mbstring::mb_strwidth($s, $enc); } function mb_substr_count($haystack, $needle, $enc = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $enc); } function mb_output_handler($contents, $status) { return p\Mbstring::mb_output_handler($contents, $status); } function mb_http_input($type = '') { return p\Mbstring::mb_http_input($type); } function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null) { return p\Mbstring::mb_convert_variables($toEncoding, $fromEncoding, $a, $b, $c, $d, $e, $f); } } if (!function_exists('mb_chr')) { function mb_ord($s, $enc = null) { return p\Mbstring::mb_ord($s, $enc); } function mb_chr($code, $enc = null) { return p\Mbstring::mb_chr($code, $enc); } function mb_scrub($s, $enc = null) { $enc = null === $enc ? mb_internal_encoding() : $enc; return mb_convert_encoding($s, $enc, $enc); } } if (!function_exists('mb_str_split')) { function mb_str_split($string, $split_length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $split_length, $encoding); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; /** * An executable finder specifically designed for the PHP executable. * * @author Fabien Potencier * @author Johannes M. Schmitt */ class PhpExecutableFinder { private $executableFinder; public function __construct() { $this->executableFinder = new ExecutableFinder(); } /** * Finds The PHP executable. * * @param bool $includeArgs Whether or not include command arguments * * @return string|false The PHP executable path or false if it cannot be found */ public function find($includeArgs = true) { $args = $this->findArguments(); $args = $includeArgs && $args ? ' '.implode(' ', $args) : ''; // HHVM support if (\defined('HHVM_VERSION')) { return (getenv('PHP_BINARY') ?: PHP_BINARY).$args; } // PHP_BINARY return the current sapi executable if (\defined('PHP_BINARY') && PHP_BINARY && \in_array(\PHP_SAPI, array('cli', 'cli-server', 'phpdbg'), true)) { return PHP_BINARY.$args; } if ($php = getenv('PHP_PATH')) { if (!@is_executable($php)) { return false; } return $php; } if ($php = getenv('PHP_PEAR_PHP_BIN')) { if (@is_executable($php)) { return $php; } } if (@is_executable($php = PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php'))) { return $php; } $dirs = array(PHP_BINDIR); if ('\\' === \DIRECTORY_SEPARATOR) { $dirs[] = 'C:\xampp\php\\'; } return $this->executableFinder->find('php', false, $dirs); } /** * Finds the PHP executable arguments. * * @return array The PHP executable arguments */ public function findArguments() { $arguments = array(); if (\defined('HHVM_VERSION')) { $arguments[] = '--php'; } elseif ('phpdbg' === \PHP_SAPI) { $arguments[] = '-qrr'; } return $arguments; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; /** * Generic executable finder. * * @author Fabien Potencier * @author Johannes M. Schmitt */ class ExecutableFinder { private $suffixes = array('.exe', '.bat', '.cmd', '.com'); /** * Replaces default suffixes of executable. */ public function setSuffixes(array $suffixes) { $this->suffixes = $suffixes; } /** * Adds new possible suffix to check for executable. * * @param string $suffix */ public function addSuffix($suffix) { $this->suffixes[] = $suffix; } /** * Finds an executable by name. * * @param string $name The executable name (without the extension) * @param string $default The default to return if no executable is found * @param array $extraDirs Additional dirs to check into * * @return string The executable path or default value */ public function find($name, $default = null, array $extraDirs = array()) { if (ini_get('open_basedir')) { $searchPath = explode(PATH_SEPARATOR, ini_get('open_basedir')); $dirs = array(); foreach ($searchPath as $path) { // Silencing against https://bugs.php.net/69240 if (@is_dir($path)) { $dirs[] = $path; } else { if (basename($path) == $name && @is_executable($path)) { return $path; } } } } else { $dirs = array_merge( explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')), $extraDirs ); } $suffixes = array(''); if ('\\' === \DIRECTORY_SEPARATOR) { $pathExt = getenv('PATHEXT'); $suffixes = array_merge($pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes); } foreach ($suffixes as $suffix) { foreach ($dirs as $dir) { if (@is_file($file = $dir.\DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === \DIRECTORY_SEPARATOR || @is_executable($file))) { return $file; } } } return $default; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; use Symfony\Component\Process\Exception\RuntimeException; /** * PhpProcess runs a PHP script in an independent process. * * $p = new PhpProcess(''); * $p->run(); * print $p->getOutput()."\n"; * * @author Fabien Potencier */ class PhpProcess extends Process { /** * @param string $script The PHP script to run (as a string) * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param int $timeout The timeout in seconds * @param array $options An array of options for proc_open */ public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = array()) { $executableFinder = new PhpExecutableFinder(); if (false === $php = $executableFinder->find()) { $php = null; } if ('phpdbg' === \PHP_SAPI) { $file = tempnam(sys_get_temp_dir(), 'dbg'); file_put_contents($file, $script); register_shutdown_function('unlink', $file); $php .= ' '.ProcessUtils::escapeArgument($file); $script = null; } if ('\\' !== \DIRECTORY_SEPARATOR && null !== $php) { // exec is mandatory to deal with sending a signal to the process // see https://github.com/symfony/symfony/issues/5030 about prepending // command with exec $php = 'exec '.$php; } parent::__construct($php, $cwd, $env, $script, $timeout, $options); } /** * Sets the path to the PHP binary to use. */ public function setPhpBinary($php) { $this->setCommandLine($php); } /** * {@inheritdoc} */ public function start($callback = null) { if (null === $this->getCommandLine()) { throw new RuntimeException('Unable to find the PHP executable.'); } parent::start($callback); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; use Symfony\Component\Process\Exception\InvalidArgumentException; use Symfony\Component\Process\Exception\LogicException; /** * @author Kris Wallsmith */ class ProcessBuilder { private $arguments; private $cwd; private $env = array(); private $input; private $timeout = 60; private $options = array(); private $inheritEnv = true; private $prefix = array(); private $outputDisabled = false; /** * @param string[] $arguments An array of arguments */ public function __construct(array $arguments = array()) { $this->arguments = $arguments; } /** * Creates a process builder instance. * * @param string[] $arguments An array of arguments * * @return static */ public static function create(array $arguments = array()) { return new static($arguments); } /** * Adds an unescaped argument to the command string. * * @param string $argument A command argument * * @return $this */ public function add($argument) { $this->arguments[] = $argument; return $this; } /** * Adds a prefix to the command string. * * The prefix is preserved when resetting arguments. * * @param string|array $prefix A command prefix or an array of command prefixes * * @return $this */ public function setPrefix($prefix) { $this->prefix = \is_array($prefix) ? $prefix : array($prefix); return $this; } /** * Sets the arguments of the process. * * Arguments must not be escaped. * Previous arguments are removed. * * @param string[] $arguments * * @return $this */ public function setArguments(array $arguments) { $this->arguments = $arguments; return $this; } /** * Sets the working directory. * * @param string|null $cwd The working directory * * @return $this */ public function setWorkingDirectory($cwd) { $this->cwd = $cwd; return $this; } /** * Sets whether environment variables will be inherited or not. * * @param bool $inheritEnv * * @return $this */ public function inheritEnvironmentVariables($inheritEnv = true) { $this->inheritEnv = $inheritEnv; return $this; } /** * Sets an environment variable. * * Setting a variable overrides its previous value. Use `null` to unset a * defined environment variable. * * @param string $name The variable name * @param string|null $value The variable value * * @return $this */ public function setEnv($name, $value) { $this->env[$name] = $value; return $this; } /** * Adds a set of environment variables. * * Already existing environment variables with the same name will be * overridden by the new values passed to this method. Pass `null` to unset * a variable. * * @param array $variables The variables * * @return $this */ public function addEnvironmentVariables(array $variables) { $this->env = array_replace($this->env, $variables); return $this; } /** * Sets the input of the process. * * @param mixed $input The input as a string * * @return $this * * @throws InvalidArgumentException In case the argument is invalid * * Passing an object as an input is deprecated since version 2.5 and will be removed in 3.0. */ public function setInput($input) { $this->input = ProcessUtils::validateInput(__METHOD__, $input); return $this; } /** * Sets the process timeout. * * To disable the timeout, set this value to null. * * @param float|null $timeout * * @return $this * * @throws InvalidArgumentException */ public function setTimeout($timeout) { if (null === $timeout) { $this->timeout = null; return $this; } $timeout = (float) $timeout; if ($timeout < 0) { throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.'); } $this->timeout = $timeout; return $this; } /** * Adds a proc_open option. * * @param string $name The option name * @param string $value The option value * * @return $this */ public function setOption($name, $value) { $this->options[$name] = $value; return $this; } /** * Disables fetching output and error output from the underlying process. * * @return $this */ public function disableOutput() { $this->outputDisabled = true; return $this; } /** * Enables fetching output and error output from the underlying process. * * @return $this */ public function enableOutput() { $this->outputDisabled = false; return $this; } /** * Creates a Process instance and returns it. * * @return Process * * @throws LogicException In case no arguments have been provided */ public function getProcess() { if (0 === \count($this->prefix) && 0 === \count($this->arguments)) { throw new LogicException('You must add() command arguments before calling getProcess().'); } $options = $this->options; $arguments = array_merge($this->prefix, $this->arguments); $script = implode(' ', array_map(array(__NAMESPACE__.'\\ProcessUtils', 'escapeArgument'), $arguments)); if ($this->inheritEnv) { // include $_ENV for BC purposes $env = array_replace($_ENV, $_SERVER, $this->env); } else { $env = $this->env; } $process = new Process($script, $this->cwd, $env, $this->input, $this->timeout, $options); if ($this->outputDisabled) { $process->disableOutput(); } return $process; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; use Symfony\Component\Process\Exception\InvalidArgumentException; use Symfony\Component\Process\Exception\LogicException; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Exception\ProcessTimedOutException; use Symfony\Component\Process\Exception\RuntimeException; use Symfony\Component\Process\Pipes\PipesInterface; use Symfony\Component\Process\Pipes\UnixPipes; use Symfony\Component\Process\Pipes\WindowsPipes; /** * Process is a thin wrapper around proc_* functions to easily * start independent PHP processes. * * @author Fabien Potencier * @author Romain Neutron */ class Process { const ERR = 'err'; const OUT = 'out'; const STATUS_READY = 'ready'; const STATUS_STARTED = 'started'; const STATUS_TERMINATED = 'terminated'; const STDIN = 0; const STDOUT = 1; const STDERR = 2; // Timeout Precision in seconds. const TIMEOUT_PRECISION = 0.2; private $callback; private $commandline; private $cwd; private $env; private $input; private $starttime; private $lastOutputTime; private $timeout; private $idleTimeout; private $options; private $exitcode; private $fallbackStatus = array(); private $processInformation; private $outputDisabled = false; private $stdout; private $stderr; private $enhanceWindowsCompatibility = true; private $enhanceSigchildCompatibility; private $process; private $status = self::STATUS_READY; private $incrementalOutputOffset = 0; private $incrementalErrorOutputOffset = 0; private $tty; private $pty; private $useFileHandles = false; /** @var PipesInterface */ private $processPipes; private $latestSignal; private static $sigchild; /** * Exit codes translation table. * * User-defined errors must use exit codes in the 64-113 range. */ public static $exitCodes = array( 0 => 'OK', 1 => 'General error', 2 => 'Misuse of shell builtins', 126 => 'Invoked command cannot execute', 127 => 'Command not found', 128 => 'Invalid exit argument', // signals 129 => 'Hangup', 130 => 'Interrupt', 131 => 'Quit and dump core', 132 => 'Illegal instruction', 133 => 'Trace/breakpoint trap', 134 => 'Process aborted', 135 => 'Bus error: "access to undefined portion of memory object"', 136 => 'Floating point exception: "erroneous arithmetic operation"', 137 => 'Kill (terminate immediately)', 138 => 'User-defined 1', 139 => 'Segmentation violation', 140 => 'User-defined 2', 141 => 'Write to pipe with no one reading', 142 => 'Signal raised by alarm', 143 => 'Termination (request to terminate)', // 144 - not defined 145 => 'Child process terminated, stopped (or continued*)', 146 => 'Continue if stopped', 147 => 'Stop executing temporarily', 148 => 'Terminal stop signal', 149 => 'Background process attempting to read from tty ("in")', 150 => 'Background process attempting to write to tty ("out")', 151 => 'Urgent data available on socket', 152 => 'CPU time limit exceeded', 153 => 'File size limit exceeded', 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"', 155 => 'Profiling timer expired', // 156 - not defined 157 => 'Pollable event', // 158 - not defined 159 => 'Bad syscall', ); /** * @param string $commandline The command line to run * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param string|null $input The input * @param int|float|null $timeout The timeout in seconds or null to disable * @param array $options An array of options for proc_open * * @throws RuntimeException When proc_open is not installed */ public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array()) { if (!\function_exists('proc_open')) { throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.'); } $this->commandline = $commandline; $this->cwd = $cwd; // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected // @see : https://bugs.php.net/bug.php?id=51800 // @see : https://bugs.php.net/bug.php?id=50524 if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) { $this->cwd = getcwd(); } if (null !== $env) { $this->setEnv($env); } $this->setInput($input); $this->setTimeout($timeout); $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR; $this->pty = false; $this->enhanceSigchildCompatibility = '\\' !== \DIRECTORY_SEPARATOR && $this->isSigchildEnabled(); $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options); } public function __destruct() { $this->stop(0); } public function __clone() { $this->resetProcessData(); } /** * Runs the process. * * The callback receives the type of output (out or err) and * some bytes from the output in real-time. It allows to have feedback * from the independent process during execution. * * The STDOUT and STDERR are also available after the process is finished * via the getOutput() and getErrorOutput() methods. * * @param callable|null $callback A PHP callback to run whenever there is some * output available on STDOUT or STDERR * * @return int The exit status code * * @throws RuntimeException When process can't be launched * @throws RuntimeException When process stopped after receiving signal * @throws LogicException In case a callback is provided and output has been disabled */ public function run($callback = null) { $this->start($callback); return $this->wait(); } /** * Runs the process. * * This is identical to run() except that an exception is thrown if the process * exits with a non-zero exit code. * * @param callable|null $callback * * @return self * * @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled * @throws ProcessFailedException if the process didn't terminate successfully */ public function mustRun($callback = null) { if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.'); } if (0 !== $this->run($callback)) { throw new ProcessFailedException($this); } return $this; } /** * Starts the process and returns after writing the input to STDIN. * * This method blocks until all STDIN data is sent to the process then it * returns while the process runs in the background. * * The termination of the process can be awaited with wait(). * * The callback receives the type of output (out or err) and some bytes from * the output in real-time while writing the standard input to the process. * It allows to have feedback from the independent process during execution. * * @param callable|null $callback A PHP callback to run whenever there is some * output available on STDOUT or STDERR * * @throws RuntimeException When process can't be launched * @throws RuntimeException When process is already running * @throws LogicException In case a callback is provided and output has been disabled */ public function start($callback = null) { if ($this->isRunning()) { throw new RuntimeException('Process is already running'); } if ($this->outputDisabled && null !== $callback) { throw new LogicException('Output has been disabled, enable it to allow the use of a callback.'); } $this->resetProcessData(); $this->starttime = $this->lastOutputTime = microtime(true); $this->callback = $this->buildCallback($callback); $descriptors = $this->getDescriptors(); $commandline = $this->commandline; if ('\\' === \DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) { $commandline = 'cmd /V:ON /E:ON /D /C "('.$commandline.')'; foreach ($this->processPipes->getFiles() as $offset => $filename) { $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename); } $commandline .= '"'; if (!isset($this->options['bypass_shell'])) { $this->options['bypass_shell'] = true; } } elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { // last exit code is output on the fourth pipe and caught to work around --enable-sigchild $descriptors[3] = array('pipe', 'w'); // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input $commandline = '{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;'; $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code'; // Workaround for the bug, when PTS functionality is enabled. // @see : https://bugs.php.net/69442 $ptsWorkaround = fopen(__FILE__, 'r'); } $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options); if (!\is_resource($this->process)) { throw new RuntimeException('Unable to launch a new process.'); } $this->status = self::STATUS_STARTED; if (isset($descriptors[3])) { $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]); } if ($this->tty) { return; } $this->updateStatus(false); $this->checkTimeout(); } /** * Restarts the process. * * Be warned that the process is cloned before being started. * * @param callable|null $callback A PHP callback to run whenever there is some * output available on STDOUT or STDERR * * @return $this * * @throws RuntimeException When process can't be launched * @throws RuntimeException When process is already running * * @see start() */ public function restart($callback = null) { if ($this->isRunning()) { throw new RuntimeException('Process is already running'); } $process = clone $this; $process->start($callback); return $process; } /** * Waits for the process to terminate. * * The callback receives the type of output (out or err) and some bytes * from the output in real-time while writing the standard input to the process. * It allows to have feedback from the independent process during execution. * * @param callable|null $callback A valid PHP callback * * @return int The exitcode of the process * * @throws RuntimeException When process timed out * @throws RuntimeException When process stopped after receiving signal * @throws LogicException When process is not yet started */ public function wait($callback = null) { $this->requireProcessIsStarted(__FUNCTION__); $this->updateStatus(false); if (null !== $callback) { $this->callback = $this->buildCallback($callback); } do { $this->checkTimeout(); $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen(); $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running); } while ($running); while ($this->isRunning()) { usleep(1000); } if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) { throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig'])); } return $this->exitcode; } /** * Returns the Pid (process identifier), if applicable. * * @return int|null The process id if running, null otherwise */ public function getPid() { return $this->isRunning() ? $this->processInformation['pid'] : null; } /** * Sends a POSIX signal to the process. * * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php) * * @return $this * * @throws LogicException In case the process is not running * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed * @throws RuntimeException In case of failure */ public function signal($signal) { $this->doSignal($signal, true); return $this; } /** * Disables fetching output and error output from the underlying process. * * @return $this * * @throws RuntimeException In case the process is already running * @throws LogicException if an idle timeout is set */ public function disableOutput() { if ($this->isRunning()) { throw new RuntimeException('Disabling output while the process is running is not possible.'); } if (null !== $this->idleTimeout) { throw new LogicException('Output can not be disabled while an idle timeout is set.'); } $this->outputDisabled = true; return $this; } /** * Enables fetching output and error output from the underlying process. * * @return $this * * @throws RuntimeException In case the process is already running */ public function enableOutput() { if ($this->isRunning()) { throw new RuntimeException('Enabling output while the process is running is not possible.'); } $this->outputDisabled = false; return $this; } /** * Returns true in case the output is disabled, false otherwise. * * @return bool */ public function isOutputDisabled() { return $this->outputDisabled; } /** * Returns the current output of the process (STDOUT). * * @return string The process output * * @throws LogicException in case the output has been disabled * @throws LogicException In case the process is not started */ public function getOutput() { $this->readPipesForOutput(__FUNCTION__); if (false === $ret = stream_get_contents($this->stdout, -1, 0)) { return ''; } return $ret; } /** * Returns the output incrementally. * * In comparison with the getOutput method which always return the whole * output, this one returns the new output since the last call. * * @return string The process output since the last call * * @throws LogicException in case the output has been disabled * @throws LogicException In case the process is not started */ public function getIncrementalOutput() { $this->readPipesForOutput(__FUNCTION__); $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset); $this->incrementalOutputOffset = ftell($this->stdout); if (false === $latest) { return ''; } return $latest; } /** * Clears the process output. * * @return $this */ public function clearOutput() { ftruncate($this->stdout, 0); fseek($this->stdout, 0); $this->incrementalOutputOffset = 0; return $this; } /** * Returns the current error output of the process (STDERR). * * @return string The process error output * * @throws LogicException in case the output has been disabled * @throws LogicException In case the process is not started */ public function getErrorOutput() { $this->readPipesForOutput(__FUNCTION__); if (false === $ret = stream_get_contents($this->stderr, -1, 0)) { return ''; } return $ret; } /** * Returns the errorOutput incrementally. * * In comparison with the getErrorOutput method which always return the * whole error output, this one returns the new error output since the last * call. * * @return string The process error output since the last call * * @throws LogicException in case the output has been disabled * @throws LogicException In case the process is not started */ public function getIncrementalErrorOutput() { $this->readPipesForOutput(__FUNCTION__); $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset); $this->incrementalErrorOutputOffset = ftell($this->stderr); if (false === $latest) { return ''; } return $latest; } /** * Clears the process output. * * @return $this */ public function clearErrorOutput() { ftruncate($this->stderr, 0); fseek($this->stderr, 0); $this->incrementalErrorOutputOffset = 0; return $this; } /** * Returns the exit code returned by the process. * * @return int|null The exit status code, null if the Process is not terminated * * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled */ public function getExitCode() { if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.'); } $this->updateStatus(false); return $this->exitcode; } /** * Returns a string representation for the exit code returned by the process. * * This method relies on the Unix exit code status standardization * and might not be relevant for other operating systems. * * @return string|null A string representation for the exit status code, null if the Process is not terminated * * @see http://tldp.org/LDP/abs/html/exitcodes.html * @see http://en.wikipedia.org/wiki/Unix_signal */ public function getExitCodeText() { if (null === $exitcode = $this->getExitCode()) { return; } return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error'; } /** * Checks if the process ended successfully. * * @return bool true if the process ended successfully, false otherwise */ public function isSuccessful() { return 0 === $this->getExitCode(); } /** * Returns true if the child process has been terminated by an uncaught signal. * * It always returns false on Windows. * * @return bool * * @throws RuntimeException In case --enable-sigchild is activated * @throws LogicException In case the process is not terminated */ public function hasBeenSignaled() { $this->requireProcessIsTerminated(__FUNCTION__); if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.'); } return $this->processInformation['signaled']; } /** * Returns the number of the signal that caused the child process to terminate its execution. * * It is only meaningful if hasBeenSignaled() returns true. * * @return int * * @throws RuntimeException In case --enable-sigchild is activated * @throws LogicException In case the process is not terminated */ public function getTermSignal() { $this->requireProcessIsTerminated(__FUNCTION__); if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) { throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.'); } return $this->processInformation['termsig']; } /** * Returns true if the child process has been stopped by a signal. * * It always returns false on Windows. * * @return bool * * @throws LogicException In case the process is not terminated */ public function hasBeenStopped() { $this->requireProcessIsTerminated(__FUNCTION__); return $this->processInformation['stopped']; } /** * Returns the number of the signal that caused the child process to stop its execution. * * It is only meaningful if hasBeenStopped() returns true. * * @return int * * @throws LogicException In case the process is not terminated */ public function getStopSignal() { $this->requireProcessIsTerminated(__FUNCTION__); return $this->processInformation['stopsig']; } /** * Checks if the process is currently running. * * @return bool true if the process is currently running, false otherwise */ public function isRunning() { if (self::STATUS_STARTED !== $this->status) { return false; } $this->updateStatus(false); return $this->processInformation['running']; } /** * Checks if the process has been started with no regard to the current state. * * @return bool true if status is ready, false otherwise */ public function isStarted() { return self::STATUS_READY != $this->status; } /** * Checks if the process is terminated. * * @return bool true if process is terminated, false otherwise */ public function isTerminated() { $this->updateStatus(false); return self::STATUS_TERMINATED == $this->status; } /** * Gets the process status. * * The status is one of: ready, started, terminated. * * @return string The current process status */ public function getStatus() { $this->updateStatus(false); return $this->status; } /** * Stops the process. * * @param int|float $timeout The timeout in seconds * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9) * * @return int The exit-code of the process */ public function stop($timeout = 10, $signal = null) { $timeoutMicro = microtime(true) + $timeout; if ($this->isRunning()) { // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here $this->doSignal(15, false); do { usleep(1000); } while ($this->isRunning() && microtime(true) < $timeoutMicro); if ($this->isRunning()) { // Avoid exception here: process is supposed to be running, but it might have stopped just // after this line. In any case, let's silently discard the error, we cannot do anything. $this->doSignal($signal ?: 9, false); } } if ($this->isRunning()) { if (isset($this->fallbackStatus['pid'])) { unset($this->fallbackStatus['pid']); return $this->stop(0, $signal); } $this->close(); } return $this->exitcode; } /** * Adds a line to the STDOUT stream. * * @internal * * @param string $line The line to append */ public function addOutput($line) { $this->lastOutputTime = microtime(true); fseek($this->stdout, 0, SEEK_END); fwrite($this->stdout, $line); fseek($this->stdout, $this->incrementalOutputOffset); } /** * Adds a line to the STDERR stream. * * @internal * * @param string $line The line to append */ public function addErrorOutput($line) { $this->lastOutputTime = microtime(true); fseek($this->stderr, 0, SEEK_END); fwrite($this->stderr, $line); fseek($this->stderr, $this->incrementalErrorOutputOffset); } /** * Gets the command line to be executed. * * @return string The command to execute */ public function getCommandLine() { return $this->commandline; } /** * Sets the command line to be executed. * * @param string $commandline The command to execute * * @return self The current Process instance */ public function setCommandLine($commandline) { $this->commandline = $commandline; return $this; } /** * Gets the process timeout (max. runtime). * * @return float|null The timeout in seconds or null if it's disabled */ public function getTimeout() { return $this->timeout; } /** * Gets the process idle timeout (max. time since last output). * * @return float|null The timeout in seconds or null if it's disabled */ public function getIdleTimeout() { return $this->idleTimeout; } /** * Sets the process timeout (max. runtime). * * To disable the timeout, set this value to null. * * @param int|float|null $timeout The timeout in seconds * * @return self The current Process instance * * @throws InvalidArgumentException if the timeout is negative */ public function setTimeout($timeout) { $this->timeout = $this->validateTimeout($timeout); return $this; } /** * Sets the process idle timeout (max. time since last output). * * To disable the timeout, set this value to null. * * @param int|float|null $timeout The timeout in seconds * * @return self The current Process instance * * @throws LogicException if the output is disabled * @throws InvalidArgumentException if the timeout is negative */ public function setIdleTimeout($timeout) { if (null !== $timeout && $this->outputDisabled) { throw new LogicException('Idle timeout can not be set while the output is disabled.'); } $this->idleTimeout = $this->validateTimeout($timeout); return $this; } /** * Enables or disables the TTY mode. * * @param bool $tty True to enabled and false to disable * * @return self The current Process instance * * @throws RuntimeException In case the TTY mode is not supported */ public function setTty($tty) { if ('\\' === \DIRECTORY_SEPARATOR && $tty) { throw new RuntimeException('TTY mode is not supported on Windows platform.'); } if ($tty) { static $isTtySupported; if (null === $isTtySupported) { $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', array(array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w')), $pipes); } if (!$isTtySupported) { throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.'); } } $this->tty = (bool) $tty; return $this; } /** * Checks if the TTY mode is enabled. * * @return bool true if the TTY mode is enabled, false otherwise */ public function isTty() { return $this->tty; } /** * Sets PTY mode. * * @param bool $bool * * @return self */ public function setPty($bool) { $this->pty = (bool) $bool; return $this; } /** * Returns PTY state. * * @return bool */ public function isPty() { return $this->pty; } /** * Gets the working directory. * * @return string|null The current working directory or null on failure */ public function getWorkingDirectory() { if (null === $this->cwd) { // getcwd() will return false if any one of the parent directories does not have // the readable or search mode set, even if the current directory does return getcwd() ?: null; } return $this->cwd; } /** * Sets the current working directory. * * @param string $cwd The new working directory * * @return self The current Process instance */ public function setWorkingDirectory($cwd) { $this->cwd = $cwd; return $this; } /** * Gets the environment variables. * * @return array The current environment variables */ public function getEnv() { return $this->env; } /** * Sets the environment variables. * * Each environment variable value should be a string. * If it is an array, the variable is ignored. * * That happens in PHP when 'argv' is registered into * the $_ENV array for instance. * * @param array $env The new environment variables * * @return self The current Process instance */ public function setEnv(array $env) { // Process can not handle env values that are arrays $env = array_filter($env, function ($value) { return !\is_array($value); }); $this->env = array(); foreach ($env as $key => $value) { $this->env[$key] = (string) $value; } return $this; } /** * Gets the contents of STDIN. * * @return string|null The current contents * * @deprecated since version 2.5, to be removed in 3.0. * Use setInput() instead. * This method is deprecated in favor of getInput. */ public function getStdin() { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.5 and will be removed in 3.0. Use the getInput() method instead.', E_USER_DEPRECATED); return $this->getInput(); } /** * Gets the Process input. * * @return string|null The Process input */ public function getInput() { return $this->input; } /** * Sets the contents of STDIN. * * @param string|null $stdin The new contents * * @return self The current Process instance * * @deprecated since version 2.5, to be removed in 3.0. * Use setInput() instead. * * @throws LogicException In case the process is running * @throws InvalidArgumentException In case the argument is invalid */ public function setStdin($stdin) { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.5 and will be removed in 3.0. Use the setInput() method instead.', E_USER_DEPRECATED); return $this->setInput($stdin); } /** * Sets the input. * * This content will be passed to the underlying process standard input. * * @param mixed $input The content * * @return self The current Process instance * * @throws LogicException In case the process is running * * Passing an object as an input is deprecated since version 2.5 and will be removed in 3.0. */ public function setInput($input) { if ($this->isRunning()) { throw new LogicException('Input can not be set while the process is running.'); } $this->input = ProcessUtils::validateInput(__METHOD__, $input); return $this; } /** * Gets the options for proc_open. * * @return array The current options */ public function getOptions() { return $this->options; } /** * Sets the options for proc_open. * * @param array $options The new options * * @return self The current Process instance */ public function setOptions(array $options) { $this->options = $options; return $this; } /** * Gets whether or not Windows compatibility is enabled. * * This is true by default. * * @return bool */ public function getEnhanceWindowsCompatibility() { return $this->enhanceWindowsCompatibility; } /** * Sets whether or not Windows compatibility is enabled. * * @param bool $enhance * * @return self The current Process instance */ public function setEnhanceWindowsCompatibility($enhance) { $this->enhanceWindowsCompatibility = (bool) $enhance; return $this; } /** * Returns whether sigchild compatibility mode is activated or not. * * @return bool */ public function getEnhanceSigchildCompatibility() { return $this->enhanceSigchildCompatibility; } /** * Activates sigchild compatibility mode. * * Sigchild compatibility mode is required to get the exit code and * determine the success of a process when PHP has been compiled with * the --enable-sigchild option * * @param bool $enhance * * @return self The current Process instance */ public function setEnhanceSigchildCompatibility($enhance) { $this->enhanceSigchildCompatibility = (bool) $enhance; return $this; } /** * Performs a check between the timeout definition and the time the process started. * * In case you run a background process (with the start method), you should * trigger this method regularly to ensure the process timeout * * @throws ProcessTimedOutException In case the timeout was reached */ public function checkTimeout() { if (self::STATUS_STARTED !== $this->status) { return; } if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) { $this->stop(0); throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL); } if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) { $this->stop(0); throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE); } } /** * Returns whether PTY is supported on the current operating system. * * @return bool */ public static function isPtySupported() { static $result; if (null !== $result) { return $result; } if ('\\' === \DIRECTORY_SEPARATOR) { return $result = false; } return $result = (bool) @proc_open('echo 1 >/dev/null', array(array('pty'), array('pty'), array('pty')), $pipes); } /** * Creates the descriptors needed by the proc_open. * * @return array */ private function getDescriptors() { if ('\\' === \DIRECTORY_SEPARATOR) { $this->processPipes = WindowsPipes::create($this, $this->input); } else { $this->processPipes = UnixPipes::create($this, $this->input); } return $this->processPipes->getDescriptors(); } /** * Builds up the callback used by wait(). * * The callbacks adds all occurred output to the specific buffer and calls * the user callback (if present) with the received output. * * @param callable|null $callback The user defined PHP callback * * @return \Closure A PHP closure */ protected function buildCallback($callback) { $that = $this; $out = self::OUT; $callback = function ($type, $data) use ($that, $callback, $out) { if ($out == $type) { $that->addOutput($data); } else { $that->addErrorOutput($data); } if (null !== $callback) { \call_user_func($callback, $type, $data); } }; return $callback; } /** * Updates the status of the process, reads pipes. * * @param bool $blocking Whether to use a blocking read call */ protected function updateStatus($blocking) { if (self::STATUS_STARTED !== $this->status) { return; } $this->processInformation = proc_get_status($this->process); $running = $this->processInformation['running']; $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running); if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { $this->processInformation = $this->fallbackStatus + $this->processInformation; } if (!$running) { $this->close(); } } /** * Returns whether PHP has been compiled with the '--enable-sigchild' option or not. * * @return bool */ protected function isSigchildEnabled() { if (null !== self::$sigchild) { return self::$sigchild; } if (!\function_exists('phpinfo') || \defined('HHVM_VERSION')) { return self::$sigchild = false; } ob_start(); phpinfo(INFO_GENERAL); return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild'); } /** * Reads pipes for the freshest output. * * @param string $caller The name of the method that needs fresh outputs * * @throws LogicException in case output has been disabled or process is not started */ private function readPipesForOutput($caller) { if ($this->outputDisabled) { throw new LogicException('Output has been disabled.'); } $this->requireProcessIsStarted($caller); $this->updateStatus(false); } /** * Validates and returns the filtered timeout. * * @param int|float|null $timeout * * @return float|null * * @throws InvalidArgumentException if the given timeout is a negative number */ private function validateTimeout($timeout) { $timeout = (float) $timeout; if (0.0 === $timeout) { $timeout = null; } elseif ($timeout < 0) { throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.'); } return $timeout; } /** * Reads pipes, executes callback. * * @param bool $blocking Whether to use blocking calls or not * @param bool $close Whether to close file handles or not */ private function readPipes($blocking, $close) { $result = $this->processPipes->readAndWrite($blocking, $close); $callback = $this->callback; foreach ($result as $type => $data) { if (3 !== $type) { $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data); } elseif (!isset($this->fallbackStatus['signaled'])) { $this->fallbackStatus['exitcode'] = (int) $data; } } } /** * Closes process resource, closes file handles, sets the exitcode. * * @return int The exitcode */ private function close() { $this->processPipes->close(); if (\is_resource($this->process)) { proc_close($this->process); } $this->exitcode = $this->processInformation['exitcode']; $this->status = self::STATUS_TERMINATED; if (-1 === $this->exitcode) { if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) { // if process has been signaled, no exitcode but a valid termsig, apply Unix convention $this->exitcode = 128 + $this->processInformation['termsig']; } elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) { $this->processInformation['signaled'] = true; $this->processInformation['termsig'] = -1; } } // Free memory from self-reference callback created by buildCallback // Doing so in other contexts like __destruct or by garbage collector is ineffective // Now pipes are closed, so the callback is no longer necessary $this->callback = null; return $this->exitcode; } /** * Resets data related to the latest run of the process. */ private function resetProcessData() { $this->starttime = null; $this->callback = null; $this->exitcode = null; $this->fallbackStatus = array(); $this->processInformation = null; $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b'); $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b'); $this->process = null; $this->latestSignal = null; $this->status = self::STATUS_READY; $this->incrementalOutputOffset = 0; $this->incrementalErrorOutputOffset = 0; } /** * Sends a POSIX signal to the process. * * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php) * @param bool $throwException Whether to throw exception in case signal failed * * @return bool True if the signal was sent successfully, false otherwise * * @throws LogicException In case the process is not running * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed * @throws RuntimeException In case of failure */ private function doSignal($signal, $throwException) { if (null === $pid = $this->getPid()) { if ($throwException) { throw new LogicException('Can not send signal on a non running process.'); } return false; } if ('\\' === \DIRECTORY_SEPARATOR) { exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode); if ($exitCode && $this->isRunning()) { if ($throwException) { throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output))); } return false; } } else { if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) { $ok = @proc_terminate($this->process, $signal); } elseif (\function_exists('posix_kill')) { $ok = @posix_kill($pid, $signal); } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) { $ok = false === fgets($pipes[2]); } if (!$ok) { if ($throwException) { throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal)); } return false; } } $this->latestSignal = (int) $signal; $this->fallbackStatus['signaled'] = true; $this->fallbackStatus['exitcode'] = -1; $this->fallbackStatus['termsig'] = $this->latestSignal; return true; } /** * Ensures the process is running or terminated, throws a LogicException if the process has a not started. * * @param string $functionName The function name that was called * * @throws LogicException if the process has not run */ private function requireProcessIsStarted($functionName) { if (!$this->isStarted()) { throw new LogicException(sprintf('Process must be started before calling %s.', $functionName)); } } /** * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`. * * @param string $functionName The function name that was called * * @throws LogicException if the process is not yet terminated */ private function requireProcessIsTerminated($functionName) { if (!$this->isTerminated()) { throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName)); } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Pipes; use Symfony\Component\Process\Exception\RuntimeException; use Symfony\Component\Process\Process; /** * WindowsPipes implementation uses temporary files as handles. * * @see https://bugs.php.net/bug.php?id=51800 * @see https://bugs.php.net/bug.php?id=65650 * * @author Romain Neutron * * @internal */ class WindowsPipes extends AbstractPipes { private $files = array(); private $fileHandles = array(); private $lockHandles = array(); private $readBytes = array( Process::STDOUT => 0, Process::STDERR => 0, ); private $disableOutput; public function __construct($disableOutput, $input) { $this->disableOutput = (bool) $disableOutput; if (!$this->disableOutput) { // Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big. // Workaround for this problem is to use temporary files instead of pipes on Windows platform. // // @see https://bugs.php.net/bug.php?id=51800 $pipes = array( Process::STDOUT => Process::OUT, Process::STDERR => Process::ERR, ); $tmpDir = sys_get_temp_dir(); $lastError = 'unknown reason'; set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; }); for ($i = 0;; ++$i) { foreach ($pipes as $pipe => $name) { $file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name); if (!$h = fopen($file.'.lock', 'w')) { restore_error_handler(); throw new RuntimeException(sprintf('A temporary file could not be opened to write the process output: %s', $lastError)); } if (!flock($h, LOCK_EX | LOCK_NB)) { continue 2; } if (isset($this->lockHandles[$pipe])) { flock($this->lockHandles[$pipe], LOCK_UN); fclose($this->lockHandles[$pipe]); } $this->lockHandles[$pipe] = $h; if (!fclose(fopen($file, 'w')) || !$h = fopen($file, 'r')) { flock($this->lockHandles[$pipe], LOCK_UN); fclose($this->lockHandles[$pipe]); unset($this->lockHandles[$pipe]); continue 2; } $this->fileHandles[$pipe] = $h; $this->files[$pipe] = $file; } break; } restore_error_handler(); } parent::__construct($input); } public function __destruct() { $this->close(); } /** * {@inheritdoc} */ public function getDescriptors() { if ($this->disableOutput) { $nullstream = fopen('NUL', 'c'); return array( array('pipe', 'r'), $nullstream, $nullstream, ); } // We're not using pipe on Windows platform as it hangs (https://bugs.php.net/bug.php?id=51800) // We're not using file handles as it can produce corrupted output https://bugs.php.net/bug.php?id=65650 // So we redirect output within the commandline and pass the nul device to the process return array( array('pipe', 'r'), array('file', 'NUL', 'w'), array('file', 'NUL', 'w'), ); } /** * {@inheritdoc} */ public function getFiles() { return $this->files; } /** * {@inheritdoc} */ public function readAndWrite($blocking, $close = false) { $this->unblock(); $w = $this->write(); $read = $r = $e = array(); if ($blocking) { if ($w) { @stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6); } elseif ($this->fileHandles) { usleep(Process::TIMEOUT_PRECISION * 1E6); } } foreach ($this->fileHandles as $type => $fileHandle) { $data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]); if (isset($data[0])) { $this->readBytes[$type] += \strlen($data); $read[$type] = $data; } if ($close) { ftruncate($fileHandle, 0); fclose($fileHandle); flock($this->lockHandles[$type], LOCK_UN); fclose($this->lockHandles[$type]); unset($this->fileHandles[$type], $this->lockHandles[$type]); } } return $read; } /** * {@inheritdoc} */ public function areOpen() { return $this->pipes && $this->fileHandles; } /** * {@inheritdoc} */ public function close() { parent::close(); foreach ($this->fileHandles as $type => $handle) { ftruncate($handle, 0); fclose($handle); flock($this->lockHandles[$type], LOCK_UN); fclose($this->lockHandles[$type]); } $this->fileHandles = $this->lockHandles = array(); } /** * Creates a new WindowsPipes instance. * * @param Process $process The process * @param $input * * @return static */ public static function create(Process $process, $input) { return new static($process->isOutputDisabled(), $input); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Pipes; /** * @author Romain Neutron * * @internal */ abstract class AbstractPipes implements PipesInterface { public $pipes = array(); private $inputBuffer = ''; private $input; private $blocked = true; private $lastError; /** * @param resource|null $input */ public function __construct($input) { if (\is_resource($input)) { $this->input = $input; } elseif (\is_string($input)) { $this->inputBuffer = $input; } else { $this->inputBuffer = (string) $input; } } /** * {@inheritdoc} */ public function close() { foreach ($this->pipes as $pipe) { fclose($pipe); } $this->pipes = array(); } /** * Returns true if a system call has been interrupted. * * @return bool */ protected function hasSystemCallBeenInterrupted() { $lastError = $this->lastError; $this->lastError = null; // stream_select returns false when the `select` system call is interrupted by an incoming signal return null !== $lastError && false !== stripos($lastError, 'interrupted system call'); } /** * Unblocks streams. */ protected function unblock() { if (!$this->blocked) { return; } foreach ($this->pipes as $pipe) { stream_set_blocking($pipe, 0); } if (null !== $this->input) { stream_set_blocking($this->input, 0); } $this->blocked = false; } /** * Writes input to stdin. */ protected function write() { if (!isset($this->pipes[0])) { return; } $input = $this->input; $r = $e = array(); $w = array($this->pipes[0]); // let's have a look if something changed in streams if (false === @stream_select($r, $w, $e, 0, 0)) { return; } foreach ($w as $stdin) { if (isset($this->inputBuffer[0])) { $written = fwrite($stdin, $this->inputBuffer); $this->inputBuffer = substr($this->inputBuffer, $written); if (isset($this->inputBuffer[0])) { return array($this->pipes[0]); } } if ($input) { for (;;) { $data = fread($input, self::CHUNK_SIZE); if (!isset($data[0])) { break; } $written = fwrite($stdin, $data); $data = substr($data, $written); if (isset($data[0])) { $this->inputBuffer = $data; return array($this->pipes[0]); } } if (feof($input)) { // no more data to read on input resource // use an empty buffer in the next reads $this->input = null; } } } // no input to read on resource, buffer is empty if (null === $this->input && !isset($this->inputBuffer[0])) { fclose($this->pipes[0]); unset($this->pipes[0]); } elseif (!$w) { return array($this->pipes[0]); } } /** * @internal */ public function handleError($type, $msg) { $this->lastError = $msg; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Pipes; use Symfony\Component\Process\Process; /** * UnixPipes implementation uses unix pipes as handles. * * @author Romain Neutron * * @internal */ class UnixPipes extends AbstractPipes { private $ttyMode; private $ptyMode; private $disableOutput; public function __construct($ttyMode, $ptyMode, $input, $disableOutput) { $this->ttyMode = (bool) $ttyMode; $this->ptyMode = (bool) $ptyMode; $this->disableOutput = (bool) $disableOutput; parent::__construct($input); } public function __destruct() { $this->close(); } /** * {@inheritdoc} */ public function getDescriptors() { if ($this->disableOutput) { $nullstream = fopen('/dev/null', 'c'); return array( array('pipe', 'r'), $nullstream, $nullstream, ); } if ($this->ttyMode) { return array( array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w'), ); } if ($this->ptyMode && Process::isPtySupported()) { return array( array('pty'), array('pty'), array('pty'), ); } return array( array('pipe', 'r'), array('pipe', 'w'), // stdout array('pipe', 'w'), // stderr ); } /** * {@inheritdoc} */ public function getFiles() { return array(); } /** * {@inheritdoc} */ public function readAndWrite($blocking, $close = false) { $this->unblock(); $w = $this->write(); $read = $e = array(); $r = $this->pipes; unset($r[0]); // let's have a look if something changed in streams set_error_handler(array($this, 'handleError')); if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) { restore_error_handler(); // if a system call has been interrupted, forget about it, let's try again // otherwise, an error occurred, let's reset pipes if (!$this->hasSystemCallBeenInterrupted()) { $this->pipes = array(); } return $read; } restore_error_handler(); foreach ($r as $pipe) { // prior PHP 5.4 the array passed to stream_select is modified and // lose key association, we have to find back the key $read[$type = array_search($pipe, $this->pipes, true)] = ''; do { $data = fread($pipe, self::CHUNK_SIZE); $read[$type] .= $data; } while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1]))); if (!isset($read[$type][0])) { unset($read[$type]); } if ($close && feof($pipe)) { fclose($pipe); unset($this->pipes[$type]); } } return $read; } /** * {@inheritdoc} */ public function areOpen() { return (bool) $this->pipes; } /** * Creates a new UnixPipes instance. * * @param Process $process * @param string|resource $input * * @return static */ public static function create(Process $process, $input) { return new static($process->isTty(), $process->isPty(), $input, $process->isOutputDisabled()); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Pipes; /** * PipesInterface manages descriptors and pipes for the use of proc_open. * * @author Romain Neutron * * @internal */ interface PipesInterface { const CHUNK_SIZE = 16384; /** * Returns an array of descriptors for the use of proc_open. * * @return array */ public function getDescriptors(); /** * Returns an array of filenames indexed by their related stream in case these pipes use temporary files. * * @return string[] */ public function getFiles(); /** * Reads data in file handles and pipes. * * @param bool $blocking Whether to use blocking calls or not * @param bool $close Whether to close pipes if they've reached EOF * * @return string[] An array of read data indexed by their fd */ public function readAndWrite($blocking, $close = false); /** * Returns if the current state has open file handles or pipes. * * @return bool */ public function areOpen(); /** * Closes file handles and pipes. */ public function close(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; use Symfony\Component\Process\Exception\InvalidArgumentException; /** * ProcessUtils is a bunch of utility methods. * * This class contains static methods only and is not meant to be instantiated. * * @author Martin Hasoň */ class ProcessUtils { /** * This class should not be instantiated. */ private function __construct() { } /** * 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 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)."'"; } /** * Validates and normalizes a Process input. * * @param string $caller The name of method call that validates the input * @param mixed $input The input to validate * * @return mixed The validated input * * @throws InvalidArgumentException In case the input is not valid * * Passing an object as an input is deprecated since version 2.5 and will be removed in 3.0. */ public static function validateInput($caller, $input) { if (null !== $input) { if (\is_resource($input)) { return $input; } if (\is_string($input)) { return $input; } if (is_scalar($input)) { return (string) $input; } // deprecated as of Symfony 2.5, to be removed in 3.0 if (\is_object($input) && method_exists($input, '__toString')) { @trigger_error('Passing an object as an input is deprecated since Symfony 2.5 and will be removed in 3.0.', E_USER_DEPRECATED); return (string) $input; } throw new InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller)); } return $input; } private static function isSurroundedBy($arg, $char) { return 2 < \strlen($arg) && $char === $arg[0] && $char === $arg[\strlen($arg) - 1]; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; /** * LogicException for the Process Component. * * @author Romain Neutron */ class LogicException extends \LogicException implements ExceptionInterface { } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; use Symfony\Component\Process\Process; /** * Exception that is thrown when a process times out. * * @author Johannes M. Schmitt */ class ProcessTimedOutException extends RuntimeException { const TYPE_GENERAL = 1; const TYPE_IDLE = 2; private $process; private $timeoutType; public function __construct(Process $process, $timeoutType) { $this->process = $process; $this->timeoutType = $timeoutType; parent::__construct(sprintf( 'The process "%s" exceeded the timeout of %s seconds.', $process->getCommandLine(), $this->getExceededTimeout() )); } public function getProcess() { return $this->process; } public function isGeneralTimeout() { return self::TYPE_GENERAL === $this->timeoutType; } public function isIdleTimeout() { return self::TYPE_IDLE === $this->timeoutType; } public function getExceededTimeout() { switch ($this->timeoutType) { case self::TYPE_GENERAL: return $this->process->getTimeout(); case self::TYPE_IDLE: return $this->process->getIdleTimeout(); default: throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)); } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; /** * Marker Interface for the Process Component. * * @author Johannes M. Schmitt */ interface ExceptionInterface { } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; /** * InvalidArgumentException for the Process Component. * * @author Romain Neutron */ class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; use Symfony\Component\Process\Process; /** * Exception for failed processes. * * @author Johannes M. Schmitt */ class ProcessFailedException extends RuntimeException { private $process; public function __construct(Process $process) { if ($process->isSuccessful()) { throw new InvalidArgumentException('Expected a failed process, but the given process was successful.'); } $error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s", $process->getCommandLine(), $process->getExitCode(), $process->getExitCodeText(), $process->getWorkingDirectory() ); if (!$process->isOutputDisabled()) { $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", $process->getOutput(), $process->getErrorOutput() ); } parent::__construct($error); $this->process = $process; } public function getProcess() { return $this->process; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Exception; /** * RuntimeException for the Process Component. * * @author Johannes M. Schmitt */ class RuntimeException extends \RuntimeException implements ExceptionInterface { } function () { if ( ! is_multisite() ) { WP_CLI::error( 'This is not a multisite installation.' ); } }, ) ); fetcher = new UserFetcher(); } /** * Lists users with super admin capabilities. * * ## OPTIONS * * [--format=] * : Render output in a particular format. * --- * default: list * options: * - list * - table * - csv * - json * - count * - yaml * --- * * ## EXAMPLES * * # List user with super-admin capabilities * $ wp super-admin list * supervisor * administrator * * @subcommand list */ public function list_subcommand( $_, $assoc_args ) { $super_admins = self::get_admins(); if ( 'list' === $assoc_args['format'] ) { foreach ( $super_admins as $user_login ) { WP_CLI::line( $user_login ); } } else { $output_users = array(); foreach ( $super_admins as $user_login ) { $output_user = new stdClass(); $output_user->user_login = $user_login; $output_users[] = $output_user; } $formatter = new \WP_CLI\Formatter( $assoc_args, $this->fields ); $formatter->display_items( $output_users ); } } /** * Grants super admin privileges to one or more users. * * ## OPTIONS * * ... * : One or more user IDs, user emails, or user logins. * * ## EXAMPLES * * $ wp super-admin add superadmin2 * Success: Granted super-admin capabilities. */ public function add( $args, $_ ) { $successes = 0; $errors = 0; $users = $this->fetcher->get_many( $args ); if ( count( $users ) !== count( $args ) ) { $errors = count( $args ) - count( $users ); } $user_logins = wp_list_pluck( $users, 'user_login' ); $super_admins = self::get_admins(); $num_super_admins = count( $super_admins ); foreach ( $user_logins as $user_login ) { if ( in_array( $user_login, $super_admins, true ) ) { WP_CLI::warning( "User '{$user_login}' already has super-admin capabilities." ); continue; } $super_admins[] = $user_login; $successes++; } if ( count( $super_admins ) === $num_super_admins ) { if ( $errors ) { $user_count = count( $args ); WP_CLI::error( "Couldn't grant super-admin capabilities to {$errors} of {$user_count} users." ); } else { WP_CLI::success( 'Super admins remain unchanged.' ); } } else { if ( update_site_option( 'site_admins', $super_admins ) ) { if ( $errors ) { $user_count = count( $args ); WP_CLI::error( "Only granted super-admin capabilities to {$successes} of {$user_count} users." ); } else { $message = $successes > 1 ? 'users' : 'user'; WP_CLI::success( "Granted super-admin capabilities to {$successes} {$message}." ); } } else { WP_CLI::error( 'Site options update failed.' ); } } } /** * Removes super admin privileges from one or more users. * * ## OPTIONS * * ... * : One or more user IDs, user emails, or user logins. * * ## EXAMPLES * * $ wp super-admin remove superadmin2 * Success: Revoked super-admin capabilities. */ public function remove( $args, $_ ) { $super_admins = self::get_admins(); if ( ! $super_admins ) { WP_CLI::error( 'No super admins to revoke super-admin privileges from.' ); } $users = $this->fetcher->get_many( $args ); $user_logins = $users ? array_values( array_unique( wp_list_pluck( $users, 'user_login' ) ) ) : array(); $user_logins_count = count( $user_logins ); if ( $user_logins_count < count( $args ) ) { $flipped_user_logins = array_flip( $user_logins ); // Fetcher has already warned so don't bother here, but continue with any args that are possible login names to cater for invalid users in the site options meta. $user_logins = array_merge( $user_logins, array_unique( array_filter( $args, function ( $v ) use ( $flipped_user_logins ) { // Exclude numeric and email-like logins (login names can be email-like but ignore this given the circumstances). return ! isset( $flipped_user_logins[ $v ] ) && ! is_numeric( $v ) && ! is_email( $v ); } ) ) ); $user_logins_count = count( $user_logins ); } if ( ! $user_logins ) { WP_CLI::error( 'No valid user logins given to revoke super-admin privileges from.' ); } $update_super_admins = array_diff( $super_admins, $user_logins ); if ( $update_super_admins === $super_admins ) { WP_CLI::error( $user_logins_count > 1 ? 'None of the given users is a super admin.' : 'The given user is not a super admin.' ); } update_site_option( 'site_admins', $update_super_admins ); $successes = count( $super_admins ) - count( $update_super_admins ); if ( $successes === $user_logins_count ) { $message = $user_logins_count > 1 ? 'users' : 'user'; $msg = "Revoked super-admin capabilities from {$user_logins_count} {$message}."; } else { $msg = "Revoked super-admin capabilities from {$successes} of {$user_logins_count} users."; } if ( ! $update_super_admins ) { $msg .= ' There are no remaining super admins.'; } WP_CLI::success( $msg ); } private static function get_admins() { // We don't use get_super_admins() because we don't want to mess with the global return (array) get_site_option( 'site_admins', array( 'admin' ) ); } } array(), 'format' => 'WP_Export_WXR_Formatter', 'writer' => 'WP_Export_Returner', 'writer_args' => null, ); $args = wp_parse_args( $args, $defaults ); $export_query = new WP_Export_Query( $args['filters'] ); $formatter = new $args['format']( $export_query ); $writer = new $args['writer']( $formatter, $args['writer_args'] ); try { return $writer->export(); } catch ( WP_Export_Exception $e ) { return new WP_Error( 'wp-export-error', $e->getMessage() ); } } // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound,WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid -- Renaming breaks Phar compat. function _wp_export_build_IN_condition( $column_name, $values, $format = '%s' ) { global $wpdb; if ( ! is_array( $values ) || empty( $values ) ) { return ''; } $formats = implode( ', ', array_fill( 0, count( $values ), $format ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $column_name_sql escaped as ident, $formats hardcoded value. return $wpdb->prepare( "{$column_name} IN ({$formats})", $values ); } export = $export; $this->wxr_version = WXR_VERSION; } public function before_posts( $requested_sections = [] ) { $available_sections = [ 'header', 'site_metadata', 'authors', 'categories', 'tags', 'nav_menu_terms', 'custom_taxonomies_terms', 'rss2_head_action', ]; $before_posts_xml = ''; foreach ( $available_sections as $section ) { if ( ! $requested_sections || in_array( $section, $requested_sections, true ) ) { $before_posts_xml .= $this->$section(); } } return $before_posts_xml; } public function posts() { return new WP_Map_Iterator( $this->export->posts(), array( $this, 'post' ) ); } public function after_posts() { return $this->footer(); } public function header() { $oxymel = new Oxymel(); $charset = $this->export->charset(); $wp_generator_tag = $this->export->wp_generator_tag(); $comment = <<xml ->comment( $comment ) ->raw( $wp_generator_tag ) ->open_rss( array( 'version' => '2.0', 'xmlns:excerpt' => "http://wordpress.org/export/{$this->wxr_version}/excerpt/", 'xmlns:content' => 'http://purl.org/rss/1.0/modules/content/', 'xmlns:wfw' => 'http://wellformedweb.org/CommentAPI/', 'xmlns:dc' => 'http://purl.org/dc/elements/1.1/', 'xmlns:wp' => "http://wordpress.org/export/{$this->wxr_version}/", ) ) ->open_channel ->to_string(); } public function site_metadata() { $oxymel = new Oxymel(); $metadata = $this->export->site_metadata(); return $oxymel ->title( $metadata['name'] ) ->link( $metadata['url'] ) ->description( $metadata['description'] ) ->pubDate( $metadata['pubDate'] ) ->language( $metadata['language'] ) ->tag( 'wp:wxr_version', $this->wxr_version ) ->tag( 'wp:base_site_url', $metadata['site_url'] ) ->tag( 'wp:base_blog_url', $metadata['blog_url'] ) ->to_string(); } public function authors() { $oxymel = new Oxymel(); $authors = $this->export->authors(); foreach ( $authors as $author ) { $oxymel ->tag( 'wp:author' )->contains ->tag( 'wp:author_id', $author->ID ) ->tag( 'wp:author_login', $author->user_login ) ->tag( 'wp:author_email', $author->user_email ) ->tag( 'wp:author_display_name' )->contains->cdata( $author->display_name )->end ->tag( 'wp:author_first_name' )->contains->cdata( $author->user_firstname )->end ->tag( 'wp:author_last_name' )->contains->cdata( $author->user_lastname )->end ->end; } return $oxymel->to_string(); } public function categories() { $oxymel = new WP_Export_Oxymel(); $categories = $this->export->categories(); foreach ( $categories as $term_id => $category ) { $category->parent_slug = $category->parent ? $categories[ $category->parent ]->slug : ''; $oxymel->tag( 'wp:category' )->contains ->tag( 'wp:term_id', $category->term_id ) ->tag( 'wp:category_nicename', $category->slug ) ->tag( 'wp:category_parent', $category->parent_slug ) ->optional_cdata( 'wp:cat_name', $category->name ) ->optional_cdata( 'wp:category_description', $category->description ) ->end; } return $oxymel->to_string(); } public function tags() { $oxymel = new WP_Export_Oxymel(); $tags = $this->export->tags(); foreach ( $tags as $tag ) { $oxymel->tag( 'wp:tag' )->contains ->tag( 'wp:term_id', $tag->term_id ) ->tag( 'wp:tag_slug', $tag->slug ) ->optional_cdata( 'wp:tag_name', $tag->name ) ->optional_cdata( 'wp:tag_description', $tag->description ) ->end; } return $oxymel->to_string(); } public function nav_menu_terms() { return $this->terms( $this->export->nav_menu_terms() ); } public function custom_taxonomies_terms() { return $this->terms( $this->export->custom_taxonomies_terms() ); } public function rss2_head_action() { ob_start(); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress native hook. do_action( 'rss2_head' ); $action_output = ob_get_clean(); return $action_output; } public function post( $post ) { $oxymel = new WP_Export_Oxymel(); $GLOBALS['wp_query']->in_the_loop = true; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Intentional. $GLOBALS['post'] = $post; setup_postdata( $post ); $oxymel->item->contains ->title( apply_filters( 'the_title_rss', $post->post_title ) ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress native hook. ->link( esc_url( apply_filters( 'the_permalink_rss', get_permalink() ) ) ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress native hook. ->pubDate( mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ) ) ->tag( 'dc:creator', get_the_author_meta( 'login' ) ) ->guid( esc_url( get_the_guid() ), array( 'isPermaLink' => 'false' ) ) ->description( '' ) ->tag( 'content:encoded' )->contains->cdata( $post->post_content )->end ->tag( 'excerpt:encoded' )->contains->cdata( $post->post_excerpt )->end ->tag( 'wp:post_id', $post->ID ) ->tag( 'wp:post_date', $post->post_date ) ->tag( 'wp:post_date_gmt', $post->post_date_gmt ) ->tag( 'wp:comment_status', $post->comment_status ) ->tag( 'wp:ping_status', $post->ping_status ) ->tag( 'wp:post_name', $post->post_name ) ->tag( 'wp:status', $post->post_status ) ->tag( 'wp:post_parent', $post->post_parent ) ->tag( 'wp:menu_order', $post->menu_order ) ->tag( 'wp:post_type', $post->post_type ) ->tag( 'wp:post_password', $post->post_password ) ->tag( 'wp:is_sticky', $post->is_sticky ) ->optional( 'wp:attachment_url', wp_get_attachment_url( $post->ID ) ); foreach ( $post->terms as $term ) { $oxymel ->category( array( 'domain' => $term->taxonomy, 'nicename' => $term->slug, ) )->contains->cdata( $term->name )->end; } foreach ( $post->meta as $meta ) { $oxymel ->tag( 'wp:postmeta' )->contains ->tag( 'wp:meta_key', $meta->meta_key ) ->tag( 'wp:meta_value' )->contains->cdata( $meta->meta_value )->end ->end; } foreach ( $post->comments as $comment ) { $oxymel ->tag( 'wp:comment' )->contains ->tag( 'wp:comment_id', $comment->comment_ID ) ->tag( 'wp:comment_author' )->contains->cdata( $comment->comment_author )->end ->tag( 'wp:comment_author_email', $comment->comment_author_email ) ->tag( 'wp:comment_author_url', esc_url( $comment->comment_author_url ) ) ->tag( 'wp:comment_author_IP', $comment->comment_author_IP ) ->tag( 'wp:comment_date', $comment->comment_date ) ->tag( 'wp:comment_date_gmt', $comment->comment_date_gmt ) ->tag( 'wp:comment_content' )->contains->cdata( $comment->comment_content )->end ->tag( 'wp:comment_approved', $comment->comment_approved ) ->tag( 'wp:comment_type', $comment->comment_type ) ->tag( 'wp:comment_parent', $comment->comment_parent ) ->tag( 'wp:comment_user_id', $comment->user_id ) ->oxymel( $this->comment_meta( $comment ) ) ->end; } $oxymel ->end; return $oxymel->to_string(); } public function footer() { $oxymel = new Oxymel(); return $oxymel->close_channel->close_rss->to_string(); } protected function terms( $terms ) { $oxymel = new WP_Export_Oxymel(); foreach ( $terms as $term ) { $term->parent_slug = $term->parent ? $terms[ $term->parent ]->slug : ''; $oxymel->tag( 'wp:term' )->contains ->tag( 'wp:term_id', $term->term_id ) ->tag( 'wp:term_taxonomy', $term->taxonomy ) ->tag( 'wp:term_slug', $term->slug ); if ( 'nav_menu' !== $term->taxonomy ) { $oxymel ->tag( 'wp:term_parent', $term->parent_slug ); } $oxymel ->optional_cdata( 'wp:term_name', $term->name ) ->optional_cdata( 'wp:term_description', $term->description ) ->end; } return $oxymel->to_string(); } protected function comment_meta( $comment ) { global $wpdb; $metas = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) ); if ( ! $metas ) { return new Oxymel(); } $oxymel = new WP_Export_Oxymel(); foreach ( $metas as $meta ) { $oxymel->tag( 'wp:commentmeta' )->contains ->tag( 'wp:meta_key', $meta->meta_key ) ->tag( 'wp:meta_value' )->contains->cdata( $meta->meta_value )->end ->end; } return $oxymel; } } max_file_size = 15 * MB_IN_BYTES; } elseif ( WP_CLI_EXPORT_COMMAND_NO_SPLIT === (string) $writer_args['max_file_size'] ) { $this->max_file_size = WP_CLI_EXPORT_COMMAND_NO_SPLIT; } else { $this->max_file_size = $writer_args['max_file_size'] * MB_IN_BYTES; } $this->destination_directory = $writer_args['destination_directory']; $this->filename_template = $writer_args['filename_template']; $this->before_posts_xml = $this->formatter->before_posts(); $this->after_posts_xml = $this->formatter->after_posts(); } public function export() { $this->start_new_file(); foreach ( $this->formatter->posts() as $post_xml ) { if ( WP_CLI_EXPORT_COMMAND_NO_SPLIT !== $this->max_file_size && $this->current_file_size + strlen( $post_xml ) > $this->max_file_size ) { $this->start_new_file(); } $this->write( $post_xml ); } $this->close_current_file(); } protected function write( $xml ) { $res = fwrite( $this->f, $xml ); if ( false === $res ) { throw new WP_Export_Exception( __( 'WP Export: error writing to export file.' ) ); } $this->current_file_size += strlen( $xml ); } private function start_new_file() { if ( $this->f ) { $this->close_current_file(); } $file_path = $this->next_file_path(); $this->f = fopen( $file_path, 'w' ); if ( ! $this->f ) { throw new WP_Export_Exception( "WP Export: error opening {$file_path} for writing." ); } // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Possibly used by third party extension. do_action( 'wp_export_new_file', $file_path ); $this->current_file_size = 0; $this->write( $this->before_posts_xml ); } private function close_current_file() { if ( ! $this->f ) { return; } $this->write( $this->after_posts_xml ); fclose( $this->f ); } private function next_file_name() { $next_file_name = sprintf( $this->filename_template, $this->next_file_number ); $this->next_file_number++; return $next_file_name; } private function next_file_path() { return untrailingslashit( $this->destination_directory ) . DIRECTORY_SEPARATOR . $this->next_file_name(); } } ] * : Full path to directory where WXR export files should be stored. Defaults * to current working directory. * * [--stdout] * : Output the whole XML using standard output (incompatible with --dir=) * * [--skip_comments] * : Don't include comments in the WXR export file. * * [--max_file_size=] * : A single export file should have this many megabytes. -1 for unlimited. * --- * default: 15 * --- * * ## FILTERS * * [--start_date=] * : Export only posts published after this date, in format YYYY-MM-DD. * * [--end_date=] * : Export only posts published before this date, in format YYYY-MM-DD. * * [--post_type=] * : Export only posts with this post_type. Separate multiple post types with a * comma. * --- * default: any * --- * * [--post_type__not_in=] * : Export all post types except those identified. Separate multiple post types * with a comma. Defaults to none. * * [--post__in=] * : Export all posts specified as a comma- or space-separated list of IDs. * Post's attachments won't be exported unless --with_attachments is specified. * * [--with_attachments] * : Force including attachments in case --post__in has been specified. * * [--start_id=] * : Export only posts with IDs greater than or equal to this post ID. * * [--max_num_posts=] * : Export no more than posts (excluding attachments). * * [--author=] * : Export only posts by this author. Can be either user login or user ID. * * [--category=] * : Export only posts in this category. * * [--post_status=] * : Export only posts with this status. * * [--filename_format=] * : Use a custom format for export filenames. Defaults to '{site}.wordpress.{date}.{n}.xml'. * * ## EXAMPLES * * # Export posts published by the user between given start and end date * $ wp export --dir=/tmp/ --user=admin --post_type=post --start_date=2011-01-01 --end_date=2011-12-31 * Starting export process... * Writing to file /tmp/staging.wordpress.2016-05-24.000.xml * Success: All done with export. * * # Export posts by IDs * $ wp export --dir=/tmp/ --post__in=123,124,125 * Starting export process... * Writing to file /tmp/staging.wordpress.2016-05-24.000.xml * Success: All done with export. * * # Export a random subset of content * $ wp export --post__in="$(wp post list --post_type=post --orderby=rand --posts_per_page=8 --format=ids)" * Starting export process... * Writing to file /var/www/example.com/public_html/staging.wordpress.2016-05-24.000.xml * Success: All done with export. */ public function __invoke( $_, $assoc_args ) { $defaults = [ 'dir' => null, 'stdout' => false, 'start_date' => null, 'end_date' => null, 'post_type' => null, 'post_type__not_in' => null, 'max_num_posts' => null, 'author' => null, 'category' => null, 'post_status' => null, 'post__in' => null, 'with_attachments' => true, // or FALSE if user requested some post__in 'start_id' => null, 'skip_comments' => null, 'max_file_size' => 15, 'filename_format' => '{site}.wordpress.{date}.{n}.xml', ]; if ( ! empty( $assoc_args['stdout'] ) && ( ! empty( $assoc_args['dir'] ) || ! empty( $assoc_args['filename_format'] ) ) ) { WP_CLI::error( '--stdout and --dir cannot be used together.' ); } if ( ! empty( $assoc_args['post__in'] ) && empty( $assoc_args['with_attachments'] ) ) { $defaults['with_attachments'] = false; } $assoc_args = wp_parse_args( $assoc_args, $defaults ); $this->validate_args( $assoc_args ); $this->export_args['with_attachments'] = Utils\get_flag_value( $assoc_args, 'with_attachments', $defaults['with_attachments'] ); if ( ! function_exists( 'wp_export' ) ) { self::load_export_api(); } if ( ! $this->stdout ) { WP_CLI::log( 'Starting export process...' ); } add_action( 'wp_export_new_file', function( $file_path ) { WP_CLI::log( sprintf( 'Writing to file %s', $file_path ) ); Utils\wp_clear_object_cache(); } ); try { if ( $this->stdout ) { wp_export( [ 'filters' => $this->export_args, 'writer' => 'WP_Export_File_Writer', 'writer_args' => 'php://output', ] ); } else { wp_export( [ 'filters' => $this->export_args, 'writer' => 'WP_Export_Split_Files_Writer', 'writer_args' => [ 'max_file_size' => $this->max_file_size, 'destination_directory' => $this->wxr_path, 'filename_template' => self::get_filename_template( $assoc_args['filename_format'] ), ], ] ); } } catch ( Exception $e ) { WP_CLI::error( $e->getMessage() ); } if ( ! $this->stdout ) { WP_CLI::success( 'All done with export.' ); } } private static function get_filename_template( $filename_format ) { $sitename = sanitize_key( get_bloginfo( 'name' ) ); if ( empty( $sitename ) ) { $sitename = 'site'; } return str_replace( [ '{site}', '{date}', '{n}' ], [ $sitename, date( 'Y-m-d' ), '%03d' ], $filename_format ); } public static function load_export_api() { require dirname( dirname( __FILE__ ) ) . '/functions.php'; } private function validate_args( $args ) { $has_errors = false; foreach ( $args as $key => $value ) { if ( is_callable( [ $this, 'check_' . $key ] ) ) { $result = call_user_func( [ $this, 'check_' . $key ], $value ); if ( false === $result ) { $has_errors = true; } } } if ( $args['stdout'] ) { $this->wxr_path = null; $this->stdout = true; } if ( $has_errors ) { WP_CLI::halt( 1 ); } } private function check_dir( $path ) { if ( empty( $path ) ) { $path = getcwd(); } elseif ( ! is_dir( $path ) ) { WP_CLI::error( sprintf( "The directory '%s' does not exist.", $path ) ); } elseif ( ! is_writable( $path ) ) { WP_CLI::error( sprintf( "The directory '%s' is not writable.", $path ) ); } $this->wxr_path = trailingslashit( $path ); return true; } private function check_start_date( $date ) { if ( null === $date ) { return true; } $time = strtotime( $date ); if ( ! empty( $date ) && ! $time ) { WP_CLI::warning( sprintf( 'The start_date %s is invalid.', $date ) ); return false; } $this->export_args['start_date'] = date( 'Y-m-d', $time ); return true; } private function check_end_date( $date ) { if ( null === $date ) { return true; } $time = strtotime( $date ); if ( ! empty( $date ) && ! $time ) { WP_CLI::warning( sprintf( 'The end_date %s is invalid.', $date ) ); return false; } $this->export_args['end_date'] = date( 'Y-m-d', $time ); return true; } private function check_post_type( $post_type ) { if ( null === $post_type || 'any' === $post_type ) { return true; } $post_type = array_unique( array_filter( explode( ',', $post_type ) ) ); $post_types = get_post_types(); foreach ( $post_type as $type ) { if ( ! in_array( $type, $post_types, true ) ) { WP_CLI::warning( sprintf( 'The post type %s does not exist. Choose "any" or any of these existing post types instead: %s', $type, implode( ', ', $post_types ) ) ); return false; } } $this->export_args['post_type'] = $post_type; return true; } private function check_post_type__not_in( $post_type ) { if ( null === $post_type ) { return true; } $post_type = array_unique( array_filter( explode( ',', $post_type ) ) ); $post_types = get_post_types(); $keep_post_types = []; foreach ( $post_type as $type ) { if ( ! in_array( $type, $post_types, true ) ) { WP_CLI::warning( sprintf( 'The post type %s does not exist. Use any of these existing post types instead: %s', $type, implode( ', ', $post_types ) ) ); return false; } } $this->export_args['post_type'] = array_diff( $post_types, $post_type ); return true; } private function check_post__in( $post__in ) { if ( null === $post__in ) { return true; } $separator = false !== stripos( $post__in, ' ' ) ? ' ' : ','; $post__in = array_filter( array_unique( array_map( 'intval', explode( $separator, $post__in ) ) ) ); if ( empty( $post__in ) ) { WP_CLI::warning( 'post__in should be comma-separated post IDs.' ); return false; } // New exporter uses a different argument. $this->export_args['post_ids'] = $post__in; return true; } private function check_start_id( $start_id ) { if ( null === $start_id ) { return true; } $start_id = intval( $start_id ); // Post IDs must be greater than 0. if ( 0 >= $start_id ) { WP_CLI::warning( "Invalid start ID: {$start_id}" ); return false; } $this->export_args['start_id'] = $start_id; return true; } private function check_author( $author ) { if ( null === $author ) { return true; } // phpcs:ignore WordPress.WP.DeprecatedFunctions.get_users_of_blogFound -- Fallback. $authors = function_exists( 'get_users' ) ? get_users() : get_users_of_blog(); if ( empty( $authors ) || is_wp_error( $authors ) ) { WP_CLI::warning( sprintf( 'Could not find any authors in this blog.' ) ); return false; } $hit = false; foreach ( $authors as $user ) { if ( $hit ) { break; } if ( (int) $author === $user->ID || $author === $user->user_login ) { $hit = $user->ID; } } if ( false === $hit ) { $authors_nice = []; foreach ( $authors as $_author ) { $authors_nice[] = sprintf( '%s (%s)', $_author->user_login, $_author->display_name ); } WP_CLI::warning( sprintf( 'Could not find a matching author for %s. The following authors exist: %s', $author, implode( ', ', $authors_nice ) ) ); return false; } $this->export_args['author'] = $hit; return true; } private function check_max_num_posts( $num ) { if ( null !== $num && ( ! is_numeric( $num ) || $num <= 0 ) ) { WP_CLI::warning( sprintf( 'max_num_posts should be a positive integer.', $num ) ); return false; } $this->export_args['max_num_posts'] = (int) $num; return true; } private function check_category( $category ) { if ( null === $category ) { return true; } $term = category_exists( $category ); if ( empty( $term ) || is_wp_error( $term ) ) { WP_CLI::warning( sprintf( 'Could not find a category matching %s.', $category ) ); return false; } $this->export_args['category'] = $category; return true; } private function check_post_status( $status ) { if ( null === $status ) { return true; } $stati = get_post_statuses(); if ( empty( $stati ) || is_wp_error( $stati ) ) { WP_CLI::warning( 'Could not find any post stati.' ); return false; } if ( ! isset( $stati[ $status ] ) ) { WP_CLI::warning( sprintf( 'Could not find a post_status matching %s. Here is a list of available stati: %s', $status, implode( ', ', array_keys( $stati ) ) ) ); return false; } $this->export_args['status'] = $status; return true; } private function check_skip_comments( $skip ) { if ( null === $skip ) { return true; } if ( 0 !== (int) $skip && 1 !== (int) $skip ) { WP_CLI::warning( 'skip_comments needs to be 0 (no) or 1 (yes).' ); return false; } $this->export_args['skip_comments'] = $skip; return true; } private function check_max_file_size( $size ) { if ( ! is_numeric( $size ) ) { WP_CLI::warning( sprintf( 'max_file_size should be numeric.', $size ) ); return false; } $this->max_file_size = $size; return true; } } null, 'post_type' => null, 'status' => null, 'author' => null, 'start_date' => null, 'end_date' => null, 'start_id' => null, 'max_num_posts' => null, 'category' => null, ); private $post_ids; private $filters; private $xml_gen; private $wheres = array(); private $joins = array(); private $author; private $category; public $missing_parents = false; public function __construct( $filters = array() ) { $this->filters = wp_parse_args( $filters, self::$defaults ); $this->post_ids = $this->calculate_post_ids(); } public function post_ids() { return $this->post_ids; } public function charset() { return get_bloginfo( 'charset' ); } public function site_metadata() { $metadata = array( 'name' => $this->bloginfo_rss( 'name' ), 'url' => $this->bloginfo_rss( 'url' ), 'language' => $this->bloginfo_rss( 'language' ), 'description' => $this->bloginfo_rss( 'description' ), 'pubDate' => date( 'D, d M Y H:i:s +0000' ), 'site_url' => is_multisite() ? network_home_url() : $this->bloginfo_rss( 'url' ), 'blog_url' => $this->bloginfo_rss( 'url' ), ); return $metadata; } public function wp_generator_tag() { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. return apply_filters( 'the_generator', get_the_generator( 'export' ), 'export' ); } public function authors() { global $wpdb; $authors = array(); $author_ids = $wpdb->get_col( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft'" ); foreach ( (array) $author_ids as $author_id ) { $authors[] = get_userdata( $author_id ); } $authors = array_filter( $authors ); return $authors; } public function categories() { if ( $this->category ) { return array( $this->category ); } if ( $this->filters['post_type'] ) { return array(); } $categories = (array) get_categories( array( 'get' => 'all' ) ); $this->check_for_orphaned_terms( $categories ); $categories = self::topologically_sort_terms( $categories ); return $categories; } public function tags() { if ( $this->filters['post_type'] ) { return array(); } $tags = (array) get_tags( array( 'get' => 'all' ) ); $this->check_for_orphaned_terms( $tags ); return $tags; } public function custom_taxonomies_terms() { if ( $this->filters['post_type'] ) { return array(); } $custom_taxonomies = get_taxonomies( array( '_builtin' => false ) ); $custom_terms = (array) get_terms( $custom_taxonomies, array( 'get' => 'all' ) ); $this->check_for_orphaned_terms( $custom_terms ); $custom_terms = self::topologically_sort_terms( $custom_terms ); return $custom_terms; } public function nav_menu_terms() { $nav_menus = wp_get_nav_menus(); foreach ( $nav_menus as &$term ) { $term->description = ''; } return $nav_menus; } public function exportify_post( $post ) { $GLOBALS['wp_query']->in_the_loop = true; $previous_global_post = Utils\get_flag_value( $GLOBALS, 'post' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Temporary override. $GLOBALS['post'] = $post; setup_postdata( $post ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. $post->post_content = apply_filters( 'the_content_export', $post->post_content ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. $post->post_excerpt = apply_filters( 'the_excerpt_export', $post->post_excerpt ); $post->is_sticky = is_sticky( $post->ID ) ? 1 : 0; $post->terms = self::get_terms_for_post( $post ); $post->meta = self::get_meta_for_post( $post ); $post->comments = $this->get_comments_for_post( $post ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Revert back to original. $GLOBALS['post'] = $previous_global_post; return $post; } public function posts() { $posts_iterator = new WP_Post_IDs_Iterator( $this->post_ids, self::QUERY_CHUNK ); return new WP_Map_Iterator( $posts_iterator, array( $this, 'exportify_post' ) ); } private function calculate_post_ids() { global $wpdb; if ( is_array( $this->filters['post_ids'] ) ) { if ( $this->filters['with_attachments'] ) { $attachment_post_ids = $this->include_attachment_ids( $this->filters['post_ids'] ); $this->filters['post_ids'] = array_merge( $this->filters['post_ids'], $attachment_post_ids ); } return $this->filters['post_ids']; } $this->post_type_where(); $this->status_where(); $this->author_where(); $this->start_date_where(); $this->end_date_where(); $this->start_id_where(); $this->category_where(); $where = implode( ' AND ', array_filter( $this->wheres ) ); if ( $where ) { $where = "WHERE $where"; } $join = implode( ' ', array_filter( $this->joins ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Individual where clauses run through $wpdb->prepare(). $post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} AS p $join $where {$this->max_num_posts()}" ); if ( $this->filters['post_type'] ) { $post_ids = array_merge( $post_ids, $this->include_attachment_ids( $post_ids ) ); } return $post_ids; } private function post_type_where() { global $wpdb; $post_types_filters = array( 'can_export' => true ); if ( $this->filters['post_type'] ) { $post_types = $this->filters['post_type']; // Flatten single post types if ( is_array( $post_types ) && 1 === count( $post_types ) ) { $post_types = array_shift( $post_types ); } $post_types_filters = array_merge( $post_types_filters, array( 'name' => $post_types ) ); } // Multiple post types if ( isset( $post_types_filters['name'] ) && is_array( $post_types_filters['name'] ) ) { $post_types = array(); foreach ( $post_types_filters['name'] as $post_type ) { if ( post_type_exists( $post_type ) ) { $post_types[] = $post_type; } } } else { $post_types = get_post_types( $post_types_filters ); } if ( ! $post_types ) { $this->wheres[] = 'p.post_type IS NULL'; return; } if ( false === $this->filters['with_attachments'] && ( ! $this->filters['post_type'] || ! in_array( 'attachment', $this->filters['post_type'], true ) ) ) { unset( $post_types['attachment'] ); } $this->wheres[] = _wp_export_build_IN_condition( 'p.post_type', $post_types ); } private function status_where() { global $wpdb; if ( ! $this->filters['status'] ) { $this->wheres[] = "p.post_status != 'auto-draft'"; return; } $this->wheres[] = $wpdb->prepare( 'p.post_status = %s', $this->filters['status'] ); } private function author_where() { global $wpdb; $user = $this->find_user_from_any_object( $this->filters['author'] ); if ( ! $user || is_wp_error( $user ) ) { return; } $this->author = $user; $this->wheres[] = $wpdb->prepare( 'p.post_author = %d', $user->ID ); } private function start_date_where() { global $wpdb; $timestamp = strtotime( $this->filters['start_date'] ); if ( ! $timestamp ) { return; } $this->wheres[] = $wpdb->prepare( 'p.post_date >= %s', date( 'Y-m-d 00:00:00', $timestamp ) ); } private function end_date_where() { global $wpdb; if ( preg_match( '/^\d{4}-\d{2}$/', $this->filters['end_date'] ) ) { $timestamp = $this->get_timestamp_for_the_last_day_of_a_month( $this->filters['end_date'] ); } else { $timestamp = strtotime( $this->filters['end_date'] ); } if ( ! $timestamp ) { return; } $this->wheres[] = $wpdb->prepare( 'p.post_date <= %s', date( 'Y-m-d 23:59:59', $timestamp ) ); } private function start_id_where() { global $wpdb; $start_id = absint( $this->filters['start_id'] ); if ( 0 === $start_id ) { return; } $this->wheres[] = $wpdb->prepare( 'p.ID >= %d', $start_id ); } private function get_timestamp_for_the_last_day_of_a_month( $yyyy_mm ) { return strtotime( "$yyyy_mm +1month -1day" ); } private function category_where() { global $wpdb; if ( 'post' !== $this->filters['post_type'] && ! in_array( 'post', (array) $this->filters['post_type'], true ) ) { return; } $category = $this->find_category_from_any_object( $this->filters['category'] ); if ( ! $category ) { return; } $this->category = $category; $this->joins[] = "INNER JOIN {$wpdb->term_relationships} AS tr ON (p.ID = tr.object_id)"; $this->wheres[] = $wpdb->prepare( 'tr.term_taxonomy_id = %d', $category->term_taxonomy_id ); } private function max_num_posts() { if ( $this->filters['max_num_posts'] > 0 ) { return "LIMIT {$this->filters['max_num_posts']}"; } else { return ''; } } private function include_attachment_ids( $post_ids ) { global $wpdb; if ( ! $post_ids ) { return array(); } $attachment_ids = []; // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- Assigment is part of the break condition. while ( $batch_of_post_ids = array_splice( $post_ids, 0, self::QUERY_CHUNK ) ) { $post_parent_condition = _wp_export_build_IN_condition( 'post_parent', $batch_of_post_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped in wpcli_export_build_in_condition() function. $attachment_ids = array_merge( $attachment_ids, (array) $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND {$post_parent_condition}" ) ); } return array_map( 'intval', $attachment_ids ); } private function bloginfo_rss( $section ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. return apply_filters( 'bloginfo_rss', get_bloginfo_rss( $section ), $section ); } private function find_user_from_any_object( $user ) { if ( is_numeric( $user ) ) { return get_user_by( 'id', $user ); } elseif ( is_string( $user ) ) { return get_user_by( 'login', $user ); } elseif ( isset( $user->ID ) ) { return get_user_by( 'id', $user->ID ); } return false; } private function find_category_from_any_object( $category ) { if ( is_numeric( $category ) ) { return get_term( $category, 'category' ); } elseif ( is_string( $category ) ) { $term = term_exists( $category, 'category' ); return isset( $term['term_id'] ) ? get_term( $term['term_id'], 'category' ) : false; } elseif ( isset( $category->term_id ) ) { return get_term( $category->term_id, 'category' ); } return false; } private static function topologically_sort_terms( $terms ) { $sorted = []; // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- assignment is used as break condition. while ( $term = array_shift( $terms ) ) { if ( 0 === (int) $term->parent || isset( $sorted[ $term->parent ] ) ) { $sorted[ $term->term_id ] = $term; } else { $terms[] = $term; } } return $sorted; } private function check_for_orphaned_terms( $terms ) { $term_ids = array(); $have_parent = array(); foreach ( $terms as $term ) { $term_ids[ $term->term_id ] = true; if ( 0 !== (int) $term->parent ) { $have_parent[] = $term; } } foreach ( $have_parent as $has_parent ) { if ( ! isset( $term_ids[ $has_parent->parent ] ) ) { $this->missing_parents = $has_parent; throw new WP_Export_Term_Exception( "Term is missing a parent: {$has_parent->slug} ({$has_parent->term_taxonomy_id})" ); } } } private static function get_terms_for_post( $post ) { $taxonomies = get_object_taxonomies( $post->post_type ); if ( empty( $taxonomies ) ) { return array(); } $terms = wp_get_object_terms( $post->ID, $taxonomies ); $terms = $terms ? $terms : array(); return $terms; } private static function get_meta_for_post( $post ) { global $wpdb; $meta_for_export = array(); $meta_from_db = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) ); foreach ( $meta_from_db as $meta ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) { continue; } if ( in_array( $meta->meta_key, [ '_edit_lock', '_wp_attachment_metadata', '_wp_attached_file' ], true ) ) { continue; } $meta_for_export[] = $meta; } return $meta_for_export; } private function get_comments_for_post( $post ) { global $wpdb; if ( isset( $this->filters['skip_comments'] ) ) { return array(); } $comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) ); foreach ( $comments as $comment ) { $meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) ); $meta = $meta ? $meta : array(); $comment->meta = $meta; } return $comments; } } file_name = $file_name; } public function export() { $this->f = fopen( $this->file_name, 'w' ); if ( ! $this->f ) { throw new WP_Export_Exception( "WP Export: error opening {$this->file_name} for writing." ); } try { parent::export(); } catch ( WP_Export_Exception $e ) { throw $e; } catch ( WP_Export_Term_Exception $e ) { throw $e; } fclose( $this->f ); } protected function write( $xml ) { $res = fwrite( $this->f, $xml ); if ( false === $res ) { throw new WP_Export_Exception( __( 'WP Export: error writing to export file.' ) ); } } } private = ''; try { parent::export(); } catch ( WP_Export_Exception $e ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Possibly used by third party extension. $message = apply_filters( 'export_error_message', $e->getMessage() ); return new WP_Error( 'wp-export-error', $message ); } catch ( WP_Export_Term_Exception $e ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Possibly used by third party extensions. do_action( 'export_term_orphaned', $this->formatter->export->missing_parents ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Possibly used by third party extension. $message = apply_filters( 'export_term_error_message', $e->getMessage() ); return new WP_Error( 'wp-export-error', $message ); } return $this->result; } protected function write( $xml ) { $this->result .= $xml; } } db = $GLOBALS['wpdb']; $this->post_ids = $post_ids; $this->ids_left = $post_ids; if ( ! is_null( $limit ) ) { $this->limit = $limit; } } public function current() { return $this->results[ $this->index_in_results ]; } public function key() { return $this->global_index; } public function next() { $this->index_in_results++; $this->global_index++; } public function rewind() { $this->results = array(); $this->global_index = 0; $this->index_in_results = 0; $this->ids_left = $this->post_ids; } public function valid() { if ( isset( $this->results[ $this->index_in_results ] ) ) { return true; } if ( empty( $this->ids_left ) ) { return false; } $has_posts = $this->load_next_posts_from_db(); if ( ! $has_posts ) { return false; } $this->index_in_results = 0; return true; } private function load_next_posts_from_db() { $next_batch_post_ids = array_splice( $this->ids_left, 0, $this->limit ); $in_post_ids_sql = _wp_export_build_IN_condition( 'ID', $next_batch_post_ids ); $this->results = $this->db->get_results( "SELECT * FROM {$this->db->posts} WHERE $in_post_ids_sql" ); if ( ! $this->results ) { if ( $this->db->last_error ) { throw new WP_Iterator_Exception( 'Database error: ' . $this->db->last_error ); } else { return false; } } return true; } } callback = $callback; parent::__construct( $iterator ); } public function current() { $original_current = parent::current(); return call_user_func( $this->callback, $original_current ); } } file_name = $file_name; } public function export() { try { $export = $this->get_export(); $this->send_headers(); echo $export; } catch ( WP_Export_Exception $e ) { // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Possibly used by third party extension. $message = apply_filters( 'export_error_message', $e->getMessage() ); wp_die( $message, __( 'Export Error' ), array( 'back_link' => true ) ); } catch ( WP_Export_Term_Exception $e ) { do_action( 'export_term_orphaned', $this->formatter->export->missing_parents ); $message = apply_filters( 'export_term_error_message', $e->getMessage() ); // phpcs:enable wp_die( $message, __( 'Export Error' ), array( 'back_link' => true ) ); } } protected function write( $xml ) { $this->result .= $xml; } protected function get_export() { $this->result = ''; parent::export(); return $this->result; } protected function send_headers() { header( 'Content-Description: File Transfer' ); header( 'Content-Disposition: attachment; filename=' . $this->file_name ); header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true ); } } formatter = $formatter; } public function export() { $this->write( $this->formatter->before_posts() ); foreach ( $this->formatter->posts() as $post_in_wxr ) { $this->write( $post_in_wxr ); } $this->write( $this->formatter->after_posts() ); } abstract protected function write( $xml ); } $tag_name( $contents ); } return $this; } public function optional_cdata( $tag_name, $contents ) { if ( $contents ) { $this->$tag_name->contains->cdata( $contents )->end; } return $this; } public function cdata( $text ) { if ( ! seems_utf8( $text ) ) { $text = utf8_encode( $text ); } return parent::cdata( $text ); } } ] * : Prints the value of a single field for each update. * * [--fields=] * : Limit the output to specific object fields. Defaults to version,update_type,package_url. * * [--format=] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - count * - json * - yaml * --- * * ## EXAMPLES * * $ wp core check-update * +---------+-------------+-------------------------------------------------------------+ * | version | update_type | package_url | * +---------+-------------+-------------------------------------------------------------+ * | 4.5.2 | major | https://downloads.wordpress.org/release/wordpress-4.5.2.zip | * +---------+-------------+-------------------------------------------------------------+ * * @subcommand check-update */ public function check_update( $_, $assoc_args ) { $updates = $this->get_updates( $assoc_args ); if ( $updates ) { $updates = array_reverse( $updates ); $formatter = new Formatter( $assoc_args, [ 'version', 'update_type', 'package_url' ] ); $formatter->display_items( $updates ); } elseif ( empty( $assoc_args['format'] ) || 'table' === $assoc_args['format'] ) { WP_CLI::success( 'WordPress is at the latest version.' ); } } /** * Downloads core WordPress files. * * Downloads and extracts WordPress core files to the specified path. Uses * current directory when no path is specified. Downloaded build is verified * to have the correct md5 and then cached to the local filesytem. * Subsequent uses of command will use the local cache if it still exists. * * ## OPTIONS * * [] * : Download directly from a provided URL instead of fetching the URL from the wordpress.org servers. * * [--path=] * : Specify the path in which to install WordPress. Defaults to current * directory. * * [--locale=] * : Select which language you want to download. * * [--version=] * : Select which version you want to download. Accepts a version number, 'latest' or 'nightly'. * * [--skip-content] * : Download WP without the default themes and plugins. * * [--force] * : Overwrites existing files, if present. * * ## EXAMPLES * * $ wp core download --locale=nl_NL * Downloading WordPress 4.5.2 (nl_NL)... * md5 hash verified: c5366d05b521831dd0b29dfc386e56a5 * Success: WordPress downloaded. * * @when before_wp_load */ public function download( $args, $assoc_args ) { $download_dir = ! empty( $assoc_args['path'] ) ? ( rtrim( $assoc_args['path'], '/\\' ) . '/' ) : ABSPATH; $wordpress_present = is_readable( $download_dir . 'wp-load.php' ); if ( $wordpress_present && ! Utils\get_flag_value( $assoc_args, 'force' ) ) { WP_CLI::error( 'WordPress files seem to already be present here.' ); } if ( ! is_dir( $download_dir ) ) { if ( ! is_writable( dirname( $download_dir ) ) ) { WP_CLI::error( "Insufficient permission to create directory '{$download_dir}'." ); } WP_CLI::log( "Creating directory '{$download_dir}'." ); if ( ! @mkdir( $download_dir, 0777, true /*recursive*/ ) ) { $error = error_get_last(); WP_CLI::error( "Failed to create directory '{$download_dir}': {$error['message']}." ); } } if ( ! is_writable( $download_dir ) ) { WP_CLI::error( "'{$download_dir}' is not writable by current user." ); } $locale = Utils\get_flag_value( $assoc_args, 'locale', 'en_US' ); $skip_content = Utils\get_flag_value( $assoc_args, 'skip-content' ); $download_url = array_shift( $args ); $from_url = ! empty( $download_url ); if ( $from_url ) { $version = null; if ( isset( $assoc_args['version'] ) ) { WP_CLI::error( 'Version option is not available for URL downloads.' ); } if ( $skip_content || 'en_US' !== $locale ) { WP_CLI::error( 'Skip content and locale options are not available for URL downloads.' ); } } elseif ( isset( $assoc_args['version'] ) && 'latest' !== $assoc_args['version'] ) { $version = $assoc_args['version']; if ( in_array( strtolower( $version ), [ 'trunk', 'nightly' ], true ) ) { $version = 'nightly'; } // Nightly builds and skip content are only available in .zip format. $extension = ( ( 'nightly' === $version ) || $skip_content ) ? 'zip' : 'tar.gz'; $download_url = $this->get_download_url( $version, $locale, $extension ); } else { $offer = $this->get_download_offer( $locale ); if ( ! $offer ) { WP_CLI::error( "The requested locale ({$locale}) was not found." ); } $version = $offer->current; $download_url = $offer->download; if ( ! $skip_content ) { $download_url = str_replace( '.zip', '.tar.gz', $download_url ); } } if ( 'nightly' === $version && 'en_US' !== $locale ) { WP_CLI::error( 'Nightly builds are only available for the en_US locale.' ); } $from_version = ''; if ( file_exists( $download_dir . 'wp-includes/version.php' ) ) { $wp_details = self::get_wp_details( $download_dir ); $from_version = $wp_details['wp_version']; } if ( $from_url ) { WP_CLI::log( "Downloading from {$download_url} ..." ); } else { WP_CLI::log( "Downloading WordPress {$version} ({$locale})..." ); } $path_parts = pathinfo( $download_url ); $extension = 'tar.gz'; if ( 'zip' === $path_parts['extension'] ) { $extension = 'zip'; if ( ! class_exists( 'ZipArchive' ) ) { WP_CLI::error( 'Extracting a zip file requires ZipArchive.' ); } } if ( $skip_content && 'zip' !== $extension ) { WP_CLI::error( 'Skip content is only available for ZIP files.' ); } $cache = WP_CLI::get_cache(); if ( $from_url ) { $cache_file = null; } else { $cache_key = "core/wordpress-{$version}-{$locale}.{$extension}"; $cache_file = $cache->has( $cache_key ); } $bad_cache = false; if ( $cache_file ) { WP_CLI::log( "Using cached file '{$cache_file}'..." ); $skip_content_cache_file = $skip_content ? self::strip_content_dir( $cache_file ) : null; try { Extractor::extract( $skip_content_cache_file ?: $cache_file, $download_dir ); } catch ( Exception $exception ) { WP_CLI::warning( 'Extraction failed, downloading a new copy...' ); $bad_cache = true; } } if ( ! $cache_file || $bad_cache ) { // We need to use a temporary file because piping from cURL to tar is flaky // on MinGW (and probably in other environments too). $temp = Utils\get_temp_dir() . uniqid( 'wp_' ) . ".{$extension}"; register_shutdown_function( function () use ( $temp ) { if ( file_exists( $temp ) ) { unlink( $temp ); } } ); $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, // 10 minutes ought to be enough for everybody 'filename' => $temp, ]; $response = Utils\http_request( 'GET', $download_url, null, $headers, $options ); if ( 404 === (int) $response->status_code ) { WP_CLI::error( 'Release not found. Double-check locale or version.' ); } elseif ( 20 !== (int) substr( $response->status_code, 0, 2 ) ) { WP_CLI::error( "Couldn't access download URL (HTTP code {$response->status_code})." ); } if ( 'nightly' !== $version ) { $md5_response = Utils\http_request( 'GET', $download_url . '.md5' ); if ( $md5_response->status_code >= 200 && $md5_response->status_code < 300 ) { $md5_file = md5_file( $temp ); if ( $md5_file === $md5_response->body ) { WP_CLI::log( 'md5 hash verified: ' . $md5_file ); } else { WP_CLI::error( "md5 hash for download ({$md5_file}) is different than the release hash ({$md5_response->body})." ); } } else { WP_CLI::warning( "Couldn't access md5 hash for release ({$download_url}.md5, HTTP code {$md5_response->status_code})." ); } } else { WP_CLI::warning( 'md5 hash checks are not available for nightly downloads.' ); } $skip_content_temp = $skip_content ? self::strip_content_dir( $temp ) : null; try { Extractor::extract( $skip_content_temp ?: $temp, $download_dir ); } catch ( Exception $exception ) { WP_CLI::error( "Couldn't extract WordPress archive. {$exception->getMessage()}" ); } // Do not use the cache for nightly builds or for downloaded URLs // (the URL could be something like "latest.zip" or "nightly.zip"). if ( ! $from_url && 'nightly' !== $version ) { $cache->import( $cache_key, $temp ); } } if ( $wordpress_present ) { $this->cleanup_extra_files( $from_version, $version, $locale ); } WP_CLI::success( 'WordPress downloaded.' ); } private static function read( $url ) { $headers = [ 'Accept' => 'application/json' ]; $response = Utils\http_request( 'GET', $url, null, $headers, [ 'timeout' => 30 ] ); if ( 200 === $response->status_code ) { return $response->body; } else { WP_CLI::error( "Couldn't fetch response from {$url} (HTTP code {$response->status_code})." ); } } private function get_download_offer( $locale ) { $out = self::read( 'https://api.wordpress.org/core/version-check/1.7/?locale=' . $locale ); $out = function_exists( 'wp_json_decode' ) ? wp_json_decode( $out ) : json_decode( $out ); $offer = $out->offers[0]; if ( $offer->locale !== $locale ) { return false; } return $offer; } /** * Checks if WordPress is installed. * * Determines whether WordPress is installed by checking if the standard * database tables are installed. Doesn't produce output; uses exit codes * to communicate whether WordPress is installed. * * [--network] * : Check if this is a multisite installation. * * ## EXAMPLES * * # Check whether WordPress is installed; exit status 0 if installed, otherwise 1 * $ wp core is-installed * $ echo $? * 1 * * # Bash script for checking whether WordPress is installed or not * if ! $(wp core is-installed); then * wp core install * fi * * @subcommand is-installed */ public function is_installed( $args, $assoc_args ) { if ( is_blog_installed() && ( ! Utils\get_flag_value( $assoc_args, 'network' ) || is_multisite() ) ) { WP_CLI::halt( 0 ); } WP_CLI::halt( 1 ); } /** * Runs the standard WordPress installation process. * * Creates the WordPress tables in the database using the URL, title, and * default admin user details provided. Performs the famous 5 minute install * in seconds or less. * * Note: if you've installed WordPress in a subdirectory, then you'll need * to `wp option update siteurl` after `wp core install`. For instance, if * WordPress is installed in the `/wp` directory and your domain is example.com, * then you'll need to run `wp option update siteurl http://example.com/wp` for * your WordPress installation to function properly. * * Note: When using custom user tables (e.g. `CUSTOM_USER_TABLE`), the admin * email and password are ignored if the user_login already exists. If the * user_login doesn't exist, a new user will be created. * * ## OPTIONS * * --url= * : The address of the new site. * * --title= * : The title of the new site. * * --admin_user= * : The name of the admin user. * * [--admin_password=] * : The password for the admin user. Defaults to randomly generated string. * * --admin_email= * : The email address for the admin user. * * [--skip-email] * : Don't send an email notification to the new admin user. * * ## EXAMPLES * * # Install WordPress in 5 seconds * $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword --admin_email=info@example.com * Success: WordPress installed successfully. * * # Install WordPress without disclosing admin_password to bash history * $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_email=info@example.com --prompt=admin_password < admin_password.txt */ public function install( $args, $assoc_args ) { if ( $this->do_install( $assoc_args ) ) { WP_CLI::success( 'WordPress installed successfully.' ); } else { WP_CLI::log( 'WordPress is already installed.' ); } } /** * Transforms an existing single-site installation into a multisite installation. * * Creates the multisite database tables, and adds the multisite constants * to wp-config.php. * * For those using WordPress with Apache, remember to update the `.htaccess` * file with the appropriate multisite rewrite rules. * * [Review the multisite documentation](https://codex.wordpress.org/Create_A_Network) * for more details about how multisite works. * * ## OPTIONS * * [--title=] * : The title of the new network. * * [--base=] * : Base path after the domain name that each site url will start with. * --- * default: / * --- * * [--subdomains] * : If passed, the network will use subdomains, instead of subdirectories. Doesn't work with 'localhost'. * * ## EXAMPLES * * $ wp core multisite-convert * Set up multisite database tables. * Added multisite constants to wp-config.php. * Success: Network installed. Don't forget to set up rewrite rules. * * @subcommand multisite-convert * @alias install-network */ public function multisite_convert( $args, $assoc_args ) { if ( is_multisite() ) { WP_CLI::error( 'This already is a multisite installation.' ); } $assoc_args = self::set_multisite_defaults( $assoc_args ); if ( ! isset( $assoc_args['title'] ) ) { // translators: placeholder is blog name $assoc_args['title'] = sprintf( _x( '%s Sites', 'Default network name' ), get_option( 'blogname' ) ); } if ( $this->multisite_convert_( $assoc_args ) ) { WP_CLI::success( "Network installed. Don't forget to set up rewrite rules (and a .htaccess file, if using Apache)." ); } } /** * Installs WordPress multisite from scratch. * * Creates the WordPress tables in the database using the URL, title, and * default admin user details provided. Then, creates the multisite tables * in the database and adds multisite constants to the wp-config.php. * * For those using WordPress with Apache, remember to update the `.htaccess` * file with the appropriate multisite rewrite rules. * * ## OPTIONS * * [--url=] * : The address of the new site. * * [--base=] * : Base path after the domain name that each site url in the network will start with. * --- * default: / * --- * * [--subdomains] * : If passed, the network will use subdomains, instead of subdirectories. Doesn't work with 'localhost'. * * --title= * : The title of the new site. * * --admin_user= * : The name of the admin user. * --- * default: admin * --- * * [--admin_password=] * : The password for the admin user. Defaults to randomly generated string. * * --admin_email= * : The email address for the admin user. * * [--skip-email] * : Don't send an email notification to the new admin user. * * [--skip-config] * : Don't add multisite constants to wp-config.php. * * ## EXAMPLES * * $ wp core multisite-install --title="Welcome to the WordPress" \ * > --admin_user="admin" --admin_password="password" \ * > --admin_email="user@example.com" * Single site database tables already present. * Set up multisite database tables. * Added multisite constants to wp-config.php. * Success: Network installed. Don't forget to set up rewrite rules. * * @subcommand multisite-install */ public function multisite_install( $args, $assoc_args ) { if ( $this->do_install( $assoc_args ) ) { WP_CLI::log( 'Created single site database tables.' ); } else { WP_CLI::log( 'Single site database tables already present.' ); } $assoc_args = self::set_multisite_defaults( $assoc_args ); // translators: placeholder is user supplied title $assoc_args['title'] = sprintf( _x( '%s Sites', 'Default network name' ), $assoc_args['title'] ); // Overwrite runtime args, to avoid mismatches. $consts_to_args = [ 'SUBDOMAIN_INSTALL' => 'subdomains', 'PATH_CURRENT_SITE' => 'base', 'SITE_ID_CURRENT_SITE' => 'site_id', 'BLOG_ID_CURRENT_SITE' => 'blog_id', ]; foreach ( $consts_to_args as $const => $arg ) { if ( defined( $const ) ) { $assoc_args[ $arg ] = constant( $const ); } } if ( ! $this->multisite_convert_( $assoc_args ) ) { return; } // Do the steps that were skipped by populate_network(), // which checks is_multisite(). if ( is_multisite() ) { $site_user = get_user_by( 'email', $assoc_args['admin_email'] ); self::add_site_admins( $site_user ); $domain = self::get_clean_basedomain(); self::create_initial_blog( $assoc_args['site_id'], $assoc_args['blog_id'], $domain, $assoc_args['base'], $assoc_args['subdomains'], $site_user ); } WP_CLI::success( "Network installed. Don't forget to set up rewrite rules (and a .htaccess file, if using Apache)." ); } private static function set_multisite_defaults( $assoc_args ) { $defaults = [ 'subdomains' => false, 'base' => '/', 'site_id' => 1, 'blog_id' => 1, ]; return array_merge( $defaults, $assoc_args ); } private function do_install( $assoc_args ) { if ( is_blog_installed() ) { return false; } if ( true === Utils\get_flag_value( $assoc_args, 'skip-email' ) ) { if ( ! function_exists( 'wp_new_blog_notification' ) ) { function wp_new_blog_notification() { // Silence is golden } } // WP 4.9.0 - skip "Notice of Admin Email Change" email as well (https://core.trac.wordpress.org/ticket/39117). add_filter( 'send_site_admin_email_change_email', '__return_false' ); } require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $defaults = [ 'title' => '', 'admin_user' => '', 'admin_email' => '', 'admin_password' => '', ]; $args = wp_parse_args( $assoc_args, $defaults ); // Support prompting for the `--url=`, // which is normally a runtime argument if ( isset( $assoc_args['url'] ) ) { WP_CLI::set_url( $assoc_args['url'] ); } $public = true; $password = empty( $args['admin_password'] ) ? wp_generate_password( 18 ) : $args['admin_password']; if ( ! is_email( $args['admin_email'] ) ) { WP_CLI::error( "The '{$args['admin_email']}' email address is invalid." ); } $result = wp_install( $args['title'], $args['admin_user'], $args['admin_email'], $public, '', $password ); if ( is_wp_error( $result ) ) { $reason = WP_CLI::error_to_string( $result ); WP_CLI::error( "Installation failed ({$reason})." ); } if ( ! empty( $GLOBALS['wpdb']->last_error ) ) { WP_CLI::error( 'Installation produced database errors, and may have partially or completely failed.' ); } if ( empty( $args['admin_password'] ) ) { WP_CLI::log( "Admin password: {$result['password']}" ); } // Confirm the uploads directory exists $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) { WP_CLI::warning( $upload_dir['error'] ); } return true; } private function multisite_convert_( $assoc_args ) { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $domain = self::get_clean_basedomain(); if ( 'localhost' === $domain && ! empty( $assoc_args['subdomains'] ) ) { WP_CLI::error( "Multisite with subdomains cannot be configured when domain is 'localhost'." ); } // need to register the multisite tables manually for some reason foreach ( $wpdb->tables( 'ms_global' ) as $table => $prefixed_table ) { $wpdb->$table = $prefixed_table; } install_network(); $result = populate_network( $assoc_args['site_id'], $domain, get_option( 'admin_email' ), $assoc_args['title'], $assoc_args['base'], $assoc_args['subdomains'] ); $site_id = $wpdb->get_var( "SELECT id FROM $wpdb->site" ); $site_id = ( null === $site_id ) ? 1 : (int) $site_id; if ( true === $result ) { WP_CLI::log( 'Set up multisite database tables.' ); } elseif ( is_wp_error( $result ) ) { switch ( $result->get_error_code() ) { case 'siteid_exists': WP_CLI::log( $result->get_error_message() ); return false; case 'no_wildcard_dns': WP_CLI::warning( __( 'Wildcard DNS may not be configured correctly.' ) ); break; default: WP_CLI::error( $result ); } } // delete_site_option() cleans the alloptions cache to prevent dupe option delete_site_option( 'upload_space_check_disabled' ); update_site_option( 'upload_space_check_disabled', 1 ); if ( ! is_multisite() ) { $subdomain_export = Utils\get_flag_value( $assoc_args, 'subdomains' ) ? 'true' : 'false'; $ms_config = <<get_results( "SELECT meta_id, site_id FROM {$wpdb->sitemeta} WHERE meta_key = 'site_admins' AND meta_value = ''" ); foreach ( $rows as $row ) { wp_cache_delete( "{$row->site_id}:site_admins", 'site-options' ); $wpdb->delete( $wpdb->sitemeta, [ 'meta_id' => $row->meta_id ] ); } } return true; } // copied from populate_network() private static function create_initial_blog( $network_id, $blog_id, $domain, $path, $subdomain_install, $site_user ) { global $wpdb, $current_site, $wp_rewrite; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- This is meant to replace Core functionality. $current_site = new stdClass(); $current_site->domain = $domain; $current_site->path = $path; $current_site->site_name = ucfirst( $domain ); $blog_data = [ 'site_id' => $network_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time( 'mysql' ), ]; $wpdb->insert( $wpdb->blogs, $blog_data ); $current_site->blog_id = $wpdb->insert_id; $blog_id = $wpdb->insert_id; update_user_meta( $site_user->ID, 'source_domain', $domain ); update_user_meta( $site_user->ID, 'primary_blog', $blog_id ); if ( $subdomain_install ) { $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); } else { $wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' ); } flush_rewrite_rules(); } // copied from populate_network() private static function add_site_admins( $site_user ) { $site_admins = [ $site_user->user_login ]; $users = get_users( [ 'fields' => [ 'ID', 'user_login' ] ] ); if ( $users ) { foreach ( $users as $user ) { if ( is_super_admin( $user->ID ) && ! in_array( $user->user_login, $site_admins, true ) ) { $site_admins[] = $user->user_login; } } } update_site_option( 'site_admins', $site_admins ); } private static function modify_wp_config( $content ) { $wp_config_path = Utils\locate_wp_config(); $token = "/* That's all, stop editing!"; $config_contents = file_get_contents( $wp_config_path ); if ( false === strpos( $config_contents, $token ) ) { return false; } list( $before, $after ) = explode( $token, $config_contents ); $content = trim( $content ); file_put_contents( $wp_config_path, "{$before}\n\n{$content}\n\n{$token}{$after}" ); return true; } private static function get_clean_basedomain() { $domain = preg_replace( '|https?://|', '', get_option( 'siteurl' ) ); $slash = strpos( $domain, '/' ); if ( false !== $slash ) { $domain = substr( $domain, 0, $slash ); } return $domain; } /** * Displays the WordPress version. * * ## OPTIONS * * [--extra] * : Show extended version information. * * ## EXAMPLES * * # Display the WordPress version * $ wp core version * 4.5.2 * * # Display WordPress version along with other information * $ wp core version --extra * WordPress version: 4.5.2 * Database revision: 36686 * TinyMCE version: 4.310 (4310-20160418) * Package language: en_US * * @when before_wp_load */ public function version( $args = [], $assoc_args = [] ) { $details = self::get_wp_details(); if ( ! Utils\get_flag_value( $assoc_args, 'extra' ) ) { WP_CLI::line( $details['wp_version'] ); return; } $match = []; $found_version = preg_match( '/(\d)(\d+)-/', $details['tinymce_version'], $match ); $human_readable_tiny_mce = $found_version ? "{$match[1]}.{$match[2]}" : ''; echo Utils\mustache_render( self::get_template_path( 'versions.mustache' ), [ 'wp-version' => $details['wp_version'], 'db-version' => $details['wp_db_version'], 'local-package' => empty( $details['wp_local_package'] ) ? 'en_US' : $details['wp_local_package'], 'mce-version' => $human_readable_tiny_mce ? "{$human_readable_tiny_mce} ({$details['tinymce_version']})" : $details['tinymce_version'], ] ); } /** * Gets version information from `wp-includes/version.php`. * * @return array { * @type string $wp_version The WordPress version. * @type int $wp_db_version The WordPress DB revision. * @type string $tinymce_version The TinyMCE version. * @type string $wp_local_package The TinyMCE version. * } */ private static function get_wp_details( $abspath = ABSPATH ) { $versions_path = $abspath . 'wp-includes/version.php'; if ( ! is_readable( $versions_path ) ) { WP_CLI::error( "This does not seem to be a WordPress installation.\n" . 'Pass --path=`path/to/wordpress` or run `wp core download`.' ); } $version_content = file_get_contents( $versions_path, null, null, 6, 2048 ); $vars = [ 'wp_version', 'wp_db_version', 'tinymce_version', 'wp_local_package' ]; $result = []; foreach ( $vars as $var_name ) { $result[ $var_name ] = self::find_var( $var_name, $version_content ); } return $result; } /** * Gets the template path based on installation type. */ private static function get_template_path( $template ) { $command_root = Utils\phar_safe_path( dirname( __DIR__ ) ); $template_path = "{$command_root}/templates/{$template}"; if ( ! file_exists( $template_path ) ) { WP_CLI::error( "Couldn't find {$template}" ); } return $template_path; } /** * Searches for the value assigned to variable `$var_name` in PHP code `$code`. * * This is equivalent to matching the `\$VAR_NAME = ([^;]+)` regular expression and returning * the first match either as a `string` or as an `integer` (depending if it's surrounded by * quotes or not). * * @param string $var_name Variable name to search for. * @param string $code PHP code to search in. * * @return int|string|null */ private static function find_var( $var_name, $code ) { $start = strpos( $code, '$' . $var_name . ' = ' ); if ( ! $start ) { return null; } $start = $start + strlen( $var_name ) + 3; $end = strpos( $code, ';', $start ); $value = substr( $code, $start, $end - $start ); return trim( $value, " '" ); } /** * Security copy of the core function with Requests - Gets the checksums for the given version of WordPress. * * @param string $version Version string to query. * @param string $locale Locale to query. * @return string|array String message on failure. An array of checksums on success. */ private static function get_core_checksums( $version, $locale ) { $query = http_build_query( compact( 'version', 'locale' ), null, '&' ); $url = "https://api.wordpress.org/core/checksums/1.0/?{$query}"; $options = [ 'timeout' => 30 ]; $headers = [ 'Accept' => 'application/json' ]; $response = Utils\http_request( 'GET', $url, null, $headers, $options ); if ( ! $response->success || 200 !== (int) $response->status_code ) { return "Checksum request '{$url}' failed (HTTP {$response->status_code})."; } $body = trim( $response->body ); $body = json_decode( $body, true ); if ( ! is_array( $body ) || ! isset( $body['checksums'] ) || ! is_array( $body['checksums'] ) ) { return "Checksums not available for WordPress {$version}/{$locale}."; } return $body['checksums']; } /** * Updates WordPress to a newer version. * * Defaults to updating WordPress to the latest version. * * If you see "Error: Another update is currently in progress.", you may * need to run `wp option delete core_updater.lock` after verifying another * update isn't actually running. * * ## OPTIONS * * [] * : Path to zip file to use, instead of downloading from wordpress.org. * * [--minor] * : Only perform updates for minor releases (e.g. update from WP 4.3 to 4.3.3 instead of 4.4.2). * * [--version=] * : Update to a specific version, instead of to the latest version. Alternatively accepts 'nightly'. * * [--force] * : Update even when installed WP version is greater than the requested version. * * [--locale=] * : Select which language you want to download. * * ## EXAMPLES * * # Update WordPress * $ wp core update * Updating to version 4.5.2 (en_US)... * Downloading update from https://downloads.wordpress.org/release/wordpress-4.5.2-no-content.zip... * Unpacking the update... * Cleaning up files... * No files found that need cleaning up * Success: WordPress updated successfully. * * # Update WordPress to latest version of 3.8 release * $ wp core update --version=3.8 ../latest.zip * Updating to version 3.8 ()... * Unpacking the update... * Cleaning up files... * File removed: wp-admin/js/tags-box.js * ... * File removed: wp-admin/js/updates.min. * 377 files cleaned up * Success: WordPress updated successfully. * * # Update WordPress to 3.1 forcefully * $ wp core update --version=3.1 --force * Updating to version 3.1 (en_US)... * Downloading update from https://wordpress.org/wordpress-3.1.zip... * Unpacking the update... * Warning: Checksums not available for WordPress 3.1/en_US. Please cleanup files manually. * Success: WordPress updated successfully. * * @alias upgrade */ public function update( $args, $assoc_args ) { global $wp_version; $update = null; $from_api = null; $upgrader = 'WP_CLI\\Core\\CoreUpgrader'; if ( 'trunk' === Utils\get_flag_value( $assoc_args, 'version' ) ) { $assoc_args['version'] = 'nightly'; } if ( ! empty( $args[0] ) ) { // ZIP path or URL is given $upgrader = 'WP_CLI\\Core\\NonDestructiveCoreUpgrader'; $version = Utils\get_flag_value( $assoc_args, 'version' ); $update = (object) [ 'response' => 'upgrade', 'current' => $version, 'download' => $args[0], 'packages' => (object) [ 'partial' => null, 'new_bundled' => null, 'no_content' => null, 'full' => $args[0], ], 'version' => $version, 'locale' => null, ]; } elseif ( empty( $assoc_args['version'] ) ) { // Update to next release wp_version_check(); $from_api = get_site_transient( 'update_core' ); if ( Utils\get_flag_value( $assoc_args, 'minor' ) ) { foreach ( $from_api->updates as $offer ) { $sem_ver = Utils\get_named_sem_ver( $offer->version, $wp_version ); if ( ! $sem_ver || 'patch' !== $sem_ver ) { continue; } $update = $offer; break; } if ( empty( $update ) ) { WP_CLI::success( 'WordPress is at the latest minor release.' ); return; } } else { if ( ! empty( $from_api->updates ) ) { list( $update ) = $from_api->updates; } } } elseif ( \WP_CLI\Utils\wp_version_compare( $assoc_args['version'], '<' ) || 'nightly' === $assoc_args['version'] || Utils\get_flag_value( $assoc_args, 'force' ) ) { // Specific version is given $version = $assoc_args['version']; $locale = Utils\get_flag_value( $assoc_args, 'locale', get_locale() ); $new_package = $this->get_download_url( $version, $locale ); $update = (object) [ 'response' => 'upgrade', 'current' => $assoc_args['version'], 'download' => $new_package, 'packages' => (object) [ 'partial' => null, 'new_bundled' => null, 'no_content' => null, 'full' => $new_package, ], 'version' => $version, 'locale' => $locale, ]; } if ( ! empty( $update ) && ( $update->version !== $wp_version || Utils\get_flag_value( $assoc_args, 'force' ) ) ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; if ( $update->version ) { WP_CLI::log( "Updating to version {$update->version} ({$update->locale})..." ); } else { WP_CLI::log( 'Starting update...' ); } $from_version = $wp_version; $GLOBALS['wpcli_core_update_obj'] = $update; $result = Utils\get_upgrader( $upgrader )->upgrade( $update ); unset( $GLOBALS['wpcli_core_update_obj'] ); if ( is_wp_error( $result ) ) { $message = WP_CLI::error_to_string( $result ); if ( 'up_to_date' !== $result->get_error_code() ) { WP_CLI::error( $message ); } else { WP_CLI::success( $message ); } } else { $to_version = ''; if ( file_exists( ABSPATH . 'wp-includes/version.php' ) ) { $wp_details = self::get_wp_details(); $to_version = $wp_details['wp_version']; } $locale = Utils\get_flag_value( $assoc_args, 'locale', get_locale() ); $this->cleanup_extra_files( $from_version, $to_version, $locale ); WP_CLI::success( 'WordPress updated successfully.' ); } } else { WP_CLI::success( 'WordPress is up to date.' ); } } /** * Runs the WordPress database update procedure. * * [--network] * : Update databases for all sites on a network * * [--dry-run] * : Compare database versions without performing the update. * * ## EXAMPLES * * # Update the WordPress database * $ wp core update-db * Success: WordPress database upgraded successfully from db version 36686 to 35700. * * # Update databases for all sites on a network * $ wp core update-db --network * WordPress database upgraded successfully from db version 35700 to 29630 on example.com/ * Success: WordPress database upgraded on 123/123 sites * * @subcommand update-db */ public function update_db( $args, $assoc_args ) { global $wpdb, $wp_db_version, $wp_current_db_version; $network = Utils\get_flag_value( $assoc_args, 'network' ); if ( $network && ! is_multisite() ) { WP_CLI::error( 'This is not a multisite installation.' ); } $dry_run = Utils\get_flag_value( $assoc_args, 'dry-run' ); if ( $dry_run ) { WP_CLI::log( 'Performing a dry run, with no database modification.' ); } if ( $network ) { $iterator_args = [ 'table' => $wpdb->blogs, 'where' => [ 'spam' => 0, 'deleted' => 0, 'archived' => 0, ], ]; $it = new TableIterator( $iterator_args ); $success = 0; $total = 0; $site_ids = []; foreach ( $it as $blog ) { $total++; $site_ids[] = $blog->site_id; $url = $blog->domain . $blog->path; $cmd = "--url={$url} core update-db"; if ( $dry_run ) { $cmd .= ' --dry-run'; } $process = WP_CLI::runcommand( $cmd, [ 'return' => 'all' ] ); if ( 0 === (int) $process->return_code ) { // See if we can parse the stdout if ( preg_match( '#Success: (.+)#', $process->stdout, $matches ) ) { $message = rtrim( $matches[1], '.' ); $message = "{$message} on {$url}"; } else { $message = "Database upgraded successfully on {$url}"; } WP_CLI::log( $message ); $success++; } else { WP_CLI::warning( "Database failed to upgrade on {$url}" ); } } if ( ! $dry_run && $total && $success === $total ) { foreach ( array_unique( $site_ids ) as $site_id ) { update_metadata( 'site', $site_id, 'wpmu_upgrade_site', $wp_db_version ); } } WP_CLI::success( "WordPress database upgraded on {$success}/{$total} sites." ); } else { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Replacing WP Core behavior is the goal here. $wp_current_db_version = (int) __get_option( 'db_version' ); if ( $wp_db_version !== $wp_current_db_version ) { if ( $dry_run ) { WP_CLI::success( "WordPress database will be upgraded from db version {$wp_current_db_version} to {$wp_db_version}." ); } else { // WP upgrade isn't too fussy about generating MySQL warnings such as "Duplicate key name" during an upgrade so suppress. $wpdb->suppress_errors(); // WP upgrade expects `$_SERVER['HTTP_HOST']` to be set in `wp_guess_url()`, otherwise get PHP notice. if ( ! isset( $_SERVER['HTTP_HOST'] ) ) { $_SERVER['HTTP_HOST'] = 'http://example.com'; } wp_upgrade(); WP_CLI::success( "WordPress database upgraded successfully from db version {$wp_current_db_version} to {$wp_db_version}." ); } } else { WP_CLI::success( "WordPress database already at latest db version {$wp_db_version}." ); } } } /** * Gets download url based on version, locale and desired file type. * * @param $version * @param string $locale * @param string $file_type * @return string */ private function get_download_url( $version, $locale = 'en_US', $file_type = 'zip' ) { if ( 'nightly' === $version ) { if ( 'zip' === $file_type ) { return 'https://wordpress.org/nightly-builds/wordpress-latest.zip'; } else { WP_CLI::error( 'Nightly builds are only available in .zip format.' ); } } $locale_subdomain = 'en_US' === $locale ? '' : substr( $locale, 0, 2 ) . '.'; $locale_suffix = 'en_US' === $locale ? '' : "-{$locale}"; return "https://{$locale_subdomain}wordpress.org/wordpress-{$version}{$locale_suffix}.{$file_type}"; } /** * Returns update information. */ private function get_updates( $assoc_args ) { wp_version_check(); $from_api = get_site_transient( 'update_core' ); if ( ! $from_api ) { return []; } $compare_version = str_replace( '-src', '', $GLOBALS['wp_version'] ); $updates = [ 'major' => false, 'minor' => false, ]; foreach ( $from_api->updates as $offer ) { $update_type = Utils\get_named_sem_ver( $offer->version, $compare_version ); if ( ! $update_type ) { continue; } // WordPress follow its own versioning which is roughly equivalent to semver if ( 'minor' === $update_type ) { $update_type = 'major'; } elseif ( 'patch' === $update_type ) { $update_type = 'minor'; } if ( ! empty( $updates[ $update_type ] ) && ! Comparator::greaterThan( $offer->version, $updates[ $update_type ]['version'] ) ) { continue; } $updates[ $update_type ] = [ 'version' => $offer->version, 'update_type' => $update_type, 'package_url' => ! empty( $offer->packages->partial ) ? $offer->packages->partial : $offer->packages->full, ]; } foreach ( $updates as $type => $value ) { if ( empty( $value ) ) { unset( $updates[ $type ] ); } } foreach ( [ 'major', 'minor' ] as $type ) { if ( true === Utils\get_flag_value( $assoc_args, $type ) ) { return ! empty( $updates[ $type ] ) ? [ $updates[ $type ] ] : false; } } return array_values( $updates ); } private function cleanup_extra_files( $version_from, $version_to, $locale ) { if ( ! $version_from || ! $version_to ) { WP_CLI::warning( 'Failed to find WordPress version. Please cleanup files manually.' ); return; } $old_checksums = self::get_core_checksums( $version_from, $locale ?: 'en_US' ); if ( ! is_array( $old_checksums ) ) { WP_CLI::warning( "{$old_checksums} Please cleanup files manually." ); return; } $new_checksums = self::get_core_checksums( $version_to, $locale ?: 'en_US' ); if ( ! is_array( $new_checksums ) ) { WP_CLI::warning( "{$new_checksums} Please cleanup files manually." ); return; } $files_to_remove = array_diff( array_keys( $old_checksums ), array_keys( $new_checksums ) ); if ( ! empty( $files_to_remove ) ) { WP_CLI::log( 'Cleaning up files...' ); $count = 0; foreach ( $files_to_remove as $file ) { // wp-content should be considered user data if ( 0 === stripos( $file, 'wp-content' ) ) { continue; } if ( file_exists( ABSPATH . $file ) ) { unlink( ABSPATH . $file ); WP_CLI::log( "File removed: {$file}" ); $count++; } } if ( $count ) { WP_CLI::log( number_format( $count ) . ' files cleaned up.' ); } else { WP_CLI::log( 'No files found that need cleaning up.' ); } } } private static function strip_content_dir( $zip_file ) { $new_zip_file = Utils\get_temp_dir() . uniqid( 'wp_' ) . '.zip'; register_shutdown_function( function () use ( $new_zip_file ) { if ( file_exists( $new_zip_file ) ) { unlink( $new_zip_file ); } } ); // Duplicate file to avoid modifying the original, which could be cache. if ( ! copy( $zip_file, $new_zip_file ) ) { WP_CLI::error( 'Failed to copy ZIP file.' ); } $zip = new ZipArchive(); $res = $zip->open( $new_zip_file ); if ( true === $res ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase for ( $i = 0; $i < $zip->numFiles; $i++ ) { $info = $zip->statIndex( $i ); if ( false !== stripos( $info['name'], 'wp-content/' ) ) { $zip->deleteIndex( $i ); } } $zip->close(); return $new_zip_file; } else { WP_CLI::error( 'ZipArchive failed to open ZIP file.' ); } } } strings['no_package'] ); } $filename = pathinfo( $package, PATHINFO_FILENAME ); $extension = pathinfo( $package, PATHINFO_EXTENSION ); $temp = Utils\get_temp_dir() . uniqid( 'wp_' ) . ".{$extension}"; register_shutdown_function( function () use ( $temp ) { if ( file_exists( $temp ) ) { unlink( $temp ); } } ); $cache = WP_CLI::get_cache(); $update = $GLOBALS['wpcli_core_update_obj']; $cache_key = "core/{$filename}-{$update->locale}.{$extension}"; $cache_file = $cache->has( $cache_key ); if ( $cache_file && false === stripos( $package, 'https://wordpress.org/nightly-builds/' ) && false === stripos( $package, 'http://wordpress.org/nightly-builds/' ) ) { WP_CLI::log( "Using cached file '{$cache_file}'..." ); copy( $cache_file, $temp ); return $temp; } /* * Download to a temporary file because piping from cURL to tar is flaky * on MinGW (and probably in other environments too). */ $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, // 10 minutes ought to be enough for everybody. 'filename' => $temp, 'halt_on_error' => false, ]; $this->skin->feedback( 'downloading_package', $package ); /** @var Requests_Response|null $req */ try { $response = Utils\http_request( 'GET', $package, null, $headers, $options ); } catch ( Exception $e ) { return new WP_Error( 'download_failed', $e->getMessage() ); } if ( ! is_null( $response ) && 200 !== (int) $response->status_code ) { return new WP_Error( 'download_failed', $this->strings['download_failed'] ); } if ( false === stripos( $package, 'https://wordpress.org/nightly-builds/' ) ) { $cache->import( $cache_key, $temp ); } return $temp; } /** * Upgrade WordPress core. * * @access public * * @global WP_Filesystem_Base $wp_filesystem Subclass * @global callable $_wp_filesystem_direct_method * * @param object $current Response object for whether WordPress is current. * @param array $args { * Optional. Arguments for upgrading WordPress core. Default empty array. * * @type bool $pre_check_md5 Whether to check the file checksums before * attempting the upgrade. Default true. * @type bool $attempt_rollback Whether to attempt to rollback the chances if * there is a problem. Default false. * @type bool $do_rollback Whether to perform this "upgrade" as a rollback. * Default false. * } * @return null|false|WP_Error False or WP_Error on failure, null on success. */ public function upgrade( $current, $args = [] ) { set_error_handler( [ __CLASS__, 'error_handler' ], E_USER_WARNING | E_USER_NOTICE ); $result = parent::upgrade( $current, $args ); restore_error_handler(); return $result; } /** * Error handler to ignore failures on accessing SSL "https://api.wordpress.org/core/checksums/1.0/" in `get_core_checksums()` which seem to occur intermittently. */ public static function error_handler( $errno, $errstr, $errfile, $errline, $errcontext = null ) { // If ignoring E_USER_WARNING | E_USER_NOTICE, default. if ( ! ( error_reporting() & $errno ) ) { return false; } // If not in "wp-admin/includes/update.php", default. $update_php = 'wp-admin/includes/update.php'; if ( 0 !== substr_compare( $errfile, $update_php, -strlen( $update_php ) ) ) { return false; } // Else assume it's in `get_core_checksums()` and just ignore it. return true; } } get_bloginfo( 'name' ); * => string(6) "WP-CLI" */ public function __invoke( $_, $assoc_args ) { $implementations = array( 'Psy\\Shell', 'Boris\\Boris', 'WP_CLI\\Shell\\REPL', ); if ( Utils\get_flag_value( $assoc_args, 'basic' ) ) { $class = 'WP_CLI\\Shell\\REPL'; } else { foreach ( $implementations as $candidate ) { if ( class_exists( $candidate ) ) { $class = $candidate; break; } } } if ( 'Psy\\Shell' === $class ) { Psy\Shell::debug(); } else { $repl = new $class( 'wp> ' ); $repl->start(); } } } prompt = $prompt; $this->set_history_file(); } public function start() { while ( true ) { $line = $this->prompt(); if ( '' === $line ) { continue; } $line = rtrim( $line, ';' ) . ';'; if ( self::starts_with( self::non_expressions(), $line ) ) { ob_start(); // phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval. eval( $line ); $out = ob_get_clean(); if ( 0 < strlen( $out ) ) { $out = rtrim( $out, "\n" ) . "\n"; } fwrite( STDOUT, $out ); } else { if ( ! self::starts_with( 'return', $line ) ) { $line = 'return ' . $line; } // Write directly to STDOUT, to sidestep any output buffers created by plugins ob_start(); // phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval. $evl = eval( $line ); $out = ob_get_clean(); if ( 0 < strlen( $out ) ) { echo rtrim( $out, "\n" ) . "\n"; } echo '=> '; var_dump( $evl ); fwrite( STDOUT, ob_get_clean() ); } } } private static function non_expressions() { return implode( '|', array( 'echo', 'global', 'unset', 'function', 'while', 'for', 'foreach', 'if', 'switch', 'include', 'include\_once', 'require', 'require\_once', ) ); } private function prompt() { $full_line = false; $done = false; do { $prompt = ( ! $done && false !== $full_line ) ? '--> ' : $this->prompt; $fp = popen( self::create_prompt_cmd( $prompt, $this->history_file ), 'r' ); $line = fgets( $fp ); pclose( $fp ); if ( ! $line ) { break; } $line = rtrim( $line, "\n" ); if ( $line && '\\' === $line[ strlen( $line ) - 1 ] ) { $line = substr( $line, 0, -1 ); } else { $done = true; } $full_line .= $line; } while ( ! $done ); if ( false === $full_line ) { return 'exit'; } return $full_line; } private static function create_prompt_cmd( $prompt, $history_path ) { $prompt = escapeshellarg( $prompt ); $history_path = escapeshellarg( $history_path ); if ( getenv( 'WP_CLI_CUSTOM_SHELL' ) ) { $shell_binary = getenv( 'WP_CLI_CUSTOM_SHELL' ); } else { $shell_binary = '/bin/bash'; } if ( ! is_file( $shell_binary ) || ! is_readable( $shell_binary ) ) { WP_CLI::error( "The shell binary '{$shell_binary}' is not valid. You can override the shell to be used through the WP_CLI_CUSTOM_SHELL environment variable." ); } $shell_binary = escapeshellarg( $shell_binary ); $cmd = 'set -f; ' . "history -r {$history_path}; " . 'LINE=""; ' . "read -re -p {$prompt} LINE; " . '[ $? -eq 0 ] || exit; ' . 'history -s "$LINE"; ' . "history -w {$history_path}; " . 'echo $LINE; '; return "{$shell_binary} -c " . escapeshellarg( $cmd ); } private function set_history_file() { $data = getcwd() . get_current_user(); $this->history_file = \WP_CLI\Utils\get_temp_dir() . 'wp-cli-history-' . md5( $data ); } private static function starts_with( $tokens, $line ) { return preg_match( "/^($tokens)[\(\s]+/", $line ); } } ] * : Display the value of a single field * * [--fields=] * : Limit the output to specific fields. * * [--format=] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - json * --- * * [--force-regex] * : Turn the asterisk-type provider URLs into regexes. * * ## AVAILABLE FIELDS * * These fields will be displayed by default for each provider: * * * format * * endpoint * * This field is optionally available: * * * regex * * ## EXAMPLES * * # List format,endpoint fields of available providers. * $ wp embed provider list --fields=format,endpoint * +------------------------------+-----------------------------------------+ * | format | endpoint | * +------------------------------+-----------------------------------------+ * | #https?://youtu\.be/.*#i | https://www.youtube.com/oembed | * | #https?://flic\.kr/.*#i | https://www.flickr.com/services/oembed/ | * | #https?://wordpress\.tv/.*#i | https://wordpress.tv/oembed/ | * * @subcommand list */ public function list_providers( $args, $assoc_args ) { $oembed = new oEmbed(); $force_regex = Utils\get_flag_value( $assoc_args, 'force-regex' ); $providers = array(); foreach ( (array) $oembed->providers as $matchmask => $data ) { list( $providerurl, $regex ) = $data; // Turn the asterisk-type provider URLs into regex if ( $force_regex && ! $regex ) { $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i'; $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask ); } $providers[] = array( 'format' => $matchmask, 'endpoint' => $providerurl, 'regex' => $regex ? '1' : '0', ); } $formatter = $this->get_formatter( $assoc_args ); $formatter->display_items( $providers ); } /** * Gets the matching provider for a given URL. * * ## OPTIONS * * * : URL to retrieve provider for. * * [--discover] * : Whether to use oEmbed discovery or not. Defaults to true. * * [--limit-response-size=] * : Limit the size of the resulting HTML when using discovery. Default 150 KB (the standard WordPress limit). Not compatible with 'no-discover'. * * [--link-type=] * : Whether to accept only a certain link type when using discovery. Defaults to any (json or xml), preferring json. Not compatible with 'no-discover'. * --- * options: * - json * - xml * --- * * ## EXAMPLES * * # Get the matching provider for the URL. * $ wp embed provider match https://www.youtube.com/watch?v=dQw4w9WgXcQ * https://www.youtube.com/oembed * * @subcommand match */ public function match_provider( $args, $assoc_args ) { $oembed = new oEmbed(); $url = $args[0]; $discover = \WP_CLI\Utils\get_flag_value( $assoc_args, 'discover', true ); $response_size_limit = \WP_CLI\Utils\get_flag_value( $assoc_args, 'limit-response-size' ); $link_type = \WP_CLI\Utils\get_flag_value( $assoc_args, 'link-type' ); if ( ! $discover && ( null !== $response_size_limit || null !== $link_type ) ) { if ( null !== $response_size_limit && null !== $link_type ) { $msg = "The 'limit-response-size' and 'link-type' options can only be used with discovery."; } elseif ( null !== $response_size_limit ) { $msg = "The 'limit-response-size' option can only be used with discovery."; } else { $msg = "The 'link-type' option can only be used with discovery."; } WP_CLI::error( $msg ); } if ( $response_size_limit ) { if ( Utils\wp_version_compare( '4.0', '<' ) ) { WP_CLI::warning( "The 'limit-response-size' option only works for WordPress 4.0 onwards." ); // Fall through anyway... } add_filter( 'oembed_remote_get_args', function ( $args ) use ( $response_size_limit ) { $args['limit_response_size'] = $response_size_limit; return $args; } ); } if ( $link_type ) { // Filter discovery response. add_filter( 'oembed_linktypes', function ( $linktypes ) use ( $link_type ) { foreach ( $linktypes as $mime_type => $linktype_format ) { if ( $link_type !== $linktype_format ) { unset( $linktypes[ $mime_type ] ); } } return $linktypes; } ); } $oembed_args = array( 'discover' => $discover, ); $provider = $oembed->get_provider( $url, $oembed_args ); if ( ! $provider ) { if ( ! $discover ) { WP_CLI::error( 'No oEmbed provider found for given URL. Maybe try discovery?' ); } else { WP_CLI::error( 'No oEmbed provider found for given URL.' ); } } WP_CLI::line( $provider ); } /** * Get Formatter object based on supplied parameters. * * @param array $assoc_args Parameters passed to command. Determines formatting. * @return \WP_CLI\Formatter */ protected function get_formatter( &$assoc_args ) { return new Formatter( $assoc_args, $this->default_fields ); } } providers as $matchmask => $data ) { list( $providerurl, $regex ) = $data; // Turn the asterisk-type provider URLs into regex if ( ! $regex ) { $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i'; $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask ); } if ( preg_match( $matchmask, $url ) ) { $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML break; } } if ( ! $provider && $args['discover'] ) { $provider = $this->discover( $url ); } return $provider; } } * : ID of the post to clear the cache for. * * ## EXAMPLES * * # Clear cache for a post * $ wp embed cache clear 123 * Success: Cleared oEmbed cache. */ public function clear( $args, $assoc_args ) { /** @var \WP_Embed $wp_embed */ global $wp_embed; $post_id = $args[0]; $post_metas = get_post_custom_keys( $post_id ); if ( $post_metas ) { $post_metas = array_filter( $post_metas, function ( $v ) { return '_oembed_' === substr( $v, 0, 8 ); } ); } if ( empty( $post_metas ) ) { WP_CLI::error( 'No cache to clear!' ); } $wp_embed->delete_oembed_caches( $post_id ); WP_CLI::success( 'Cleared oEmbed cache.' ); } /** * Finds an oEmbed cache post ID for a given URL. * * Starting with WordPress 4.9, embeds that aren't associated with a specific post will be cached in * a new oembed_cache post type. There can be more than one such entry for a url depending on attributes and context. * * Not to be confused with oEmbed caches for a given post which are stored in the post's metadata. * * ## OPTIONS * * * : URL to retrieve oEmbed data for. * * [--width=] * : Width of the embed in pixels. Part of cache key so must match. Defaults to `content_width` if set else 500px, so is theme and context dependent. * * [--height=] * : Height of the embed in pixels. Part of cache key so must match. Defaults to 1.5 * default width (`content_width` or 500px), to a maximum of 1000px. * * [--discover] * : Whether to search with the discover attribute set or not. Part of cache key so must match. If not given, will search with attribute: unset, '1', '0', returning first. * * ## EXAMPLES * * # Find cache post ID for a given URL. * $ wp embed cache find https://www.youtube.com/watch?v=dQw4w9WgXcQ --width=500 * 123 */ public function find( $args, $assoc_args ) { if ( Utils\wp_version_compare( '4.9', '<' ) ) { WP_CLI::error( 'Requires WordPress 4.9 or greater.' ); } /** @var \WP_Embed $wp_embed */ global $wp_embed; $url = $args[0]; $width = Utils\get_flag_value( $assoc_args, 'width' ); $height = Utils\get_flag_value( $assoc_args, 'height' ); $discover = Utils\get_flag_value( $assoc_args, 'discover' ); // The `$key_suffix` used for caching is part based on serializing the attributes array without normalizing it first so need to try to replicate that. $oembed_args = array(); if ( null !== $width ) { $oembed_args['width'] = $width; // Keep as string as if from a shortcode attribute. } if ( null !== $height ) { $oembed_args['height'] = $height; // Keep as string as if from a shortcode attribute. } if ( null !== $discover ) { $discovers = array( ( $discover ) ? '1' : '0' ); } else { $discovers = array( null, '1', '0' ); } $attr = wp_parse_args( $oembed_args, wp_embed_defaults( $url ) ); foreach ( $discovers as $discover ) { if ( null !== $discover ) { $attr['discover'] = $discover; } // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- needed to mimic WP Core behavior. See: \WP_Embed::shortcode. $key_suffix = md5( $url . serialize( $attr ) ); $cached_post_id = $wp_embed->find_oembed_post_id( $key_suffix ); if ( $cached_post_id ) { WP_CLI::line( $cached_post_id ); return; } } WP_CLI::error( 'No cache post ID found!' ); } /** * Triggers the caching of all oEmbed results for a given post. * * oEmbed caches for a post are stored in the post's metadata. * * ## OPTIONS * * * : ID of the post to do the caching for. * * ## EXAMPLES * * # Triggers cache for a post * $ wp embed cache trigger 456 * Success: Caching triggered! */ public function trigger( $args, $assoc_args ) { /** @var \WP_Embed $wp_embed */ global $wp_embed; $post_id = $args[0]; $post = get_post( $post_id ); $post_types = get_post_types( array( 'show_ui' => true ) ); if ( empty( $post->ID ) ) { WP_CLI::warning( sprintf( "Post id '%s' not found.", $post_id ) ); return; } /** This filter is documented in wp-includes/class-wp-embed.php */ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using WP Core hook. if ( ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ), true ) ) { WP_CLI::warning( sprintf( "Cannot cache oEmbed results for '%s' post type", $post->post_type ) ); return; } $wp_embed->cache_oembed( $post_id ); WP_CLI::success( 'Caching triggered!' ); } } ] * : Display the value of a single field * * [--fields=] * : Limit the output to specific fields. * * [--format=] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - json * --- * * ## AVAILABLE FIELDS * * These fields will be displayed by default for each handler: * * * id * * regex * * These fields are optionally available: * * * callback * * priority * * ## EXAMPLES * * # List id,regex,priority fields of available handlers. * $ wp embed handler list --fields=priority,id * +----------+-------------------+ * | priority | id | * +----------+-------------------+ * | 10 | youtube_embed_url | * | 9999 | audio | * | 9999 | video | * * @subcommand list */ public function list_handlers( $args, $assoc_args ) { /** @var \WP_Embed $wp_embed */ global $wp_embed; $all_handlers = array(); ksort( $wp_embed->handlers ); foreach ( $wp_embed->handlers as $priority => $handlers ) { foreach ( $handlers as $id => $handler ) { $all_handlers[] = array( 'id' => $id, 'regex' => $handler['regex'], 'callback' => $handler['callback'], 'priority' => $priority, ); } } $formatter = $this->get_formatter( $assoc_args ); $formatter->display_items( $all_handlers ); } /** * Get Formatter object based on supplied parameters. * * @param array $assoc_args Parameters passed to command. Determines formatting. * @return \WP_CLI\Formatter */ protected function get_formatter( &$assoc_args ) { return new Formatter( $assoc_args, $this->default_fields ); } } * : URL to retrieve oEmbed data for. * * [--width=] * : Width of the embed in pixels. * * [--height=] * : Height of the embed in pixels. * * [--post-id=] * : Cache oEmbed response for a given post. * * [--discover] * : Enable oEmbed discovery. Defaults to true. * * [--skip-cache] * : Ignore already cached oEmbed responses. Has no effect if using the 'raw' option, which doesn't use the cache. * * [--skip-sanitization] * : Remove the filter that WordPress from 4.4 onwards uses to sanitize oEmbed responses. Has no effect if using the 'raw' option, which by-passes sanitization. * * [--do-shortcode] * : If the URL is handled by a registered embed handler and returns a shortcode, do shortcode and return result. Has no effect if using the 'raw' option, which by-passes handlers. * * [--limit-response-size=] * : Limit the size of the resulting HTML when using discovery. Default 150 KB (the standard WordPress limit). Not compatible with 'no-discover'. * * [--raw] * : Return the raw oEmbed response instead of the resulting HTML. Ignores the cache and does not sanitize responses or use registered embed handlers. * * [--raw-format=] * : Render raw oEmbed data in a particular format. Defaults to json. Can only be specified in conjunction with the 'raw' option. * --- * options: * - json * - xml * --- * * ## EXAMPLES * * # Get embed HTML for a given URL. * $ wp embed fetch https://www.youtube.com/watch?v=dQw4w9WgXcQ *
| *=> *)(.*?)(?: