ComposerRepository.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 $hasProviders = false;
  36. protected $providersUrl;
  37. protected $providerListing;
  38. protected $providers = array();
  39. protected $providersByUid = array();
  40. protected $loader;
  41. protected $rootAliases;
  42. private $rawData;
  43. private $minimalPackages;
  44. private $degradedMode = false;
  45. private $rootData;
  46. public function __construct(array $repoConfig, IOInterface $io, Config $config)
  47. {
  48. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  49. // assume http as the default protocol
  50. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  51. }
  52. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  53. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  54. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  55. }
  56. $urlBits = parse_url($repoConfig['url']);
  57. if (empty($urlBits['scheme']) || empty($urlBits['host'])) {
  58. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  59. }
  60. if (!isset($repoConfig['options'])) {
  61. $repoConfig['options'] = array();
  62. }
  63. $this->config = $config;
  64. $this->options = $repoConfig['options'];
  65. $this->url = $repoConfig['url'];
  66. $this->baseUrl = rtrim(preg_replace('{^(.*)(?:/packages.json)?(?:[?#].*)?$}', '$1', $this->url), '/');
  67. $this->io = $io;
  68. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  69. $this->loader = new ArrayLoader();
  70. $this->rfs = new RemoteFilesystem($this->io, $this->options);
  71. }
  72. public function setRootAliases(array $rootAliases)
  73. {
  74. $this->rootAliases = $rootAliases;
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. public function getMinimalPackages()
  80. {
  81. if (isset($this->minimalPackages)) {
  82. return $this->minimalPackages;
  83. }
  84. if (null === $this->rawData) {
  85. $this->rawData = $this->loadDataFromServer();
  86. }
  87. $this->minimalPackages = array();
  88. $versionParser = new VersionParser;
  89. foreach ($this->rawData as $package) {
  90. $version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
  91. $data = array(
  92. 'name' => strtolower($package['name']),
  93. 'repo' => $this,
  94. 'version' => $version,
  95. 'raw' => $package,
  96. );
  97. if (!empty($package['replace'])) {
  98. $data['replace'] = $package['replace'];
  99. }
  100. if (!empty($package['provide'])) {
  101. $data['provide'] = $package['provide'];
  102. }
  103. // add branch aliases
  104. if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
  105. $data['alias'] = preg_replace('{(\.9{7})+}', '.x', $aliasNormalized);
  106. $data['alias_normalized'] = $aliasNormalized;
  107. }
  108. $this->minimalPackages[] = $data;
  109. }
  110. return $this->minimalPackages;
  111. }
  112. /**
  113. * {@inheritDoc}
  114. */
  115. public function filterPackages($callback, $class = 'Composer\Package\Package')
  116. {
  117. if (null === $this->rawData) {
  118. $this->rawData = $this->loadDataFromServer();
  119. }
  120. foreach ($this->rawData as $package) {
  121. if (false === call_user_func($callback, $package = $this->createPackage($package, $class))) {
  122. return false;
  123. }
  124. if ($package->getAlias()) {
  125. if (false === call_user_func($callback, $this->createAliasPackage($package))) {
  126. return false;
  127. }
  128. }
  129. }
  130. return true;
  131. }
  132. /**
  133. * {@inheritDoc}
  134. */
  135. public function loadPackage(array $data)
  136. {
  137. $package = $this->createPackage($data['raw'], 'Composer\Package\Package');
  138. $package->setRepository($this);
  139. return $package;
  140. }
  141. /**
  142. * {@inheritDoc}
  143. */
  144. public function loadAliasPackage(array $data, PackageInterface $aliasOf)
  145. {
  146. $aliasPackage = $this->createAliasPackage($aliasOf, $data['version'], $data['alias']);
  147. $aliasPackage->setRepository($this);
  148. return $aliasPackage;
  149. }
  150. public function hasProviders()
  151. {
  152. $this->loadRootServerFile();
  153. return $this->hasProviders;
  154. }
  155. public function resetPackageIds()
  156. {
  157. foreach ($this->providersByUid as $package) {
  158. if ($package instanceof AliasPackage) {
  159. $package->getAliasOf()->setId(-1);
  160. }
  161. $package->setId(-1);
  162. }
  163. }
  164. public function whatProvides(Pool $pool, $name)
  165. {
  166. // skip platform packages
  167. if ($name === 'php' || in_array(substr($name, 0, 4), array('ext-', 'lib-'), true) || $name === '__root__') {
  168. return array();
  169. }
  170. if (isset($this->providers[$name])) {
  171. return $this->providers[$name];
  172. }
  173. if (null === $this->providerListing) {
  174. $this->loadProviderListings($this->loadRootServerFile());
  175. }
  176. if ($this->providersUrl) {
  177. // package does not exist in this repo
  178. if (!isset($this->providerListing[$name])) {
  179. return array();
  180. }
  181. $hash = $this->providerListing[$name]['sha256'];
  182. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  183. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  184. } else {
  185. // BC handling for old providers-includes
  186. $url = 'p/'.$name.'.json';
  187. // package does not exist in this repo
  188. if (!isset($this->providerListing[$url])) {
  189. return array();
  190. }
  191. $hash = $this->providerListing[$url]['sha256'];
  192. $cacheKey = null;
  193. }
  194. if ($this->cache->sha256($cacheKey) === $hash) {
  195. $packages = json_decode($this->cache->read($cacheKey), true);
  196. } else {
  197. $packages = $this->fetchFile($url, $cacheKey, $hash);
  198. }
  199. $this->providers[$name] = array();
  200. foreach ($packages['packages'] as $versions) {
  201. foreach ($versions as $version) {
  202. // avoid loading the same objects twice
  203. if (isset($this->providersByUid[$version['uid']])) {
  204. // skip if already assigned
  205. if (!isset($this->providers[$name][$version['uid']])) {
  206. // expand alias in two packages
  207. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  208. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  209. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  210. } else {
  211. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  212. }
  213. // check for root aliases
  214. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  215. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  216. }
  217. }
  218. } else {
  219. if (!$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  220. continue;
  221. }
  222. // load acceptable packages in the providers
  223. $package = $this->createPackage($version, 'Composer\Package\Package');
  224. $package->setRepository($this);
  225. $this->providers[$name][$version['uid']] = $package;
  226. $this->providersByUid[$version['uid']] = $package;
  227. if ($package->getAlias()) {
  228. $alias = $this->createAliasPackage($package);
  229. $alias->setRepository($this);
  230. $this->providers[$name][$version['uid'].'-alias'] = $alias;
  231. // override provider with its alias so it can be expanded in the if block above
  232. $this->providersByUid[$version['uid']] = $alias;
  233. }
  234. // handle root package aliases
  235. unset($rootAliasData);
  236. if (isset($this->rootAliases[$name][$package->getVersion()])) {
  237. $rootAliasData = $this->rootAliases[$name][$package->getVersion()];
  238. } elseif (($aliasNormalized = $package->getAlias()) && isset($this->rootAliases[$name][$aliasNormalized])) {
  239. $rootAliasData = $this->rootAliases[$name][$aliasNormalized];
  240. }
  241. if (isset($rootAliasData)) {
  242. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  243. $alias->setRepository($this);
  244. $this->providers[$name][$version['uid'].'-root'] = $alias;
  245. $this->providersByUid[$version['uid'].'-root'] = $alias;
  246. }
  247. }
  248. }
  249. }
  250. return $this->providers[$name];
  251. }
  252. /**
  253. * {@inheritDoc}
  254. */
  255. protected function initialize()
  256. {
  257. parent::initialize();
  258. $repoData = $this->loadDataFromServer();
  259. foreach ($repoData as $package) {
  260. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  261. }
  262. }
  263. protected function loadRootServerFile()
  264. {
  265. if (null !== $this->rootData) {
  266. return $this->rootData;
  267. }
  268. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  269. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  270. }
  271. $jsonUrlParts = parse_url($this->url);
  272. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '/packages.json')) {
  273. $jsonUrl = $this->url;
  274. } else {
  275. $jsonUrl = $this->url . '/packages.json';
  276. }
  277. $data = $this->fetchFile($jsonUrl, 'packages.json');
  278. // TODO remove this BC notify_batch support
  279. if (!empty($data['notify_batch'])) {
  280. $notifyBatchUrl = $data['notify_batch'];
  281. }
  282. if (!empty($data['notify-batch'])) {
  283. $notifyBatchUrl = $data['notify-batch'];
  284. }
  285. if (!empty($notifyBatchUrl)) {
  286. if ('/' === $notifyBatchUrl[0]) {
  287. $this->notifyUrl = preg_replace('{(https?://[^/]+).*}i', '$1' . $notifyBatchUrl, $this->url);
  288. } else {
  289. $this->notifyUrl = $notifyBatchUrl;
  290. }
  291. }
  292. if (!$this->notifyUrl && !empty($data['notify'])) {
  293. if ('/' === $data['notify'][0]) {
  294. $this->notifyUrl = preg_replace('{(https?://[^/]+).*}i', '$1' . $data['notify'], $this->url);
  295. } else {
  296. $this->notifyUrl = $data['notify'];
  297. }
  298. }
  299. if (!empty($data['providers-url'])) {
  300. if ('/' === $data['providers-url'][0]) {
  301. $this->providersUrl = preg_replace('{(https?://[^/]+).*}i', '$1' . $data['providers-url'], $this->url);
  302. } else {
  303. $this->providersUrl = $data['providers-url'];
  304. }
  305. $this->hasProviders = true;
  306. }
  307. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  308. $this->hasProviders = true;
  309. }
  310. return $this->rootData = $data;
  311. }
  312. protected function loadDataFromServer()
  313. {
  314. $data = $this->loadRootServerFile();
  315. return $this->loadIncludes($data);
  316. }
  317. protected function loadProviderListings($data)
  318. {
  319. if (isset($data['providers'])) {
  320. if (!is_array($this->providerListing)) {
  321. $this->providerListing = array();
  322. }
  323. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  324. }
  325. if ($this->providersUrl && isset($data['provider-includes'])) {
  326. $includes = $data['provider-includes'];
  327. } elseif (isset($data['providers-includes'])) {
  328. // BC layer for old-style providers-includes
  329. $includes = $data['providers-includes'];
  330. }
  331. if (!empty($includes)) {
  332. foreach ($includes as $include => $metadata) {
  333. if ($this->cache->sha256($include) === $metadata['sha256']) {
  334. $includedData = json_decode($this->cache->read($include), true);
  335. } else {
  336. $includedData = $this->fetchFile($include, null, $metadata['sha256']);
  337. }
  338. $this->loadProviderListings($includedData);
  339. }
  340. }
  341. }
  342. protected function loadIncludes($data)
  343. {
  344. $packages = array();
  345. // legacy repo handling
  346. if (!isset($data['packages']) && !isset($data['includes'])) {
  347. foreach ($data as $pkg) {
  348. foreach ($pkg['versions'] as $metadata) {
  349. $packages[] = $metadata;
  350. }
  351. }
  352. return $packages;
  353. }
  354. if (isset($data['packages'])) {
  355. foreach ($data['packages'] as $package => $versions) {
  356. foreach ($versions as $version => $metadata) {
  357. $packages[] = $metadata;
  358. }
  359. }
  360. }
  361. if (isset($data['includes'])) {
  362. foreach ($data['includes'] as $include => $metadata) {
  363. if ($this->cache->sha1($include) === $metadata['sha1']) {
  364. $includedData = json_decode($this->cache->read($include), true);
  365. } else {
  366. $includedData = $this->fetchFile($include);
  367. }
  368. $packages = array_merge($packages, $this->loadIncludes($includedData));
  369. }
  370. }
  371. return $packages;
  372. }
  373. protected function createPackage(array $data, $class)
  374. {
  375. try {
  376. $data['notification-url'] = $this->notifyUrl;
  377. return $this->loader->load($data, 'Composer\Package\CompletePackage');
  378. } catch (\Exception $e) {
  379. 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);
  380. }
  381. }
  382. protected function fetchFile($filename, $cacheKey = null, $sha256 = null)
  383. {
  384. if (!$cacheKey) {
  385. $cacheKey = $filename;
  386. $filename = $this->baseUrl.'/'.$filename;
  387. }
  388. $retries = 3;
  389. while ($retries--) {
  390. try {
  391. $json = $this->rfs->getContents($filename, $filename, false);
  392. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  393. if ($retries) {
  394. usleep(100);
  395. continue;
  396. }
  397. // TODO throw SecurityException and abort once we are sure this can not happen accidentally
  398. $this->io->write('<warning>The contents of '.$filename.' do not match its signature, this is most likely due to a temporary glitch but could indicate a man-in-the-middle attack. Try running composer again and please report it if it still persists.</warning>');
  399. }
  400. $data = JsonFile::parseJson($json, $filename);
  401. $this->cache->write($cacheKey, $json);
  402. break;
  403. } catch (\Exception $e) {
  404. if (!$retries) {
  405. if ($contents = $this->cache->read($cacheKey)) {
  406. if (!$this->degradedMode) {
  407. $this->io->write('<warning>'.$e->getMessage().'</warning>');
  408. $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>');
  409. }
  410. $this->degradedMode = true;
  411. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  412. break;
  413. }
  414. throw $e;
  415. }
  416. usleep(100);
  417. }
  418. }
  419. return $data;
  420. }
  421. }