Config.php 16 KB

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