ComposerRepository.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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\IO\IOInterface;
  21. use Composer\Util\RemoteFilesystem;
  22. /**
  23. * @author Jordi Boggiano <j.boggiano@seld.be>
  24. */
  25. class ComposerRepository extends ArrayRepository implements StreamableRepositoryInterface
  26. {
  27. protected $config;
  28. protected $options;
  29. protected $url;
  30. protected $baseUrl;
  31. protected $io;
  32. protected $rfs;
  33. protected $cache;
  34. protected $notifyUrl;
  35. protected $searchUrl;
  36. protected $hasProviders = false;
  37. protected $providersUrl;
  38. protected $providerListing;
  39. protected $providers = array();
  40. protected $providersByUid = array();
  41. protected $loader;
  42. protected $rootAliases;
  43. protected $allowSslDowngrade = false;
  44. private $rawData;
  45. private $minimalPackages;
  46. private $degradedMode = false;
  47. private $rootData;
  48. public function __construct(array $repoConfig, IOInterface $io, Config $config)
  49. {
  50. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  51. // assume http as the default protocol
  52. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  53. }
  54. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  55. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  56. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  57. }
  58. $urlBits = parse_url($repoConfig['url']);
  59. if (empty($urlBits['scheme']) || empty($urlBits['host'])) {
  60. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  61. }
  62. if (!isset($repoConfig['options'])) {
  63. $repoConfig['options'] = array();
  64. }
  65. if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
  66. $this->allowSslDowngrade = true;
  67. }
  68. $this->config = $config;
  69. $this->options = $repoConfig['options'];
  70. $this->url = $repoConfig['url'];
  71. $this->baseUrl = rtrim(preg_replace('{^(.*)(?:/packages.json)?(?:[?#].*)?$}', '$1', $this->url), '/');
  72. $this->io = $io;
  73. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  74. $this->loader = new ArrayLoader();
  75. $this->rfs = new RemoteFilesystem($this->io, $this->options);
  76. }
  77. public function setRootAliases(array $rootAliases)
  78. {
  79. $this->rootAliases = $rootAliases;
  80. }
  81. public function getPackages()
  82. {
  83. if ($this->hasProviders()) {
  84. throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.');
  85. }
  86. return parent::getPackages();
  87. }
  88. /**
  89. * {@inheritDoc}
  90. */
  91. public function getMinimalPackages()
  92. {
  93. if (isset($this->minimalPackages)) {
  94. return $this->minimalPackages;
  95. }
  96. if (null === $this->rawData) {
  97. $this->rawData = $this->loadDataFromServer();
  98. }
  99. $this->minimalPackages = array();
  100. $versionParser = new VersionParser;
  101. foreach ($this->rawData as $package) {
  102. $version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
  103. $data = array(
  104. 'name' => strtolower($package['name']),
  105. 'repo' => $this,
  106. 'version' => $version,
  107. 'raw' => $package,
  108. );
  109. if (!empty($package['replace'])) {
  110. $data['replace'] = $package['replace'];
  111. }
  112. if (!empty($package['provide'])) {
  113. $data['provide'] = $package['provide'];
  114. }
  115. // add branch aliases
  116. if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
  117. $data['alias'] = preg_replace('{(\.9{7})+}', '.x', $aliasNormalized);
  118. $data['alias_normalized'] = $aliasNormalized;
  119. }
  120. $this->minimalPackages[] = $data;
  121. }
  122. return $this->minimalPackages;
  123. }
  124. /**
  125. * {@inheritDoc}
  126. */
  127. public function search($query, $mode = 0)
  128. {
  129. $this->loadRootServerFile();
  130. if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
  131. $url = str_replace('%query%', $query, $this->searchUrl);
  132. $json = $this->rfs->getContents($url, $url, false);
  133. $results = JsonFile::parseJson($json, $url);
  134. return $results['results'];
  135. }
  136. if ($this->hasProviders()) {
  137. $results = array();
  138. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  139. foreach ($this->getProviderNames() as $name) {
  140. if (preg_match($regex, $name)) {
  141. $results[] = array('name' => $name);
  142. }
  143. }
  144. return $results;
  145. }
  146. return parent::search($query, $mode);
  147. }
  148. public function getProviderNames()
  149. {
  150. $this->loadRootServerFile();
  151. if (null === $this->providerListing) {
  152. $this->loadProviderListings($this->loadRootServerFile());
  153. }
  154. if ($this->providersUrl) {
  155. return array_keys($this->providerListing);
  156. }
  157. // BC handling for old providers-includes
  158. $providers = array();
  159. foreach (array_keys($this->providerListing) as $provider) {
  160. $providers[] = substr($provider, 2, -5);
  161. }
  162. return $providers;
  163. }
  164. /**
  165. * {@inheritDoc}
  166. */
  167. public function loadPackage(array $data)
  168. {
  169. $package = $this->createPackage($data['raw'], 'Composer\Package\Package');
  170. $package->setRepository($this);
  171. return $package;
  172. }
  173. /**
  174. * {@inheritDoc}
  175. */
  176. public function loadAliasPackage(array $data, PackageInterface $aliasOf)
  177. {
  178. $aliasPackage = $this->createAliasPackage($aliasOf, $data['version'], $data['alias']);
  179. $aliasPackage->setRepository($this);
  180. return $aliasPackage;
  181. }
  182. public function hasProviders()
  183. {
  184. $this->loadRootServerFile();
  185. return $this->hasProviders;
  186. }
  187. public function resetPackageIds()
  188. {
  189. foreach ($this->providersByUid as $package) {
  190. if ($package instanceof AliasPackage) {
  191. $package->getAliasOf()->setId(-1);
  192. }
  193. $package->setId(-1);
  194. }
  195. }
  196. public function whatProvides(Pool $pool, $name)
  197. {
  198. if (isset($this->providers[$name])) {
  199. return $this->providers[$name];
  200. }
  201. // skip platform packages
  202. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name) {
  203. return array();
  204. }
  205. if (null === $this->providerListing) {
  206. $this->loadProviderListings($this->loadRootServerFile());
  207. }
  208. if ($this->providersUrl) {
  209. // package does not exist in this repo
  210. if (!isset($this->providerListing[$name])) {
  211. return array();
  212. }
  213. $hash = $this->providerListing[$name]['sha256'];
  214. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  215. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  216. } else {
  217. // BC handling for old providers-includes
  218. $url = 'p/'.$name.'.json';
  219. // package does not exist in this repo
  220. if (!isset($this->providerListing[$url])) {
  221. return array();
  222. }
  223. $hash = $this->providerListing[$url]['sha256'];
  224. $cacheKey = null;
  225. }
  226. if ($this->cache->sha256($cacheKey) === $hash) {
  227. $packages = json_decode($this->cache->read($cacheKey), true);
  228. } else {
  229. $packages = $this->fetchFile($url, $cacheKey, $hash);
  230. }
  231. $this->providers[$name] = array();
  232. foreach ($packages['packages'] as $versions) {
  233. foreach ($versions as $version) {
  234. // avoid loading the same objects twice
  235. if (isset($this->providersByUid[$version['uid']])) {
  236. // skip if already assigned
  237. if (!isset($this->providers[$name][$version['uid']])) {
  238. // expand alias in two packages
  239. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  240. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  241. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  242. } else {
  243. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  244. }
  245. // check for root aliases
  246. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  247. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  248. }
  249. }
  250. } else {
  251. if (isset($version['provide']) || isset($version['replace'])) {
  252. // collect names
  253. $names = array(
  254. strtolower($version['name']) => true,
  255. );
  256. if (isset($version['provide'])) {
  257. foreach ($version['provide'] as $target => $constraint) {
  258. $names[strtolower($target)] = true;
  259. }
  260. }
  261. if (isset($version['replace'])) {
  262. foreach ($version['replace'] as $target => $constraint) {
  263. $names[strtolower($target)] = true;
  264. }
  265. }
  266. $names = array_keys($names);
  267. } else {
  268. $names = array(strtolower($version['name']));
  269. }
  270. if (!$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  271. continue;
  272. }
  273. // load acceptable packages in the providers
  274. $package = $this->createPackage($version, 'Composer\Package\Package');
  275. $package->setRepository($this);
  276. if ($package instanceof AliasPackage) {
  277. $aliased = $package->getAliasOf();
  278. $aliased->setRepository($this);
  279. $this->providers[$name][$version['uid']] = $aliased;
  280. $this->providers[$name][$version['uid'].'-alias'] = $package;
  281. // override provider with its alias so it can be expanded in the if block above
  282. $this->providersByUid[$version['uid']] = $package;
  283. } else {
  284. $this->providers[$name][$version['uid']] = $package;
  285. $this->providersByUid[$version['uid']] = $package;
  286. }
  287. // handle root package aliases
  288. unset($rootAliasData);
  289. if (isset($this->rootAliases[$name][$package->getVersion()])) {
  290. $rootAliasData = $this->rootAliases[$name][$package->getVersion()];
  291. } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$name][$package->getAliasOf()->getVersion()])) {
  292. $rootAliasData = $this->rootAliases[$name][$package->getAliasOf()->getVersion()];
  293. }
  294. if (isset($rootAliasData)) {
  295. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  296. $alias->setRepository($this);
  297. $this->providers[$name][$version['uid'].'-root'] = $alias;
  298. $this->providersByUid[$version['uid'].'-root'] = $alias;
  299. }
  300. }
  301. }
  302. }
  303. return $this->providers[$name];
  304. }
  305. /**
  306. * {@inheritDoc}
  307. */
  308. protected function initialize()
  309. {
  310. parent::initialize();
  311. $repoData = $this->loadDataFromServer();
  312. foreach ($repoData as $package) {
  313. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  314. }
  315. }
  316. protected function loadRootServerFile()
  317. {
  318. if (null !== $this->rootData) {
  319. return $this->rootData;
  320. }
  321. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  322. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  323. }
  324. $jsonUrlParts = parse_url($this->url);
  325. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '/packages.json')) {
  326. $jsonUrl = $this->url;
  327. } else {
  328. $jsonUrl = $this->url . '/packages.json';
  329. }
  330. $data = $this->fetchFile($jsonUrl, 'packages.json');
  331. if (!empty($data['notify-batch'])) {
  332. $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']);
  333. } elseif (!empty($data['notify_batch'])) {
  334. // TODO remove this BC notify_batch support
  335. $this->notifyUrl = $this->canonicalizeUrl($data['notify_batch']);
  336. } elseif (!empty($data['notify'])) {
  337. $this->notifyUrl = $this->canonicalizeUrl($data['notify']);
  338. }
  339. if (!empty($data['search'])) {
  340. $this->searchUrl = $this->canonicalizeUrl($data['search']);
  341. }
  342. if ($this->allowSslDowngrade) {
  343. $this->url = str_replace('https://', 'http://', $this->url);
  344. }
  345. if (!empty($data['providers-url'])) {
  346. $this->providersUrl = $this->canonicalizeUrl($data['providers-url']);
  347. $this->hasProviders = true;
  348. }
  349. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  350. $this->hasProviders = true;
  351. }
  352. return $this->rootData = $data;
  353. }
  354. protected function canonicalizeUrl($url)
  355. {
  356. if ('/' === $url[0]) {
  357. return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url);
  358. }
  359. return $url;
  360. }
  361. protected function loadDataFromServer()
  362. {
  363. $data = $this->loadRootServerFile();
  364. return $this->loadIncludes($data);
  365. }
  366. protected function loadProviderListings($data)
  367. {
  368. if (isset($data['providers'])) {
  369. if (!is_array($this->providerListing)) {
  370. $this->providerListing = array();
  371. }
  372. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  373. }
  374. if ($this->providersUrl && isset($data['provider-includes'])) {
  375. $includes = $data['provider-includes'];
  376. foreach ($includes as $include => $metadata) {
  377. $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include);
  378. $cacheKey = str_replace(array('%hash%','$'), '', $include);
  379. if ($this->cache->sha256($cacheKey) === $metadata['sha256']) {
  380. $includedData = json_decode($this->cache->read($cacheKey), true);
  381. } else {
  382. $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']);
  383. }
  384. $this->loadProviderListings($includedData);
  385. }
  386. } elseif (isset($data['providers-includes'])) {
  387. // BC layer for old-style providers-includes
  388. $includes = $data['providers-includes'];
  389. foreach ($includes as $include => $metadata) {
  390. if ($this->cache->sha256($include) === $metadata['sha256']) {
  391. $includedData = json_decode($this->cache->read($include), true);
  392. } else {
  393. $includedData = $this->fetchFile($include, null, $metadata['sha256']);
  394. }
  395. $this->loadProviderListings($includedData);
  396. }
  397. }
  398. }
  399. protected function loadIncludes($data)
  400. {
  401. $packages = array();
  402. // legacy repo handling
  403. if (!isset($data['packages']) && !isset($data['includes'])) {
  404. foreach ($data as $pkg) {
  405. foreach ($pkg['versions'] as $metadata) {
  406. $packages[] = $metadata;
  407. }
  408. }
  409. return $packages;
  410. }
  411. if (isset($data['packages'])) {
  412. foreach ($data['packages'] as $package => $versions) {
  413. foreach ($versions as $version => $metadata) {
  414. $packages[] = $metadata;
  415. }
  416. }
  417. }
  418. if (isset($data['includes'])) {
  419. foreach ($data['includes'] as $include => $metadata) {
  420. if ($this->cache->sha1($include) === $metadata['sha1']) {
  421. $includedData = json_decode($this->cache->read($include), true);
  422. } else {
  423. $includedData = $this->fetchFile($include);
  424. }
  425. $packages = array_merge($packages, $this->loadIncludes($includedData));
  426. }
  427. }
  428. return $packages;
  429. }
  430. protected function createPackage(array $data, $class)
  431. {
  432. try {
  433. $data['notification-url'] = $this->notifyUrl;
  434. return $this->loader->load($data, 'Composer\Package\CompletePackage');
  435. } catch (\Exception $e) {
  436. 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);
  437. }
  438. }
  439. protected function fetchFile($filename, $cacheKey = null, $sha256 = null)
  440. {
  441. if (!$cacheKey) {
  442. $cacheKey = $filename;
  443. $filename = $this->baseUrl.'/'.$filename;
  444. }
  445. $retries = 3;
  446. while ($retries--) {
  447. try {
  448. $json = $this->rfs->getContents($filename, $filename, false);
  449. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  450. if ($retries) {
  451. usleep(100);
  452. continue;
  453. }
  454. // TODO use scarier wording once we know for sure it doesn't do false positives anymore
  455. 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.');
  456. }
  457. $data = JsonFile::parseJson($json, $filename);
  458. $this->cache->write($cacheKey, $json);
  459. break;
  460. } catch (\Exception $e) {
  461. if ($retries) {
  462. usleep(100);
  463. continue;
  464. }
  465. if ($e instanceof RepositorySecurityException) {
  466. throw $e;
  467. }
  468. if ($contents = $this->cache->read($cacheKey)) {
  469. if (!$this->degradedMode) {
  470. $this->io->write('<warning>'.$e->getMessage().'</warning>');
  471. $this->io->write('<warning>'.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  472. }
  473. $this->degradedMode = true;
  474. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  475. break;
  476. }
  477. throw $e;
  478. }
  479. }
  480. return $data;
  481. }
  482. }