Config.php 16 KB

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