ComposerRepository.php 43 KB

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