Config.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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;
  12. use Composer\Config\ConfigSourceInterface;
  13. use Composer\Downloader\TransportException;
  14. use Composer\IO\IOInterface;
  15. use Composer\Util\Platform;
  16. /**
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. class Config
  20. {
  21. const RELATIVE_PATHS = 1;
  22. public static $defaultConfig = array(
  23. 'process-timeout' => 300,
  24. 'use-include-path' => false,
  25. 'preferred-install' => 'auto',
  26. 'notify-on-install' => true,
  27. 'github-protocols' => array('https', 'ssh', 'git'),
  28. 'vendor-dir' => 'vendor',
  29. 'bin-dir' => '{$vendor-dir}/bin',
  30. 'cache-dir' => '{$home}/cache',
  31. 'data-dir' => '{$home}',
  32. 'cache-files-dir' => '{$cache-dir}/files',
  33. 'cache-repo-dir' => '{$cache-dir}/repo',
  34. 'cache-vcs-dir' => '{$cache-dir}/vcs',
  35. 'cache-ttl' => 15552000, // 6 months
  36. 'cache-files-ttl' => null, // fallback to cache-ttl
  37. 'cache-files-maxsize' => '300MiB',
  38. 'bin-compat' => 'auto',
  39. 'discard-changes' => false,
  40. 'autoloader-suffix' => null,
  41. 'sort-packages' => false,
  42. 'optimize-autoloader' => false,
  43. 'classmap-authoritative' => false,
  44. 'apcu-autoloader' => false,
  45. 'prepend-autoloader' => true,
  46. 'github-domains' => array('github.com'),
  47. 'bitbucket-expose-hostname' => true,
  48. 'disable-tls' => false,
  49. 'secure-http' => true,
  50. 'cafile' => null,
  51. 'capath' => null,
  52. 'github-expose-hostname' => true,
  53. 'gitlab-domains' => array('gitlab.com'),
  54. 'store-auths' => 'prompt',
  55. 'platform' => array(),
  56. 'archive-format' => 'tar',
  57. 'archive-dir' => '.',
  58. // valid keys without defaults (auth config stuff):
  59. // bitbucket-oauth
  60. // github-oauth
  61. // gitlab-oauth
  62. // gitlab-token
  63. // http-basic
  64. );
  65. public static $defaultRepositories = array(
  66. 'packagist.org' => array(
  67. 'type' => 'composer',
  68. 'url' => 'https?://packagist.org',
  69. 'allow_ssl_downgrade' => true,
  70. ),
  71. );
  72. private $config;
  73. private $baseDir;
  74. private $repositories;
  75. private $configSource;
  76. private $authConfigSource;
  77. private $useEnvironment;
  78. private $warnedHosts = array();
  79. /**
  80. * @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings
  81. * @param string $baseDir Optional base directory of the config
  82. */
  83. public function __construct($useEnvironment = true, $baseDir = null)
  84. {
  85. // load defaults
  86. $this->config = static::$defaultConfig;
  87. $this->repositories = static::$defaultRepositories;
  88. $this->useEnvironment = (bool) $useEnvironment;
  89. $this->baseDir = $baseDir;
  90. }
  91. public function setConfigSource(ConfigSourceInterface $source)
  92. {
  93. $this->configSource = $source;
  94. }
  95. public function getConfigSource()
  96. {
  97. return $this->configSource;
  98. }
  99. public function setAuthConfigSource(ConfigSourceInterface $source)
  100. {
  101. $this->authConfigSource = $source;
  102. }
  103. public function getAuthConfigSource()
  104. {
  105. return $this->authConfigSource;
  106. }
  107. /**
  108. * Merges new config values with the existing ones (overriding)
  109. *
  110. * @param array $config
  111. */
  112. public function merge($config)
  113. {
  114. // override defaults with given config
  115. if (!empty($config['config']) && is_array($config['config'])) {
  116. foreach ($config['config'] as $key => $val) {
  117. if (in_array($key, array('bitbucket-oauth', 'github-oauth', 'gitlab-oauth', 'gitlab-token', 'http-basic')) && isset($this->config[$key])) {
  118. $this->config[$key] = array_merge($this->config[$key], $val);
  119. } elseif ('preferred-install' === $key && isset($this->config[$key])) {
  120. if (is_array($val) || is_array($this->config[$key])) {
  121. if (is_string($val)) {
  122. $val = array('*' => $val);
  123. }
  124. if (is_string($this->config[$key])) {
  125. $this->config[$key] = array('*' => $this->config[$key]);
  126. }
  127. $this->config[$key] = array_merge($this->config[$key], $val);
  128. // the full match pattern needs to be last
  129. if (isset($this->config[$key]['*'])) {
  130. $wildcard = $this->config[$key]['*'];
  131. unset($this->config[$key]['*']);
  132. $this->config[$key]['*'] = $wildcard;
  133. }
  134. } else {
  135. $this->config[$key] = $val;
  136. }
  137. } else {
  138. $this->config[$key] = $val;
  139. }
  140. }
  141. }
  142. if (!empty($config['repositories']) && is_array($config['repositories'])) {
  143. $this->repositories = array_reverse($this->repositories, true);
  144. $newRepos = array_reverse($config['repositories'], true);
  145. foreach ($newRepos as $name => $repository) {
  146. // disable a repository by name
  147. if (false === $repository) {
  148. $this->disableRepoByName($name);
  149. continue;
  150. }
  151. // disable a repository with an anonymous {"name": false} repo
  152. if (is_array($repository) && 1 === count($repository) && false === current($repository)) {
  153. $this->disableRepoByName(key($repository));
  154. continue;
  155. }
  156. // store repo
  157. if (is_int($name)) {
  158. $this->repositories[] = $repository;
  159. } else {
  160. if ($name === 'packagist') { // BC support for default "packagist" named repo
  161. $this->repositories[$name . '.org'] = $repository;
  162. } else {
  163. $this->repositories[$name] = $repository;
  164. }
  165. }
  166. }
  167. $this->repositories = array_reverse($this->repositories, true);
  168. }
  169. }
  170. /**
  171. * @return array
  172. */
  173. public function getRepositories()
  174. {
  175. return $this->repositories;
  176. }
  177. /**
  178. * Returns a setting
  179. *
  180. * @param string $key
  181. * @param int $flags Options (see class constants)
  182. * @throws \RuntimeException
  183. * @return mixed
  184. */
  185. public function get($key, $flags = 0)
  186. {
  187. switch ($key) {
  188. case 'vendor-dir':
  189. case 'bin-dir':
  190. case 'process-timeout':
  191. case 'data-dir':
  192. case 'cache-dir':
  193. case 'cache-files-dir':
  194. case 'cache-repo-dir':
  195. case 'cache-vcs-dir':
  196. case 'cafile':
  197. case 'capath':
  198. // convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
  199. $env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
  200. $val = $this->getComposerEnv($env);
  201. $val = rtrim($this->process(false !== $val ? $val : $this->config[$key], $flags), '/\\');
  202. $val = Platform::expandPath($val);
  203. if (substr($key, -4) !== '-dir') {
  204. return $val;
  205. }
  206. return (($flags & self::RELATIVE_PATHS) == self::RELATIVE_PATHS) ? $val : $this->realpath($val);
  207. case 'cache-ttl':
  208. return (int) $this->config[$key];
  209. case 'cache-files-maxsize':
  210. if (!preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $this->config[$key], $matches)) {
  211. throw new \RuntimeException(
  212. "Could not parse the value of 'cache-files-maxsize': {$this->config[$key]}"
  213. );
  214. }
  215. $size = $matches[1];
  216. if (isset($matches[2])) {
  217. switch (strtolower($matches[2])) {
  218. case 'g':
  219. $size *= 1024;
  220. // intentional fallthrough
  221. case 'm':
  222. $size *= 1024;
  223. // intentional fallthrough
  224. case 'k':
  225. $size *= 1024;
  226. break;
  227. }
  228. }
  229. return $size;
  230. case 'cache-files-ttl':
  231. if (isset($this->config[$key])) {
  232. return (int) $this->config[$key];
  233. }
  234. return (int) $this->config['cache-ttl'];
  235. case 'home':
  236. $val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $this->config[$key]);
  237. return rtrim($this->process($val, $flags), '/\\');
  238. case 'bin-compat':
  239. $value = $this->getComposerEnv('COMPOSER_BIN_COMPAT') ?: $this->config[$key];
  240. if (!in_array($value, array('auto', 'full'))) {
  241. throw new \RuntimeException(
  242. "Invalid value for 'bin-compat': {$value}. Expected auto, full"
  243. );
  244. }
  245. return $value;
  246. case 'discard-changes':
  247. if ($env = $this->getComposerEnv('COMPOSER_DISCARD_CHANGES')) {
  248. if (!in_array($env, array('stash', 'true', 'false', '1', '0'), true)) {
  249. throw new \RuntimeException(
  250. "Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash"
  251. );
  252. }
  253. if ('stash' === $env) {
  254. return 'stash';
  255. }
  256. // convert string value to bool
  257. return $env !== 'false' && (bool) $env;
  258. }
  259. if (!in_array($this->config[$key], array(true, false, 'stash'), true)) {
  260. throw new \RuntimeException(
  261. "Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash"
  262. );
  263. }
  264. return $this->config[$key];
  265. case 'github-protocols':
  266. $protos = $this->config['github-protocols'];
  267. if ($this->config['secure-http'] && false !== ($index = array_search('git', $protos))) {
  268. unset($protos[$index]);
  269. }
  270. if (reset($protos) === 'http') {
  271. throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"');
  272. }
  273. return $protos;
  274. case 'disable-tls':
  275. return $this->config[$key] !== 'false' && (bool) $this->config[$key];
  276. case 'secure-http':
  277. return $this->config[$key] !== 'false' && (bool) $this->config[$key];
  278. default:
  279. if (!isset($this->config[$key])) {
  280. return null;
  281. }
  282. return $this->process($this->config[$key], $flags);
  283. }
  284. }
  285. public function all($flags = 0)
  286. {
  287. $all = array(
  288. 'repositories' => $this->getRepositories(),
  289. );
  290. foreach (array_keys($this->config) as $key) {
  291. $all['config'][$key] = $this->get($key, $flags);
  292. }
  293. return $all;
  294. }
  295. public function raw()
  296. {
  297. return array(
  298. 'repositories' => $this->getRepositories(),
  299. 'config' => $this->config,
  300. );
  301. }
  302. /**
  303. * Checks whether a setting exists
  304. *
  305. * @param string $key
  306. * @return bool
  307. */
  308. public function has($key)
  309. {
  310. return array_key_exists($key, $this->config);
  311. }
  312. /**
  313. * Replaces {$refs} inside a config string
  314. *
  315. * @param string $value a config string that can contain {$refs-to-other-config}
  316. * @param int $flags Options (see class constants)
  317. * @return string
  318. */
  319. private function process($value, $flags)
  320. {
  321. $config = $this;
  322. if (!is_string($value)) {
  323. return $value;
  324. }
  325. return preg_replace_callback('#\{\$(.+)\}#', function ($match) use ($config, $flags) {
  326. return $config->get($match[1], $flags);
  327. }, $value);
  328. }
  329. /**
  330. * Turns relative paths in absolute paths without realpath()
  331. *
  332. * Since the dirs might not exist yet we can not call realpath or it will fail.
  333. *
  334. * @param string $path
  335. * @return string
  336. */
  337. private function realpath($path)
  338. {
  339. if (preg_match('{^(?:/|[a-z]:|[a-z0-9.]+://)}i', $path)) {
  340. return $path;
  341. }
  342. return $this->baseDir . '/' . $path;
  343. }
  344. /**
  345. * Reads the value of a Composer environment variable
  346. *
  347. * This should be used to read COMPOSER_ environment variables
  348. * that overload config values.
  349. *
  350. * @param string $var
  351. * @return string|bool
  352. */
  353. private function getComposerEnv($var)
  354. {
  355. if ($this->useEnvironment) {
  356. return getenv($var);
  357. }
  358. return false;
  359. }
  360. private function disableRepoByName($name)
  361. {
  362. if (isset($this->repositories[$name])) {
  363. unset($this->repositories[$name]);
  364. } else if ($name === 'packagist') { // BC support for default "packagist" named repo
  365. unset($this->repositories['packagist.org']);
  366. }
  367. }
  368. /**
  369. * Validates that the passed URL is allowed to be used by current config, or throws an exception.
  370. *
  371. * @param string $url
  372. * @param IOInterface $io
  373. */
  374. public function prohibitUrlByConfig($url, IOInterface $io = null)
  375. {
  376. // Return right away if the URL is malformed or custom (see issue #5173)
  377. if (false === filter_var($url, FILTER_VALIDATE_URL)) {
  378. return;
  379. }
  380. // Extract scheme and throw exception on known insecure protocols
  381. $scheme = parse_url($url, PHP_URL_SCHEME);
  382. if (in_array($scheme, array('http', 'git', 'ftp', 'svn'))) {
  383. if ($this->get('secure-http')) {
  384. throw new TransportException("Your configuration does not allow connections to $url. See https://getcomposer.org/doc/06-config.md#secure-http for details.");
  385. } elseif ($io) {
  386. $host = parse_url($url, PHP_URL_HOST);
  387. if (!isset($this->warnedHosts[$host])) {
  388. $io->writeError("<warning>Warning: Accessing $host over $scheme which is an insecure protocol.</warning>");
  389. }
  390. $this->warnedHosts[$host] = true;
  391. }
  392. }
  393. }
  394. }