ComposerRepository.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. use Composer\Downloader\TransportException;
  23. /**
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. */
  26. class ComposerRepository extends ArrayRepository implements NotifiableRepositoryInterface, StreamableRepositoryInterface
  27. {
  28. protected $config;
  29. protected $options;
  30. protected $url;
  31. protected $baseUrl;
  32. protected $io;
  33. protected $cache;
  34. protected $notifyUrl;
  35. protected $hasProviders = false;
  36. protected $providerListing;
  37. protected $providers = array();
  38. protected $providersByUid = array();
  39. protected $loader;
  40. private $rawData;
  41. private $minimalPackages;
  42. private $degradedMode = false;
  43. private $rootData;
  44. public function __construct(array $repoConfig, IOInterface $io, Config $config)
  45. {
  46. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  47. // assume http as the default protocol
  48. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  49. }
  50. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  51. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  52. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  53. }
  54. if (function_exists('filter_var') && version_compare(PHP_VERSION, '5.3.3', '>=') && !filter_var($repoConfig['url'], FILTER_VALIDATE_URL)) {
  55. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  56. }
  57. if (!isset($repoConfig['options'])) {
  58. $repoConfig['options'] = array();
  59. }
  60. $this->config = $config;
  61. $this->options = $repoConfig['options'];
  62. $this->url = $repoConfig['url'];
  63. $this->baseUrl = rtrim(preg_replace('{^(.*)(?:/packages.json)?(?:[?#].*)?$}', '$1', $this->url), '/');
  64. $this->io = $io;
  65. $this->cache = new Cache($io, $config->get('home').'/cache/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url));
  66. $this->loader = new ArrayLoader();
  67. }
  68. /**
  69. * {@inheritDoc}
  70. */
  71. public function notifyInstall(PackageInterface $package)
  72. {
  73. if (!$this->notifyUrl || !$this->config->get('notify-on-install')) {
  74. return;
  75. }
  76. // TODO use an optional curl_multi pool for all the notifications
  77. $url = str_replace('%package%', $package->getPrettyName(), $this->notifyUrl);
  78. $params = array(
  79. 'version' => $package->getPrettyVersion(),
  80. 'version_normalized' => $package->getVersion(),
  81. );
  82. $opts = array('http' =>
  83. array(
  84. 'method' => 'POST',
  85. 'header' => 'Content-type: application/x-www-form-urlencoded',
  86. 'content' => http_build_query($params, '', '&'),
  87. 'timeout' => 3,
  88. )
  89. );
  90. $context = stream_context_create($opts);
  91. @file_get_contents($url, false, $context);
  92. }
  93. /**
  94. * {@inheritDoc}
  95. */
  96. public function getMinimalPackages()
  97. {
  98. if (isset($this->minimalPackages)) {
  99. return $this->minimalPackages;
  100. }
  101. if (null === $this->rawData) {
  102. $this->rawData = $this->loadDataFromServer();
  103. }
  104. $this->minimalPackages = array();
  105. $versionParser = new VersionParser;
  106. foreach ($this->rawData as $package) {
  107. $version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
  108. $data = array(
  109. 'name' => strtolower($package['name']),
  110. 'repo' => $this,
  111. 'version' => $version,
  112. 'raw' => $package,
  113. );
  114. if (!empty($package['replace'])) {
  115. $data['replace'] = $package['replace'];
  116. }
  117. if (!empty($package['provide'])) {
  118. $data['provide'] = $package['provide'];
  119. }
  120. // add branch aliases
  121. if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
  122. $data['alias'] = preg_replace('{(\.9{7})+}', '.x', $aliasNormalized);
  123. $data['alias_normalized'] = $aliasNormalized;
  124. }
  125. $this->minimalPackages[] = $data;
  126. }
  127. return $this->minimalPackages;
  128. }
  129. /**
  130. * {@inheritDoc}
  131. */
  132. public function filterPackages($callback, $class = 'Composer\Package\Package')
  133. {
  134. if (null === $this->rawData) {
  135. $this->rawData = $this->loadDataFromServer();
  136. }
  137. foreach ($this->rawData as $package) {
  138. if (false === call_user_func($callback, $package = $this->createPackage($package, $class))) {
  139. return false;
  140. }
  141. if ($package->getAlias()) {
  142. if (false === call_user_func($callback, $this->createAliasPackage($package))) {
  143. return false;
  144. }
  145. }
  146. }
  147. return true;
  148. }
  149. /**
  150. * {@inheritDoc}
  151. */
  152. public function loadPackage(array $data)
  153. {
  154. $package = $this->createPackage($data['raw'], 'Composer\Package\Package');
  155. $package->setRepository($this);
  156. return $package;
  157. }
  158. /**
  159. * {@inheritDoc}
  160. */
  161. public function loadAliasPackage(array $data, PackageInterface $aliasOf)
  162. {
  163. $aliasPackage = $this->createAliasPackage($aliasOf, $data['version'], $data['alias']);
  164. $aliasPackage->setRepository($this);
  165. return $aliasPackage;
  166. }
  167. public function hasProviders()
  168. {
  169. $this->loadRootServerFile();
  170. return $this->hasProviders;
  171. }
  172. public function resetPackageIds()
  173. {
  174. foreach ($this->providersByUid as $package) {
  175. if ($package instanceof AliasPackage) {
  176. $package->getAliasOf()->setId(-1);
  177. }
  178. $package->setId(-1);
  179. }
  180. }
  181. public function whatProvides(Pool $pool, $name)
  182. {
  183. // skip platform packages
  184. if ($name === 'php' || in_array(substr($name, 0, 4), array('ext-', 'lib-'), true) || $name === '__root__') {
  185. return array();
  186. }
  187. if (isset($this->providers[$name])) {
  188. return $this->providers[$name];
  189. }
  190. if (null === $this->providerListing) {
  191. $this->loadProviderListings($this->loadRootServerFile());
  192. }
  193. $url = 'p/'.$name.'.json';
  194. // package does not exist in this repo
  195. if (!isset($this->providerListing[$url])) {
  196. return array();
  197. }
  198. if ($this->cache->sha256($url) === $this->providerListing[$url]['sha256']) {
  199. $packages = json_decode($this->cache->read($url), true);
  200. } else {
  201. $packages = $this->fetchFile($url, null, $this->providerListing[$url]['sha256']);
  202. }
  203. $this->providers[$name] = array();
  204. foreach ($packages['packages'] as $versions) {
  205. foreach ($versions as $version) {
  206. // avoid loading the same objects twice
  207. if (isset($this->providersByUid[$version['uid']])) {
  208. // skip if already assigned
  209. if (!isset($this->providers[$name][$version['uid']])) {
  210. // expand alias in two packages
  211. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  212. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  213. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  214. } else {
  215. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  216. }
  217. }
  218. } else {
  219. if (!$pool->isPackageAcceptable($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. }
  235. }
  236. }
  237. return $this->providers[$name];
  238. }
  239. /**
  240. * {@inheritDoc}
  241. */
  242. protected function initialize()
  243. {
  244. parent::initialize();
  245. $repoData = $this->loadDataFromServer();
  246. foreach ($repoData as $package) {
  247. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  248. }
  249. }
  250. protected function loadRootServerFile()
  251. {
  252. if (null !== $this->rootData) {
  253. return $this->rootData;
  254. }
  255. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  256. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  257. }
  258. $jsonUrlParts = parse_url($this->url);
  259. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '/packages.json')) {
  260. $jsonUrl = $this->url;
  261. } else {
  262. $jsonUrl = $this->url . '/packages.json';
  263. }
  264. $data = $this->fetchFile($jsonUrl, 'packages.json');
  265. if (!empty($data['notify'])) {
  266. if ('/' === $data['notify'][0]) {
  267. $this->notifyUrl = preg_replace('{(https?://[^/]+).*}i', '$1' . $data['notify'], $this->url);
  268. } else {
  269. $this->notifyUrl = $data['notify'];
  270. }
  271. }
  272. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  273. $this->hasProviders = true;
  274. }
  275. return $this->rootData = $data;
  276. }
  277. protected function loadDataFromServer()
  278. {
  279. $data = $this->loadRootServerFile();
  280. return $this->loadIncludes($data);
  281. }
  282. protected function loadProviderListings($data)
  283. {
  284. if (isset($data['providers'])) {
  285. if (!is_array($this->providerListing)) {
  286. $this->providerListing = array();
  287. }
  288. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  289. }
  290. if (isset($data['providers-includes'])) {
  291. foreach ($data['providers-includes'] as $include => $metadata) {
  292. if ($this->cache->sha256($include) === $metadata['sha256']) {
  293. $includedData = json_decode($this->cache->read($include), true);
  294. } else {
  295. $includedData = $this->fetchFile($include, null, $metadata['sha256']);
  296. }
  297. $this->loadProviderListings($includedData);
  298. }
  299. }
  300. }
  301. protected function loadIncludes($data)
  302. {
  303. $packages = array();
  304. // legacy repo handling
  305. if (!isset($data['packages']) && !isset($data['includes'])) {
  306. foreach ($data as $pkg) {
  307. foreach ($pkg['versions'] as $metadata) {
  308. $packages[] = $metadata;
  309. }
  310. }
  311. return;
  312. }
  313. if (isset($data['packages'])) {
  314. foreach ($data['packages'] as $package => $versions) {
  315. foreach ($versions as $version => $metadata) {
  316. $packages[] = $metadata;
  317. }
  318. }
  319. }
  320. if (isset($data['includes'])) {
  321. foreach ($data['includes'] as $include => $metadata) {
  322. if ($this->cache->sha1($include) === $metadata['sha1']) {
  323. $includedData = json_decode($this->cache->read($include), true);
  324. } else {
  325. $includedData = $this->fetchFile($include);
  326. }
  327. $packages = array_merge($packages, $this->loadIncludes($includedData));
  328. }
  329. }
  330. return $packages;
  331. }
  332. protected function createPackage(array $data, $class)
  333. {
  334. try {
  335. return $this->loader->load($data, 'Composer\Package\CompletePackage');
  336. } catch (\Exception $e) {
  337. 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);
  338. }
  339. }
  340. protected function fetchFile($filename, $cacheKey = null, $sha256 = null)
  341. {
  342. if (!$cacheKey) {
  343. $cacheKey = $filename;
  344. $filename = $this->baseUrl.'/'.$filename;
  345. }
  346. $retries = 3;
  347. while ($retries--) {
  348. try {
  349. $json = new JsonFile($filename, new RemoteFilesystem($this->io, $this->options));
  350. $data = $json->read();
  351. $encoded = json_encode($data);
  352. if ($sha256 && $sha256 !== hash('sha256', $encoded)) {
  353. if ($retries) {
  354. usleep(100);
  355. continue;
  356. }
  357. // TODO throw SecurityException and abort once we are sure this can not happen accidentally
  358. $this->io->write('<warning>The contents of '.$filename.' do not match its signature, this may be due to a temporary glitch or a man-in-the-middle attack. Please report this.</warning>');
  359. }
  360. $this->cache->write($cacheKey, $encoded);
  361. break;
  362. } catch (\Exception $e) {
  363. if (!$retries) {
  364. if ($contents = $this->cache->read($cacheKey)) {
  365. if (!$this->degradedMode) {
  366. $this->io->write('<warning>'.$e->getMessage().'</warning>');
  367. $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>');
  368. }
  369. $this->degradedMode = true;
  370. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  371. break;
  372. }
  373. throw $e;
  374. }
  375. usleep(100);
  376. }
  377. }
  378. return $data;
  379. }
  380. }