Config.php 14 KB

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