ComposerRepository.php 28 KB

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