ComposerRepository.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Repository;
  12. use Composer\Package\Loader\ArrayLoader;
  13. use Composer\Package\PackageInterface;
  14. use Composer\Package\AliasPackage;
  15. use Composer\Package\Version\VersionParser;
  16. use Composer\Json\JsonFile;
  17. use Composer\Cache;
  18. use Composer\Config;
  19. use Composer\Factory;
  20. use Composer\IO\IOInterface;
  21. use Composer\Util\HttpDownloader;
  22. use Composer\Plugin\PluginEvents;
  23. use Composer\Plugin\PreFileDownloadEvent;
  24. use Composer\EventDispatcher\EventDispatcher;
  25. use Composer\Downloader\TransportException;
  26. use Composer\Semver\Constraint\ConstraintInterface;
  27. use Composer\Semver\Constraint\Constraint;
  28. use Composer\Semver\Constraint\EmptyConstraint;
  29. /**
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class ComposerRepository extends ArrayRepository implements ConfigurableRepositoryInterface
  33. {
  34. protected $config;
  35. protected $repoConfig;
  36. protected $options;
  37. protected $url;
  38. protected $baseUrl;
  39. protected $io;
  40. protected $httpDownloader;
  41. protected $cache;
  42. protected $notifyUrl;
  43. protected $searchUrl;
  44. protected $hasProviders = false;
  45. protected $providersUrl;
  46. protected $lazyProvidersUrl;
  47. protected $providerListing;
  48. protected $providers = array();
  49. protected $providersByUid = array();
  50. protected $loader;
  51. protected $rootAliases;
  52. protected $allowSslDowngrade = false;
  53. protected $eventDispatcher;
  54. protected $sourceMirrors;
  55. protected $distMirrors;
  56. private $degradedMode = false;
  57. private $rootData;
  58. private $hasPartialPackages;
  59. private $partialPackagesByName;
  60. /**
  61. * TODO v3 should make this private once we can drop PHP 5.3 support
  62. * @private
  63. */
  64. public $versionParser;
  65. public function __construct(array $repoConfig, IOInterface $io, Config $config, HttpDownloader $httpDownloader, EventDispatcher $eventDispatcher = null)
  66. {
  67. parent::__construct();
  68. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  69. // assume http as the default protocol
  70. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  71. }
  72. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  73. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  74. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  75. }
  76. $urlBits = parse_url($repoConfig['url']);
  77. if ($urlBits === false || empty($urlBits['scheme'])) {
  78. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  79. }
  80. if (!isset($repoConfig['options'])) {
  81. $repoConfig['options'] = array();
  82. }
  83. if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
  84. $this->allowSslDowngrade = true;
  85. }
  86. $this->config = $config;
  87. $this->options = $repoConfig['options'];
  88. $this->url = $repoConfig['url'];
  89. // force url for packagist.org to repo.packagist.org
  90. if (preg_match('{^(?P<proto>https?)://packagist\.org/?$}i', $this->url, $match)) {
  91. $this->url = $match['proto'].'://repo.packagist.org';
  92. }
  93. $this->baseUrl = rtrim(preg_replace('{(?:/[^/\\\\]+\.json)?(?:[?#].*)?$}', '', $this->url), '/');
  94. $this->io = $io;
  95. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  96. $this->versionParser = new VersionParser();
  97. $this->loader = new ArrayLoader($this->versionParser);
  98. $this->httpDownloader = $httpDownloader;
  99. $this->eventDispatcher = $eventDispatcher;
  100. $this->repoConfig = $repoConfig;
  101. }
  102. public function getRepoConfig()
  103. {
  104. return $this->repoConfig;
  105. }
  106. public function setRootAliases(array $rootAliases)
  107. {
  108. $this->rootAliases = $rootAliases;
  109. }
  110. /**
  111. * {@inheritDoc}
  112. */
  113. public function findPackage($name, $constraint)
  114. {
  115. // this call initializes loadRootServerFile which is needed for the rest below to work
  116. $hasProviders = $this->hasProviders();
  117. $name = strtolower($name);
  118. if (!$constraint instanceof ConstraintInterface) {
  119. $constraint = $this->versionParser->parseConstraints($constraint);
  120. }
  121. // TODO we need a new way for the repo to report this v2 protocol somehow
  122. if ($this->lazyProvidersUrl) {
  123. return $this->loadAsyncPackages(array($name => $constraint), function ($name, $stability) {
  124. return true;
  125. });
  126. }
  127. if (!$hasProviders) {
  128. return parent::findPackage($name, $constraint);
  129. }
  130. foreach ($this->getProviderNames() as $providerName) {
  131. if ($name === $providerName) {
  132. $packages = $this->whatProvides($providerName);
  133. foreach ($packages as $package) {
  134. if ($name === $package->getName()) {
  135. $pkgConstraint = new Constraint('==', $package->getVersion());
  136. if ($constraint->matches($pkgConstraint)) {
  137. return $package;
  138. }
  139. }
  140. }
  141. break;
  142. }
  143. }
  144. }
  145. /**
  146. * {@inheritDoc}
  147. */
  148. public function findPackages($name, $constraint = null)
  149. {
  150. // this call initializes loadRootServerFile which is needed for the rest below to work
  151. $hasProviders = $this->hasProviders();
  152. // TODO we need a new way for the repo to report this v2 protocol somehow
  153. if ($this->lazyProvidersUrl) {
  154. return $this->loadAsyncPackages(array($name => $constraint ?: new EmptyConstraint()), function ($name, $stability) {
  155. return true;
  156. });
  157. }
  158. if (!$hasProviders) {
  159. return parent::findPackages($name, $constraint);
  160. }
  161. // normalize name
  162. $name = strtolower($name);
  163. if (null !== $constraint && !$constraint instanceof ConstraintInterface) {
  164. $constraint = $this->versionParser->parseConstraints($constraint);
  165. }
  166. $packages = array();
  167. foreach ($this->getProviderNames() as $providerName) {
  168. if ($name === $providerName) {
  169. $candidates = $this->whatProvides($providerName);
  170. foreach ($candidates as $package) {
  171. if ($name === $package->getName()) {
  172. $pkgConstraint = new Constraint('==', $package->getVersion());
  173. if (null === $constraint || $constraint->matches($pkgConstraint)) {
  174. $packages[] = $package;
  175. }
  176. }
  177. }
  178. break;
  179. }
  180. }
  181. return $packages;
  182. }
  183. public function getPackages()
  184. {
  185. if ($this->hasProviders()) {
  186. throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.');
  187. }
  188. return parent::getPackages();
  189. }
  190. public function loadPackages(array $packageNameMap, $isPackageAcceptableCallable)
  191. {
  192. // this call initializes loadRootServerFile which is needed for the rest below to work
  193. $hasProviders = $this->hasProviders();
  194. // TODO we need a new way for the repo to report this v2 protocol somehow
  195. if ($this->lazyProvidersUrl) {
  196. return $this->loadAsyncPackages($packageNameMap, $isPackageAcceptableCallable);
  197. }
  198. if (!$hasProviders) {
  199. return parent::loadPackages($packageNameMap, $isPackageAcceptableCallable);
  200. }
  201. $packages = array();
  202. foreach ($packageNameMap as $name => $constraint) {
  203. $matches = array();
  204. $candidates = $this->whatProvides($name, false, $isPackageAcceptableCallable);
  205. foreach ($candidates as $candidate) {
  206. if ($candidate->getName() === $name && (!$constraint || $constraint->matches(new Constraint('==', $candidate->getVersion())))) {
  207. $matches[spl_object_hash($candidate)] = $candidate;
  208. if ($candidate instanceof AliasPackage && !isset($matches[spl_object_hash($candidate->getAliasOf())])) {
  209. $matches[spl_object_hash($candidate->getAliasOf())] = $candidate->getAliasOf();
  210. }
  211. }
  212. }
  213. foreach ($candidates as $candidate) {
  214. if ($candidate instanceof AliasPackage) {
  215. if (isset($result[spl_object_hash($candidate->getAliasOf())])) {
  216. $matches[spl_object_hash($candidate)] = $candidate;
  217. }
  218. }
  219. }
  220. $packages = array_merge($packages, $matches);
  221. }
  222. return $packages;
  223. }
  224. /**
  225. * {@inheritDoc}
  226. */
  227. public function search($query, $mode = 0, $type = null)
  228. {
  229. $this->loadRootServerFile();
  230. if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
  231. $url = str_replace(array('%query%', '%type%'), array($query, $type), $this->searchUrl);
  232. $search = $this->httpDownloader->get($url, $this->options)->decodeJson();
  233. if (empty($search['results'])) {
  234. return array();
  235. }
  236. $results = array();
  237. foreach ($search['results'] as $result) {
  238. // do not show virtual packages in results as they are not directly useful from a composer perspective
  239. if (empty($result['virtual'])) {
  240. $results[] = $result;
  241. }
  242. }
  243. return $results;
  244. }
  245. if ($this->hasProviders()) {
  246. $results = array();
  247. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  248. foreach ($this->getProviderNames() as $name) {
  249. if (preg_match($regex, $name)) {
  250. $results[] = array('name' => $name);
  251. }
  252. }
  253. return $results;
  254. }
  255. return parent::search($query, $mode);
  256. }
  257. public function getProviderNames()
  258. {
  259. $this->loadRootServerFile();
  260. if (null === $this->providerListing) {
  261. $this->loadProviderListings($this->loadRootServerFile());
  262. }
  263. if ($this->lazyProvidersUrl) {
  264. // Can not determine list of provided packages for lazy repositories
  265. return array();
  266. }
  267. if ($this->providersUrl) {
  268. return array_keys($this->providerListing);
  269. }
  270. return array();
  271. }
  272. protected function configurePackageTransportOptions(PackageInterface $package)
  273. {
  274. foreach ($package->getDistUrls() as $url) {
  275. if (strpos($url, $this->baseUrl) === 0) {
  276. $package->setTransportOptions($this->options);
  277. return;
  278. }
  279. }
  280. }
  281. public function hasProviders()
  282. {
  283. $this->loadRootServerFile();
  284. return $this->hasProviders;
  285. }
  286. /**
  287. * @param string $name package name
  288. * @param bool $bypassFilters If set to true, this bypasses the stability filtering, and forces a recompute without cache
  289. * @param callable $isPackageAcceptableCallable
  290. * @return array|mixed
  291. */
  292. public function whatProvides($name, $bypassFilters = false, $isPackageAcceptableCallable = null)
  293. {
  294. if (isset($this->providers[$name]) && !$bypassFilters) {
  295. return $this->providers[$name];
  296. }
  297. if ($this->hasPartialPackages && null === $this->partialPackagesByName) {
  298. $this->initializePartialPackages();
  299. }
  300. if (!$this->hasPartialPackages || !isset($this->partialPackagesByName[$name])) {
  301. // skip platform packages, root package and composer-plugin-api
  302. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name || 'composer-plugin-api' === $name) {
  303. return array();
  304. }
  305. if (null === $this->providerListing) {
  306. $this->loadProviderListings($this->loadRootServerFile());
  307. }
  308. $useLastModifiedCheck = false;
  309. if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) {
  310. $hash = null;
  311. $url = str_replace('%package%', $name, $this->lazyProvidersUrl);
  312. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  313. $useLastModifiedCheck = true;
  314. } elseif ($this->providersUrl) {
  315. // package does not exist in this repo
  316. if (!isset($this->providerListing[$name])) {
  317. return array();
  318. }
  319. $hash = $this->providerListing[$name]['sha256'];
  320. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  321. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  322. } else {
  323. return array();
  324. }
  325. $packages = null;
  326. if ($cacheKey) {
  327. if (!$useLastModifiedCheck && $hash && $this->cache->sha256($cacheKey) === $hash) {
  328. $packages = json_decode($this->cache->read($cacheKey), true);
  329. } elseif ($useLastModifiedCheck) {
  330. if ($contents = $this->cache->read($cacheKey)) {
  331. $contents = json_decode($contents, true);
  332. if (isset($contents['last-modified'])) {
  333. $response = $this->fetchFileIfLastModified($url, $cacheKey, $contents['last-modified']);
  334. if (true === $response) {
  335. $packages = $contents;
  336. } elseif ($response) {
  337. $packages = $response;
  338. }
  339. }
  340. }
  341. }
  342. }
  343. if (!$packages) {
  344. try {
  345. $packages = $this->fetchFile($url, $cacheKey, $hash, $useLastModifiedCheck);
  346. } catch (TransportException $e) {
  347. // 404s are acceptable for lazy provider repos
  348. if ($e->getStatusCode() === 404 && $this->lazyProvidersUrl) {
  349. $packages = array('packages' => array());
  350. } else {
  351. throw $e;
  352. }
  353. }
  354. }
  355. $loadingPartialPackage = false;
  356. } else {
  357. $packages = array('packages' => array('versions' => $this->partialPackagesByName[$name]));
  358. $loadingPartialPackage = true;
  359. }
  360. $this->providers[$name] = array();
  361. foreach ($packages['packages'] as $versions) {
  362. $versionsToLoad = array();
  363. foreach ($versions as $version) {
  364. if (!$loadingPartialPackage && $this->hasPartialPackages && isset($this->partialPackagesByName[$version['name']])) {
  365. continue;
  366. }
  367. // avoid loading the same objects twice
  368. if (isset($this->providersByUid[$version['uid']])) {
  369. // skip if already assigned
  370. if (!isset($this->providers[$name][$version['uid']])) {
  371. // expand alias in two packages
  372. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  373. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  374. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  375. } else {
  376. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  377. }
  378. // check for root aliases
  379. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  380. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  381. }
  382. }
  383. } else {
  384. if (!$bypassFilters && $isPackageAcceptableCallable && !call_user_func($isPackageAcceptableCallable, strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  385. continue;
  386. }
  387. $versionsToLoad[] = $version;
  388. }
  389. }
  390. // load acceptable packages in the providers
  391. $loadedPackages = $this->createPackages($versionsToLoad, 'Composer\Package\CompletePackage');
  392. foreach ($loadedPackages as $package) {
  393. $package->setRepository($this);
  394. if ($package instanceof AliasPackage) {
  395. $aliased = $package->getAliasOf();
  396. $aliased->setRepository($this);
  397. $this->providers[$name][$version['uid']] = $aliased;
  398. $this->providers[$name][$version['uid'].'-alias'] = $package;
  399. // override provider with its alias so it can be expanded in the if block above
  400. $this->providersByUid[$version['uid']] = $package;
  401. } else {
  402. $this->providers[$name][$version['uid']] = $package;
  403. $this->providersByUid[$version['uid']] = $package;
  404. }
  405. // handle root package aliases
  406. unset($rootAliasData);
  407. if (isset($this->rootAliases[$package->getName()][$package->getVersion()])) {
  408. $rootAliasData = $this->rootAliases[$package->getName()][$package->getVersion()];
  409. } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()])) {
  410. $rootAliasData = $this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()];
  411. }
  412. if (isset($rootAliasData)) {
  413. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  414. $alias->setRepository($this);
  415. $this->providers[$name][$version['uid'].'-root'] = $alias;
  416. $this->providersByUid[$version['uid'].'-root'] = $alias;
  417. }
  418. }
  419. }
  420. $result = $this->providers[$name];
  421. // clean up the cache because otherwise using this puts the repo in an inconsistent state with a polluted unfiltered cache
  422. // which is likely not an issue but might cause hard to track behaviors depending on how the repo is used
  423. if ($bypassFilters) {
  424. foreach ($this->providers[$name] as $uid => $provider) {
  425. unset($this->providersByUid[$uid]);
  426. }
  427. unset($this->providers[$name]);
  428. }
  429. return $result;
  430. }
  431. /**
  432. * {@inheritDoc}
  433. */
  434. protected function initialize()
  435. {
  436. parent::initialize();
  437. $repoData = $this->loadDataFromServer();
  438. foreach ($this->createPackages($repoData, 'Composer\Package\CompletePackage') as $package) {
  439. $this->addPackage($package);
  440. }
  441. }
  442. /**
  443. * Adds a new package to the repository
  444. *
  445. * @param PackageInterface $package
  446. */
  447. public function addPackage(PackageInterface $package)
  448. {
  449. parent::addPackage($package);
  450. $this->configurePackageTransportOptions($package);
  451. }
  452. private function loadAsyncPackages(array $packageNames, $isPackageAcceptableCallable)
  453. {
  454. $this->loadRootServerFile();
  455. $packages = array();
  456. $repo = $this;
  457. // TODO what if not, then throw?
  458. if ($this->lazyProvidersUrl) {
  459. foreach ($packageNames as $name => $constraint) {
  460. $name = strtolower($name);
  461. // skip platform packages, root package and composer-plugin-api
  462. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name || 'composer-plugin-api' === $name) {
  463. continue;
  464. }
  465. $url = str_replace('%package%', $name, $this->lazyProvidersUrl);
  466. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  467. $lastModified = null;
  468. if ($contents = $this->cache->read($cacheKey)) {
  469. $contents = json_decode($contents, true);
  470. $lastModified = isset($contents['last-modified']) ? $contents['last-modified'] : null;
  471. }
  472. $this->asyncFetchFile($url, $cacheKey, $lastModified)
  473. ->then(function ($response) use (&$packages, $contents, $name, $constraint, $repo, $isPackageAcceptableCallable) {
  474. static $uniqKeys = array('version', 'version_normalized', 'source', 'dist', 'time');
  475. if (true === $response) {
  476. $response = $contents;
  477. }
  478. if (!isset($response['packages'][$name])) {
  479. return;
  480. }
  481. $versionsToLoad = array();
  482. foreach ($response['packages'][$name] as $version) {
  483. if (isset($version['version_normalizeds'])) {
  484. foreach ($version['version_normalizeds'] as $index => $normalizedVersion) {
  485. if (!$repo->isVersionAcceptable($isPackageAcceptableCallable, $constraint, $name, $normalizedVersion)) {
  486. foreach ($uniqKeys as $key) {
  487. unset($version[$key.'s'][$index]);
  488. }
  489. }
  490. }
  491. if (count($version['version_normalizeds'])) {
  492. $versionsToLoad[] = $version;
  493. }
  494. } else {
  495. if (!isset($version['version_normalized'])) {
  496. $version['version_normalized'] = $repo->versionParser->normalize($version['version']);
  497. }
  498. if ($repo->isVersionAcceptable($isPackageAcceptableCallable, $constraint, $name, $version['version_normalized'])) {
  499. $versionsToLoad[] = $version;
  500. }
  501. }
  502. }
  503. $loadedPackages = $this->createPackages($versionsToLoad, 'Composer\Package\CompletePackage');
  504. foreach ($loadedPackages as $package) {
  505. $package->setRepository($this);
  506. $packages[spl_object_hash($package)] = $package;
  507. if ($package instanceof AliasPackage && !isset($packages[spl_object_hash($package->getAliasOf())])) {
  508. $packages[spl_object_hash($package->getAliasOf())] = $package->getAliasOf();
  509. }
  510. }
  511. }, function ($e) {
  512. // TODO use ->done() above instead with react/promise 2.0
  513. var_dump('Uncaught Ex', $e->getMessage());
  514. throw $e;
  515. });
  516. }
  517. }
  518. $this->httpDownloader->wait();
  519. return $packages;
  520. // RepositorySet should call loadMetadata, getMetadata when all promises resolved, then metadataComplete when done so we can GC the loaded json and whatnot then as needed
  521. }
  522. /**
  523. * TODO v3 should make this private once we can drop PHP 5.3 support
  524. *
  525. * @private
  526. */
  527. public function isVersionAcceptable($isPackageAcceptableCallable, $constraint, $name, $versionNormalized)
  528. {
  529. if (!call_user_func($isPackageAcceptableCallable, strtolower($name), VersionParser::parseStability($versionNormalized))) {
  530. return false;
  531. }
  532. if ($constraint && !$constraint->matches(new Constraint('==', $versionNormalized))) {
  533. return false;
  534. }
  535. return true;
  536. }
  537. protected function loadRootServerFile()
  538. {
  539. if (null !== $this->rootData) {
  540. return $this->rootData;
  541. }
  542. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  543. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  544. }
  545. $jsonUrlParts = parse_url($this->url);
  546. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '.json')) {
  547. $jsonUrl = $this->url;
  548. } else {
  549. $jsonUrl = $this->url . '/packages.json';
  550. }
  551. $data = $this->fetchFile($jsonUrl, 'packages.json');
  552. if (!empty($data['notify-batch'])) {
  553. $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']);
  554. } elseif (!empty($data['notify'])) {
  555. $this->notifyUrl = $this->canonicalizeUrl($data['notify']);
  556. }
  557. if (!empty($data['search'])) {
  558. $this->searchUrl = $this->canonicalizeUrl($data['search']);
  559. }
  560. if (!empty($data['mirrors'])) {
  561. foreach ($data['mirrors'] as $mirror) {
  562. if (!empty($mirror['git-url'])) {
  563. $this->sourceMirrors['git'][] = array('url' => $mirror['git-url'], 'preferred' => !empty($mirror['preferred']));
  564. }
  565. if (!empty($mirror['hg-url'])) {
  566. $this->sourceMirrors['hg'][] = array('url' => $mirror['hg-url'], 'preferred' => !empty($mirror['preferred']));
  567. }
  568. if (!empty($mirror['dist-url'])) {
  569. $this->distMirrors[] = array(
  570. 'url' => $this->canonicalizeUrl($mirror['dist-url']),
  571. 'preferred' => !empty($mirror['preferred']),
  572. );
  573. }
  574. }
  575. }
  576. if (!empty($data['providers-lazy-url'])) {
  577. $this->lazyProvidersUrl = $this->canonicalizeUrl($data['providers-lazy-url']);
  578. $this->hasProviders = true;
  579. $this->hasPartialPackages = !empty($data['packages']) && is_array($data['packages']);
  580. }
  581. // metadata-url indiates V2 repo protocol so it takes over from all the V1 types
  582. // V2 only has lazyProviders and no ability to process anything else, plus support for async loading
  583. if (!empty($data['metadata-url'])) {
  584. $this->lazyProvidersUrl = $this->canonicalizeUrl($data['metadata-url']);
  585. $this->providersUrl = null;
  586. $this->hasProviders = false;
  587. $this->hasPartialPackages = false;
  588. $this->allowSslDowngrade = false;
  589. unset($data['providers-url'], $data['providers'], $data['providers-includes']);
  590. }
  591. if ($this->allowSslDowngrade) {
  592. $this->url = str_replace('https://', 'http://', $this->url);
  593. $this->baseUrl = str_replace('https://', 'http://', $this->baseUrl);
  594. }
  595. if (!empty($data['providers-url'])) {
  596. $this->providersUrl = $this->canonicalizeUrl($data['providers-url']);
  597. $this->hasProviders = true;
  598. }
  599. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  600. $this->hasProviders = true;
  601. }
  602. return $this->rootData = $data;
  603. }
  604. protected function canonicalizeUrl($url)
  605. {
  606. if ('/' === $url[0]) {
  607. return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url);
  608. }
  609. return $url;
  610. }
  611. protected function loadDataFromServer()
  612. {
  613. $data = $this->loadRootServerFile();
  614. return $this->loadIncludes($data);
  615. }
  616. protected function loadProviderListings($data)
  617. {
  618. if (isset($data['providers'])) {
  619. if (!is_array($this->providerListing)) {
  620. $this->providerListing = array();
  621. }
  622. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  623. }
  624. if ($this->providersUrl && isset($data['provider-includes'])) {
  625. $includes = $data['provider-includes'];
  626. foreach ($includes as $include => $metadata) {
  627. $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include);
  628. $cacheKey = str_replace(array('%hash%','$'), '', $include);
  629. if ($this->cache->sha256($cacheKey) === $metadata['sha256']) {
  630. $includedData = json_decode($this->cache->read($cacheKey), true);
  631. } else {
  632. $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']);
  633. }
  634. $this->loadProviderListings($includedData);
  635. }
  636. }
  637. }
  638. protected function loadIncludes($data)
  639. {
  640. $packages = array();
  641. // legacy repo handling
  642. if (!isset($data['packages']) && !isset($data['includes'])) {
  643. foreach ($data as $pkg) {
  644. foreach ($pkg['versions'] as $metadata) {
  645. $packages[] = $metadata;
  646. }
  647. }
  648. return $packages;
  649. }
  650. if (isset($data['packages'])) {
  651. foreach ($data['packages'] as $package => $versions) {
  652. foreach ($versions as $version => $metadata) {
  653. $packages[] = $metadata;
  654. }
  655. }
  656. }
  657. if (isset($data['includes'])) {
  658. foreach ($data['includes'] as $include => $metadata) {
  659. if ($this->cache->sha1($include) === $metadata['sha1']) {
  660. $includedData = json_decode($this->cache->read($include), true);
  661. } else {
  662. $includedData = $this->fetchFile($include);
  663. }
  664. $packages = array_merge($packages, $this->loadIncludes($includedData));
  665. }
  666. }
  667. return $packages;
  668. }
  669. /**
  670. * TODO v3 should make this private once we can drop PHP 5.3 support
  671. *
  672. * @private
  673. */
  674. public function createPackages(array $packages, $class = 'Composer\Package\CompletePackage')
  675. {
  676. if (!$packages) {
  677. return;
  678. }
  679. try {
  680. foreach ($packages as &$data) {
  681. if (!isset($data['notification-url'])) {
  682. $data['notification-url'] = $this->notifyUrl;
  683. }
  684. }
  685. $packages = $this->loader->loadPackages($packages, $class);
  686. foreach ($packages as $package) {
  687. if (isset($this->sourceMirrors[$package->getSourceType()])) {
  688. $package->setSourceMirrors($this->sourceMirrors[$package->getSourceType()]);
  689. }
  690. $package->setDistMirrors($this->distMirrors);
  691. $this->configurePackageTransportOptions($package);
  692. }
  693. return $packages;
  694. } catch (\Exception $e) {
  695. throw new \RuntimeException('Could not load packages '.(isset($packages[0]['name']) ? $packages[0]['name'] : json_encode($packages)).' in '.$this->url.': ['.get_class($e).'] '.$e->getMessage(), 0, $e);
  696. }
  697. }
  698. protected function fetchFile($filename, $cacheKey = null, $sha256 = null, $storeLastModifiedTime = false)
  699. {
  700. if (null === $cacheKey) {
  701. $cacheKey = $filename;
  702. $filename = $this->baseUrl.'/'.$filename;
  703. }
  704. // url-encode $ signs in URLs as bad proxies choke on them
  705. if (($pos = strpos($filename, '$')) && preg_match('{^https?://.*}i', $filename)) {
  706. $filename = substr($filename, 0, $pos) . '%24' . substr($filename, $pos + 1);
  707. }
  708. $retries = 3;
  709. while ($retries--) {
  710. try {
  711. $httpDownloader = $this->httpDownloader;
  712. if ($this->eventDispatcher) {
  713. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->httpDownloader, $filename);
  714. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  715. $httpDownloader = $preFileDownloadEvent->getHttpDownloader();
  716. }
  717. $response = $httpDownloader->get($filename, $this->options);
  718. $json = $response->getBody();
  719. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  720. // undo downgrade before trying again if http seems to be hijacked or modifying content somehow
  721. if ($this->allowSslDowngrade) {
  722. $this->url = str_replace('http://', 'https://', $this->url);
  723. $this->baseUrl = str_replace('http://', 'https://', $this->baseUrl);
  724. $filename = str_replace('http://', 'https://', $filename);
  725. }
  726. if ($retries) {
  727. usleep(100000);
  728. continue;
  729. }
  730. // TODO use scarier wording once we know for sure it doesn't do false positives anymore
  731. 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.');
  732. }
  733. $data = $response->decodeJson();
  734. if (!empty($data['warning'])) {
  735. $this->io->writeError('<warning>Warning from '.$this->url.': '.$data['warning'].'</warning>');
  736. }
  737. if (!empty($data['info'])) {
  738. $this->io->writeError('<info>Info from '.$this->url.': '.$data['info'].'</info>');
  739. }
  740. if ($cacheKey) {
  741. if ($storeLastModifiedTime) {
  742. $lastModifiedDate = $response->getHeader('last-modified');
  743. if ($lastModifiedDate) {
  744. $data['last-modified'] = $lastModifiedDate;
  745. $json = json_encode($data);
  746. }
  747. }
  748. $this->cache->write($cacheKey, $json);
  749. }
  750. $response->collect();
  751. break;
  752. } catch (\Exception $e) {
  753. if ($e instanceof \LogicException) {
  754. throw $e;
  755. }
  756. if ($e instanceof TransportException && $e->getStatusCode() === 404) {
  757. throw $e;
  758. }
  759. if ($retries) {
  760. usleep(100000);
  761. continue;
  762. }
  763. if ($e instanceof RepositorySecurityException) {
  764. throw $e;
  765. }
  766. if ($cacheKey && ($contents = $this->cache->read($cacheKey))) {
  767. if (!$this->degradedMode) {
  768. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  769. $this->io->writeError('<warning>'.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  770. }
  771. $this->degradedMode = true;
  772. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  773. break;
  774. }
  775. throw $e;
  776. }
  777. }
  778. return $data;
  779. }
  780. protected function fetchFileIfLastModified($filename, $cacheKey, $lastModifiedTime)
  781. {
  782. $retries = 3;
  783. while ($retries--) {
  784. try {
  785. $httpDownloader = $this->httpDownloader;
  786. if ($this->eventDispatcher) {
  787. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->httpDownloader, $filename);
  788. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  789. $httpDownloader = $preFileDownloadEvent->getHttpDownloader();
  790. }
  791. $options = $this->options;
  792. if (isset($options['http']['header'])) {
  793. $options['http']['header'] = (array) $options['http']['header'];
  794. }
  795. $options['http']['header'][] = array('If-Modified-Since: '.$lastModifiedTime);
  796. $response = $httpDownloader->get($filename, $options);
  797. $json = $response->getBody();
  798. if ($json === '' && $response->getStatusCode() === 304) {
  799. return true;
  800. }
  801. $data = $response->decodeJson();
  802. if (!empty($data['warning'])) {
  803. $this->io->writeError('<warning>Warning from '.$this->url.': '.$data['warning'].'</warning>');
  804. }
  805. if (!empty($data['info'])) {
  806. $this->io->writeError('<info>Info from '.$this->url.': '.$data['info'].'</info>');
  807. }
  808. $lastModifiedDate = $response->getHeader('last-modified');
  809. $response->collect();
  810. if ($lastModifiedDate) {
  811. $data['last-modified'] = $lastModifiedDate;
  812. $json = json_encode($data);
  813. }
  814. $this->cache->write($cacheKey, $json);
  815. return $data;
  816. } catch (\Exception $e) {
  817. if ($e instanceof \LogicException) {
  818. throw $e;
  819. }
  820. if ($e instanceof TransportException && $e->getStatusCode() === 404) {
  821. throw $e;
  822. }
  823. if ($retries) {
  824. usleep(100000);
  825. continue;
  826. }
  827. if (!$this->degradedMode) {
  828. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  829. $this->io->writeError('<warning>'.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  830. }
  831. $this->degradedMode = true;
  832. return true;
  833. }
  834. }
  835. }
  836. protected function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null)
  837. {
  838. $retries = 3;
  839. $httpDownloader = $this->httpDownloader;
  840. if ($this->eventDispatcher) {
  841. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->httpDownloader, $filename);
  842. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  843. $httpDownloader = $preFileDownloadEvent->getHttpDownloader();
  844. }
  845. $options = $lastModifiedTime ? array('http' => array('header' => array('If-Modified-Since: '.$lastModifiedTime))) : array();
  846. $io = $this->io;
  847. $url = $this->url;
  848. $cache = $this->cache;
  849. $degradedMode =& $this->degradedMode;
  850. $accept = function ($response) use ($io, $url, $cache, $cacheKey) {
  851. // package not found is acceptable for a v2 protocol repository
  852. if ($response->getStatusCode() === 404) {
  853. return array('packages' => array());
  854. }
  855. $json = $response->getBody();
  856. if ($json === '' && $response->getStatusCode() === 304) {
  857. return true;
  858. }
  859. $data = $response->decodeJson();
  860. if (!empty($data['warning'])) {
  861. $io->writeError('<warning>Warning from '.$url.': '.$data['warning'].'</warning>');
  862. }
  863. if (!empty($data['info'])) {
  864. $io->writeError('<info>Info from '.$url.': '.$data['info'].'</info>');
  865. }
  866. $lastModifiedDate = $response->getHeader('last-modified');
  867. $response->collect();
  868. if ($lastModifiedDate) {
  869. $data['last-modified'] = $lastModifiedDate;
  870. $json = JsonFile::encode($data, JsonFile::JSON_UNESCAPED_SLASHES | JsonFile::JSON_UNESCAPED_UNICODE);
  871. }
  872. $cache->write($cacheKey, $json);
  873. return $data;
  874. };
  875. $reject = function ($e) use (&$retries, $httpDownloader, $filename, $options, &$reject, $accept, $io, $url, $cache, &$degradedMode) {
  876. var_dump('Caught8', $e->getMessage());
  877. if ($e instanceof TransportException && $e->getStatusCode() === 404) {
  878. return false;
  879. }
  880. if (--$retries) {
  881. usleep(100000);
  882. return $httpDownloader->add($filename, $options)->then($accept, $reject);
  883. }
  884. if (!$degradedMode) {
  885. $io->writeError('<warning>'.$e->getMessage().'</warning>');
  886. $io->writeError('<warning>'.$url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  887. }
  888. $degradedMode = true;
  889. return true;
  890. };
  891. return $httpDownloader->add($filename, $options)->then($accept, $reject);
  892. }
  893. /**
  894. * This initializes the packages key of a partial packages.json that contain some packages inlined + a providers-lazy-url
  895. *
  896. * This should only be called once
  897. */
  898. private function initializePartialPackages()
  899. {
  900. $rootData = $this->loadRootServerFile();
  901. $this->partialPackagesByName = array();
  902. foreach ($rootData['packages'] as $package => $versions) {
  903. $package = strtolower($package);
  904. foreach ($versions as $version) {
  905. $this->partialPackagesByName[$package][] = $version;
  906. if (!empty($version['provide']) && is_array($version['provide'])) {
  907. foreach ($version['provide'] as $provided => $providedVersion) {
  908. $this->partialPackagesByName[strtolower($provided)][] = $version;
  909. }
  910. }
  911. if (!empty($version['replace']) && is_array($version['replace'])) {
  912. foreach ($version['replace'] as $provided => $providedVersion) {
  913. $this->partialPackagesByName[strtolower($provided)][] = $version;
  914. }
  915. }
  916. }
  917. }
  918. // wipe rootData as it is fully consumed at this point and this saves some memory
  919. $this->rootData = true;
  920. }
  921. }