ComposerRepository.php 28 KB

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