ComposerRepository.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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\DependencyResolver\Pool;
  17. use Composer\Json\JsonFile;
  18. use Composer\Cache;
  19. use Composer\Config;
  20. use Composer\Composer;
  21. use Composer\Factory;
  22. use Composer\IO\IOInterface;
  23. use Composer\Util\RemoteFilesystem;
  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. /**
  31. * @author Jordi Boggiano <j.boggiano@seld.be>
  32. */
  33. class ComposerRepository extends ArrayRepository implements ConfigurableRepositoryInterface
  34. {
  35. protected $config;
  36. protected $repoConfig;
  37. protected $options;
  38. protected $url;
  39. protected $baseUrl;
  40. protected $io;
  41. protected $rfs;
  42. protected $cache;
  43. protected $notifyUrl;
  44. protected $searchUrl;
  45. protected $hasProviders = false;
  46. protected $providersUrl;
  47. protected $lazyProvidersUrl;
  48. protected $providerListing;
  49. protected $providers = array();
  50. protected $providersByUid = array();
  51. protected $loader;
  52. protected $rootAliases;
  53. protected $allowSslDowngrade = false;
  54. protected $eventDispatcher;
  55. protected $sourceMirrors;
  56. protected $distMirrors;
  57. private $degradedMode = false;
  58. private $rootData;
  59. private $hasPartialPackages;
  60. private $partialPackagesByName;
  61. public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, RemoteFilesystem $rfs = null)
  62. {
  63. parent::__construct();
  64. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  65. // assume http as the default protocol
  66. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  67. }
  68. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  69. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  70. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  71. }
  72. $urlBits = parse_url($repoConfig['url']);
  73. if ($urlBits === false || empty($urlBits['scheme'])) {
  74. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  75. }
  76. if (!isset($repoConfig['options'])) {
  77. $repoConfig['options'] = array();
  78. }
  79. if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
  80. $this->allowSslDowngrade = true;
  81. }
  82. $this->config = $config;
  83. $this->options = $repoConfig['options'];
  84. $this->url = $repoConfig['url'];
  85. // force url for packagist.org to repo.packagist.org
  86. if (preg_match('{^(?P<proto>https?)://packagist\.org/?$}i', $this->url, $match)) {
  87. $this->url = $match['proto'].'://repo.packagist.org';
  88. }
  89. $this->baseUrl = rtrim(preg_replace('{(?:/[^/\\\\]+\.json)?(?:[?#].*)?$}', '', $this->url), '/');
  90. $this->io = $io;
  91. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  92. $this->loader = new ArrayLoader();
  93. if ($rfs && $this->options) {
  94. $rfs = clone $rfs;
  95. $rfs->setOptions($this->options);
  96. }
  97. $this->rfs = $rfs ?: Factory::createRemoteFilesystem($this->io, $this->config, $this->options);
  98. $this->eventDispatcher = $eventDispatcher;
  99. $this->repoConfig = $repoConfig;
  100. }
  101. public function getRepoConfig()
  102. {
  103. return $this->repoConfig;
  104. }
  105. public function setRootAliases(array $rootAliases)
  106. {
  107. $this->rootAliases = $rootAliases;
  108. }
  109. /**
  110. * {@inheritDoc}
  111. */
  112. public function findPackage($name, $constraint)
  113. {
  114. if (!$this->hasProviders()) {
  115. return parent::findPackage($name, $constraint);
  116. }
  117. $name = strtolower($name);
  118. if (!$constraint instanceof ConstraintInterface) {
  119. $versionParser = new VersionParser();
  120. $constraint = $versionParser->parseConstraints($constraint);
  121. }
  122. foreach ($this->getProviderNames() as $providerName) {
  123. if ($name === $providerName) {
  124. $packages = $this->whatProvides(new Pool('dev'), $providerName);
  125. foreach ($packages as $package) {
  126. if ($name === $package->getName()) {
  127. $pkgConstraint = new Constraint('==', $package->getVersion());
  128. if ($constraint->matches($pkgConstraint)) {
  129. return $package;
  130. }
  131. }
  132. }
  133. break;
  134. }
  135. }
  136. }
  137. /**
  138. * {@inheritDoc}
  139. */
  140. public function findPackages($name, $constraint = null)
  141. {
  142. if (!$this->hasProviders()) {
  143. return parent::findPackages($name, $constraint);
  144. }
  145. // normalize name
  146. $name = strtolower($name);
  147. if (null !== $constraint && !$constraint instanceof ConstraintInterface) {
  148. $versionParser = new VersionParser();
  149. $constraint = $versionParser->parseConstraints($constraint);
  150. }
  151. $packages = array();
  152. foreach ($this->getProviderNames() as $providerName) {
  153. if ($name === $providerName) {
  154. $candidates = $this->whatProvides(new Pool('dev'), $providerName);
  155. foreach ($candidates as $package) {
  156. if ($name === $package->getName()) {
  157. $pkgConstraint = new Constraint('==', $package->getVersion());
  158. if (null === $constraint || $constraint->matches($pkgConstraint)) {
  159. $packages[] = $package;
  160. }
  161. }
  162. }
  163. break;
  164. }
  165. }
  166. return $packages;
  167. }
  168. public function getPackages()
  169. {
  170. if ($this->hasProviders()) {
  171. throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.');
  172. }
  173. return parent::getPackages();
  174. }
  175. /**
  176. * {@inheritDoc}
  177. */
  178. public function search($query, $mode = 0, $type = null)
  179. {
  180. $this->loadRootServerFile();
  181. if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
  182. $url = str_replace(array('%query%', '%type%'), array($query, $type), $this->searchUrl);
  183. $hostname = parse_url($url, PHP_URL_HOST) ?: $url;
  184. $json = $this->rfs->getContents($hostname, $url, false);
  185. $search = JsonFile::parseJson($json, $url);
  186. if (empty($search['results'])) {
  187. return array();
  188. }
  189. $results = array();
  190. foreach ($search['results'] as $result) {
  191. // do not show virtual packages in results as they are not directly useful from a composer perspective
  192. if (empty($result['virtual'])) {
  193. $results[] = $result;
  194. }
  195. }
  196. return $results;
  197. }
  198. if ($this->hasProviders()) {
  199. $results = array();
  200. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  201. foreach ($this->getProviderNames() as $name) {
  202. if (preg_match($regex, $name)) {
  203. $results[] = array('name' => $name);
  204. }
  205. }
  206. return $results;
  207. }
  208. return parent::search($query, $mode);
  209. }
  210. public function getProviderNames()
  211. {
  212. $this->loadRootServerFile();
  213. if (null === $this->providerListing) {
  214. $this->loadProviderListings($this->loadRootServerFile());
  215. }
  216. if ($this->lazyProvidersUrl) {
  217. // Can not determine list of provided packages for lazy repositories
  218. return array();
  219. }
  220. if ($this->providersUrl) {
  221. return array_keys($this->providerListing);
  222. }
  223. return array();
  224. }
  225. protected function configurePackageTransportOptions(PackageInterface $package)
  226. {
  227. foreach ($package->getDistUrls() as $url) {
  228. if (strpos($url, $this->baseUrl) === 0) {
  229. $package->setTransportOptions($this->options);
  230. return;
  231. }
  232. }
  233. }
  234. public function hasProviders()
  235. {
  236. $this->loadRootServerFile();
  237. return $this->hasProviders;
  238. }
  239. public function resetPackageIds()
  240. {
  241. foreach ($this->providersByUid as $package) {
  242. if ($package instanceof AliasPackage) {
  243. $package->getAliasOf()->setId(-1);
  244. }
  245. $package->setId(-1);
  246. }
  247. }
  248. /**
  249. * @param Pool $pool
  250. * @param string $name package name
  251. * @param bool $bypassFilters If set to true, this bypasses the stability filtering, and forces a recompute without cache
  252. * @return array|mixed
  253. */
  254. public function whatProvides(Pool $pool, $name, $bypassFilters = false)
  255. {
  256. if (isset($this->providers[$name]) && !$bypassFilters) {
  257. return $this->providers[$name];
  258. }
  259. if ($this->hasPartialPackages && null === $this->partialPackagesByName) {
  260. $this->initializePartialPackages();
  261. }
  262. if (!$this->hasPartialPackages || !isset($this->partialPackagesByName[$name])) {
  263. // skip platform packages, root package and composer-plugin-api
  264. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name || 'composer-plugin-api' === $name) {
  265. return array();
  266. }
  267. if (null === $this->providerListing) {
  268. $this->loadProviderListings($this->loadRootServerFile());
  269. }
  270. $useLastModifiedCheck = false;
  271. if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) {
  272. $hash = null;
  273. $url = str_replace('%package%', $name, $this->lazyProvidersUrl);
  274. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  275. $useLastModifiedCheck = true;
  276. } elseif ($this->providersUrl) {
  277. // package does not exist in this repo
  278. if (!isset($this->providerListing[$name])) {
  279. return array();
  280. }
  281. $hash = $this->providerListing[$name]['sha256'];
  282. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  283. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  284. } else {
  285. return array();
  286. }
  287. $packages = null;
  288. if ($cacheKey) {
  289. if (!$useLastModifiedCheck && $hash && $this->cache->sha256($cacheKey) === $hash) {
  290. $packages = json_decode($this->cache->read($cacheKey), true);
  291. } elseif ($useLastModifiedCheck) {
  292. if ($contents = $this->cache->read($cacheKey)) {
  293. $contents = json_decode($contents, true);
  294. if (isset($contents['last-modified'])) {
  295. $response = $this->fetchFileIfLastModified($url, $cacheKey, $contents['last-modified']);
  296. if (true === $response) {
  297. $packages = $contents;
  298. } elseif ($response) {
  299. $packages = $response;
  300. }
  301. }
  302. }
  303. }
  304. }
  305. if (!$packages) {
  306. try {
  307. $packages = $this->fetchFile($url, $cacheKey, $hash, $useLastModifiedCheck);
  308. } catch (TransportException $e) {
  309. // 404s are acceptable for lazy provider repos
  310. if ($e->getStatusCode() === 404 && $this->lazyProvidersUrl) {
  311. $packages = array('packages' => array());
  312. } else {
  313. throw $e;
  314. }
  315. }
  316. }
  317. $loadingPartialPackage = false;
  318. } else {
  319. $packages = array('packages' => array('versions' => $this->partialPackagesByName[$name]));
  320. $loadingPartialPackage = true;
  321. }
  322. $this->providers[$name] = array();
  323. foreach ($packages['packages'] as $versions) {
  324. foreach ($versions as $version) {
  325. if (!$loadingPartialPackage && $this->hasPartialPackages && isset($this->partialPackagesByName[$version['name']])) {
  326. continue;
  327. }
  328. // avoid loading the same objects twice
  329. if (isset($this->providersByUid[$version['uid']])) {
  330. // skip if already assigned
  331. if (!isset($this->providers[$name][$version['uid']])) {
  332. // expand alias in two packages
  333. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  334. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  335. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  336. } else {
  337. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  338. }
  339. // check for root aliases
  340. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  341. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  342. }
  343. }
  344. } else {
  345. if (!$bypassFilters && !$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  346. continue;
  347. }
  348. // load acceptable packages in the providers
  349. $package = $this->createPackage($version, 'Composer\Package\CompletePackage');
  350. $package->setRepository($this);
  351. if ($package instanceof AliasPackage) {
  352. $aliased = $package->getAliasOf();
  353. $aliased->setRepository($this);
  354. $this->providers[$name][$version['uid']] = $aliased;
  355. $this->providers[$name][$version['uid'].'-alias'] = $package;
  356. // override provider with its alias so it can be expanded in the if block above
  357. $this->providersByUid[$version['uid']] = $package;
  358. } else {
  359. $this->providers[$name][$version['uid']] = $package;
  360. $this->providersByUid[$version['uid']] = $package;
  361. }
  362. // handle root package aliases
  363. unset($rootAliasData);
  364. if (isset($this->rootAliases[$package->getName()][$package->getVersion()])) {
  365. $rootAliasData = $this->rootAliases[$package->getName()][$package->getVersion()];
  366. } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()])) {
  367. $rootAliasData = $this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()];
  368. }
  369. if (isset($rootAliasData)) {
  370. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  371. $alias->setRepository($this);
  372. $this->providers[$name][$version['uid'].'-root'] = $alias;
  373. $this->providersByUid[$version['uid'].'-root'] = $alias;
  374. }
  375. }
  376. }
  377. }
  378. $result = $this->providers[$name];
  379. // clean up the cache because otherwise using this puts the repo in an inconsistent state with a polluted unfiltered cache
  380. // which is likely not an issue but might cause hard to track behaviors depending on how the repo is used
  381. if ($bypassFilters) {
  382. foreach ($this->providers[$name] as $uid => $provider) {
  383. unset($this->providersByUid[$uid]);
  384. }
  385. unset($this->providers[$name]);
  386. }
  387. return $result;
  388. }
  389. /**
  390. * {@inheritDoc}
  391. */
  392. protected function initialize()
  393. {
  394. parent::initialize();
  395. $repoData = $this->loadDataFromServer();
  396. foreach ($repoData as $package) {
  397. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  398. }
  399. }
  400. /**
  401. * Adds a new package to the repository
  402. *
  403. * @param PackageInterface $package
  404. */
  405. public function addPackage(PackageInterface $package)
  406. {
  407. parent::addPackage($package);
  408. $this->configurePackageTransportOptions($package);
  409. }
  410. protected function loadRootServerFile()
  411. {
  412. if (null !== $this->rootData) {
  413. return $this->rootData;
  414. }
  415. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  416. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  417. }
  418. $jsonUrlParts = parse_url($this->url);
  419. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '.json')) {
  420. $jsonUrl = $this->url;
  421. } else {
  422. $jsonUrl = $this->url . '/packages.json';
  423. }
  424. $data = $this->fetchFile($jsonUrl, 'packages.json');
  425. if (!empty($data['notify-batch'])) {
  426. $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']);
  427. } elseif (!empty($data['notify'])) {
  428. $this->notifyUrl = $this->canonicalizeUrl($data['notify']);
  429. }
  430. if (!empty($data['search'])) {
  431. $this->searchUrl = $this->canonicalizeUrl($data['search']);
  432. }
  433. if (!empty($data['mirrors'])) {
  434. foreach ($data['mirrors'] as $mirror) {
  435. if (!empty($mirror['git-url'])) {
  436. $this->sourceMirrors['git'][] = array('url' => $mirror['git-url'], 'preferred' => !empty($mirror['preferred']));
  437. }
  438. if (!empty($mirror['hg-url'])) {
  439. $this->sourceMirrors['hg'][] = array('url' => $mirror['hg-url'], 'preferred' => !empty($mirror['preferred']));
  440. }
  441. if (!empty($mirror['dist-url'])) {
  442. $this->distMirrors[] = array(
  443. 'url' => $this->canonicalizeUrl($mirror['dist-url']),
  444. 'preferred' => !empty($mirror['preferred']),
  445. );
  446. }
  447. }
  448. }
  449. if (!empty($data['providers-lazy-url'])) {
  450. $this->lazyProvidersUrl = $this->canonicalizeUrl($data['providers-lazy-url']);
  451. $this->hasProviders = true;
  452. $this->hasPartialPackages = !empty($data['packages']) && is_array($data['packages']);
  453. }
  454. if ($this->allowSslDowngrade) {
  455. $this->url = str_replace('https://', 'http://', $this->url);
  456. $this->baseUrl = str_replace('https://', 'http://', $this->baseUrl);
  457. }
  458. if (!empty($data['providers-url'])) {
  459. $this->providersUrl = $this->canonicalizeUrl($data['providers-url']);
  460. $this->hasProviders = true;
  461. }
  462. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  463. $this->hasProviders = true;
  464. }
  465. // force values for packagist
  466. if (preg_match('{^https?://repo\.packagist\.org/?$}i', $this->url) && !empty($this->repoConfig['force-lazy-providers'])) {
  467. $this->url = 'https://repo.packagist.org';
  468. $this->baseUrl = 'https://repo.packagist.org';
  469. $this->lazyProvidersUrl = $this->canonicalizeUrl('https://repo.packagist.org/p/%package%.json');
  470. $this->providersUrl = null;
  471. } elseif (!empty($this->repoConfig['force-lazy-providers'])) {
  472. $this->lazyProvidersUrl = $this->canonicalizeUrl('/p/%package%.json');
  473. $this->providersUrl = null;
  474. }
  475. return $this->rootData = $data;
  476. }
  477. protected function canonicalizeUrl($url)
  478. {
  479. if ('/' === $url[0]) {
  480. return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url);
  481. }
  482. return $url;
  483. }
  484. protected function loadDataFromServer()
  485. {
  486. $data = $this->loadRootServerFile();
  487. return $this->loadIncludes($data);
  488. }
  489. protected function loadProviderListings($data)
  490. {
  491. if (isset($data['providers'])) {
  492. if (!is_array($this->providerListing)) {
  493. $this->providerListing = array();
  494. }
  495. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  496. }
  497. if ($this->providersUrl && isset($data['provider-includes'])) {
  498. $includes = $data['provider-includes'];
  499. foreach ($includes as $include => $metadata) {
  500. $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include);
  501. $cacheKey = str_replace(array('%hash%','$'), '', $include);
  502. if ($this->cache->sha256($cacheKey) === $metadata['sha256']) {
  503. $includedData = json_decode($this->cache->read($cacheKey), true);
  504. } else {
  505. $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']);
  506. }
  507. $this->loadProviderListings($includedData);
  508. }
  509. }
  510. }
  511. protected function loadIncludes($data)
  512. {
  513. $packages = array();
  514. // legacy repo handling
  515. if (!isset($data['packages']) && !isset($data['includes'])) {
  516. foreach ($data as $pkg) {
  517. foreach ($pkg['versions'] as $metadata) {
  518. $packages[] = $metadata;
  519. }
  520. }
  521. return $packages;
  522. }
  523. if (isset($data['packages'])) {
  524. foreach ($data['packages'] as $package => $versions) {
  525. foreach ($versions as $version => $metadata) {
  526. $packages[] = $metadata;
  527. }
  528. }
  529. }
  530. if (isset($data['includes'])) {
  531. foreach ($data['includes'] as $include => $metadata) {
  532. if ($this->cache->sha1($include) === $metadata['sha1']) {
  533. $includedData = json_decode($this->cache->read($include), true);
  534. } else {
  535. $includedData = $this->fetchFile($include);
  536. }
  537. $packages = array_merge($packages, $this->loadIncludes($includedData));
  538. }
  539. }
  540. return $packages;
  541. }
  542. protected function createPackage(array $data, $class = 'Composer\Package\CompletePackage')
  543. {
  544. try {
  545. if (!isset($data['notification-url'])) {
  546. $data['notification-url'] = $this->notifyUrl;
  547. }
  548. $package = $this->loader->load($data, $class);
  549. if (isset($this->sourceMirrors[$package->getSourceType()])) {
  550. $package->setSourceMirrors($this->sourceMirrors[$package->getSourceType()]);
  551. }
  552. $package->setDistMirrors($this->distMirrors);
  553. $this->configurePackageTransportOptions($package);
  554. return $package;
  555. } catch (\Exception $e) {
  556. 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);
  557. }
  558. }
  559. protected function fetchFile($filename, $cacheKey = null, $sha256 = null, $storeLastModifiedTime = false)
  560. {
  561. if (null === $cacheKey) {
  562. $cacheKey = $filename;
  563. $filename = $this->baseUrl.'/'.$filename;
  564. }
  565. // url-encode $ signs in URLs as bad proxies choke on them
  566. if (($pos = strpos($filename, '$')) && preg_match('{^https?://.*}i', $filename)) {
  567. $filename = substr($filename, 0, $pos) . '%24' . substr($filename, $pos + 1);
  568. }
  569. $retries = 3;
  570. while ($retries--) {
  571. try {
  572. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename);
  573. if ($this->eventDispatcher) {
  574. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  575. }
  576. $hostname = parse_url($filename, PHP_URL_HOST) ?: $filename;
  577. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  578. $json = $rfs->getContents($hostname, $filename, false);
  579. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  580. // undo downgrade before trying again if http seems to be hijacked or modifying content somehow
  581. if ($this->allowSslDowngrade) {
  582. $this->url = str_replace('http://', 'https://', $this->url);
  583. $this->baseUrl = str_replace('http://', 'https://', $this->baseUrl);
  584. $filename = str_replace('http://', 'https://', $filename);
  585. }
  586. if ($retries) {
  587. usleep(100000);
  588. continue;
  589. }
  590. // TODO use scarier wording once we know for sure it doesn't do false positives anymore
  591. 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.');
  592. }
  593. $data = JsonFile::parseJson($json, $filename);
  594. $this->outputWarnings($data);
  595. if ($cacheKey) {
  596. if ($storeLastModifiedTime) {
  597. $lastModifiedDate = $rfs->findHeaderValue($rfs->getLastHeaders(), 'last-modified');
  598. if ($lastModifiedDate) {
  599. $data['last-modified'] = $lastModifiedDate;
  600. $json = json_encode($data);
  601. }
  602. }
  603. $this->cache->write($cacheKey, $json);
  604. }
  605. break;
  606. } catch (\Exception $e) {
  607. if ($e instanceof TransportException && $e->getStatusCode() === 404) {
  608. throw $e;
  609. }
  610. if ($retries) {
  611. usleep(100000);
  612. continue;
  613. }
  614. if ($e instanceof RepositorySecurityException) {
  615. throw $e;
  616. }
  617. if ($cacheKey && ($contents = $this->cache->read($cacheKey))) {
  618. if (!$this->degradedMode) {
  619. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  620. $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>');
  621. }
  622. $this->degradedMode = true;
  623. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  624. break;
  625. }
  626. throw $e;
  627. }
  628. }
  629. return $data;
  630. }
  631. protected function fetchFileIfLastModified($filename, $cacheKey, $lastModifiedTime)
  632. {
  633. $retries = 3;
  634. while ($retries--) {
  635. try {
  636. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename);
  637. if ($this->eventDispatcher) {
  638. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  639. }
  640. $hostname = parse_url($filename, PHP_URL_HOST) ?: $filename;
  641. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  642. $options = array('http' => array('header' => array('If-Modified-Since: '.$lastModifiedTime)));
  643. $json = $rfs->getContents($hostname, $filename, false, $options);
  644. if ($json === '' && $rfs->findStatusCode($rfs->getLastHeaders()) === 304) {
  645. return true;
  646. }
  647. $data = JsonFile::parseJson($json, $filename);
  648. $this->outputWarnings($data);
  649. $lastModifiedDate = $rfs->findHeaderValue($rfs->getLastHeaders(), 'last-modified');
  650. if ($lastModifiedDate) {
  651. $data['last-modified'] = $lastModifiedDate;
  652. $json = json_encode($data);
  653. }
  654. $this->cache->write($cacheKey, $json);
  655. return $data;
  656. } catch (\Exception $e) {
  657. if ($e instanceof TransportException && $e->getStatusCode() === 404) {
  658. throw $e;
  659. }
  660. if ($retries) {
  661. usleep(100000);
  662. continue;
  663. }
  664. if (!$this->degradedMode) {
  665. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  666. $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>');
  667. }
  668. $this->degradedMode = true;
  669. return true;
  670. }
  671. }
  672. }
  673. /**
  674. * This initializes the packages key of a partial packages.json that contain some packages inlined + a providers-lazy-url
  675. *
  676. * This should only be called once
  677. */
  678. private function initializePartialPackages()
  679. {
  680. $rootData = $this->loadRootServerFile();
  681. $this->partialPackagesByName = array();
  682. foreach ($rootData['packages'] as $package => $versions) {
  683. $package = strtolower($package);
  684. foreach ($versions as $version) {
  685. $this->partialPackagesByName[$package][] = $version;
  686. if (!empty($version['provide']) && is_array($version['provide'])) {
  687. foreach ($version['provide'] as $provided => $providedVersion) {
  688. $this->partialPackagesByName[strtolower($provided)][] = $version;
  689. }
  690. }
  691. if (!empty($version['replace']) && is_array($version['replace'])) {
  692. foreach ($version['replace'] as $provided => $providedVersion) {
  693. $this->partialPackagesByName[strtolower($provided)][] = $version;
  694. }
  695. }
  696. }
  697. }
  698. // wipe rootData as it is fully consumed at this point and this saves some memory
  699. $this->rootData = true;
  700. }
  701. private function outputWarnings($data)
  702. {
  703. foreach (array('warning', 'info') as $type) {
  704. if (empty($data[$type])) {
  705. continue;
  706. }
  707. if (!empty($data[$type . '-versions'])) {
  708. $versionParser = new VersionParser();
  709. $constraint = $versionParser->parseConstraints($data[$type . '-versions']);
  710. $composer = new Constraint('==', $versionParser->normalize(Composer::getVersion()));
  711. if (!$constraint->matches($composer)) {
  712. continue;
  713. }
  714. }
  715. $this->io->writeError('<'.$type.'>'.ucfirst($type).' from '.$this->url.': '.$data[$type].'</'.$type.'>');
  716. }
  717. }
  718. }