ComposerRepository.php 31 KB

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