ComposerRepository.php 28 KB

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