ComposerRepository.php 32 KB

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