Factory.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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\JsonConfigSource;
  13. use Composer\Json\JsonFile;
  14. use Composer\IO\IOInterface;
  15. use Composer\Package\Archiver;
  16. use Composer\Package\Version\VersionGuesser;
  17. use Composer\Repository\RepositoryManager;
  18. use Composer\Repository\WritableRepositoryInterface;
  19. use Composer\Util\ProcessExecutor;
  20. use Composer\Util\RemoteFilesystem;
  21. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  22. use Composer\EventDispatcher\EventDispatcher;
  23. use Composer\Autoload\AutoloadGenerator;
  24. use Composer\Semver\VersionParser;
  25. use Composer\Downloader\TransportException;
  26. use Seld\JsonLint\JsonParser;
  27. /**
  28. * Creates a configured instance of composer.
  29. *
  30. * @author Ryan Weaver <ryan@knplabs.com>
  31. * @author Jordi Boggiano <j.boggiano@seld.be>
  32. * @author Igor Wiedler <igor@wiedler.ch>
  33. * @author Nils Adermann <naderman@naderman.de>
  34. */
  35. class Factory
  36. {
  37. /**
  38. * @throws \RuntimeException
  39. * @return string
  40. */
  41. protected static function getHomeDir()
  42. {
  43. $home = getenv('COMPOSER_HOME');
  44. if (!$home) {
  45. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  46. if (!getenv('APPDATA')) {
  47. throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
  48. }
  49. $home = strtr(getenv('APPDATA'), '\\', '/') . '/Composer';
  50. } else {
  51. if (!getenv('HOME')) {
  52. throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
  53. }
  54. $home = rtrim(getenv('HOME'), '/') . '/.composer';
  55. }
  56. }
  57. return $home;
  58. }
  59. /**
  60. * @param string $home
  61. * @return string
  62. */
  63. protected static function getCacheDir($home)
  64. {
  65. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  66. if (!$cacheDir) {
  67. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  68. if ($cacheDir = getenv('LOCALAPPDATA')) {
  69. $cacheDir .= '/Composer';
  70. } else {
  71. $cacheDir = $home . '/cache';
  72. }
  73. $cacheDir = strtr($cacheDir, '\\', '/');
  74. } else {
  75. $cacheDir = $home.'/cache';
  76. }
  77. }
  78. return $cacheDir;
  79. }
  80. /**
  81. * @param IOInterface|null $io
  82. * @return Config
  83. */
  84. public static function createConfig(IOInterface $io = null, $cwd = null)
  85. {
  86. $cwd = $cwd ?: getcwd();
  87. // determine home and cache dirs
  88. $home = self::getHomeDir();
  89. $cacheDir = self::getCacheDir($home);
  90. // Protect directory against web access. Since HOME could be
  91. // the www-data's user home and be web-accessible it is a
  92. // potential security risk
  93. foreach (array($home, $cacheDir) as $dir) {
  94. if (!file_exists($dir . '/.htaccess')) {
  95. if (!is_dir($dir)) {
  96. @mkdir($dir, 0777, true);
  97. }
  98. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  99. }
  100. }
  101. $config = new Config(true, $cwd);
  102. // add dirs to the config
  103. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  104. // load global config
  105. $file = new JsonFile($config->get('home').'/config.json');
  106. if ($file->exists()) {
  107. if ($io && $io->isDebug()) {
  108. $io->writeError('Loading config file ' . $file->getPath());
  109. }
  110. $config->merge($file->read());
  111. }
  112. $config->setConfigSource(new JsonConfigSource($file));
  113. // load global auth file
  114. $file = new JsonFile($config->get('home').'/auth.json');
  115. if ($file->exists()) {
  116. if ($io && $io->isDebug()) {
  117. $io->writeError('Loading config file ' . $file->getPath());
  118. }
  119. $config->merge(array('config' => $file->read()));
  120. }
  121. $config->setAuthConfigSource(new JsonConfigSource($file, true));
  122. return $config;
  123. }
  124. public static function getComposerFile()
  125. {
  126. return trim(getenv('COMPOSER')) ?: './composer.json';
  127. }
  128. public static function createAdditionalStyles()
  129. {
  130. return array(
  131. 'highlight' => new OutputFormatterStyle('red'),
  132. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  133. );
  134. }
  135. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  136. {
  137. $repos = array();
  138. if (!$config) {
  139. $config = static::createConfig($io);
  140. }
  141. if (!$rm) {
  142. if (!$io) {
  143. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  144. }
  145. $factory = new static;
  146. $rm = $factory->createRepositoryManager($io, $config);
  147. }
  148. foreach ($config->getRepositories() as $index => $repo) {
  149. if (is_string($repo)) {
  150. throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given');
  151. }
  152. if (!is_array($repo)) {
  153. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  154. }
  155. if (!isset($repo['type'])) {
  156. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined');
  157. }
  158. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  159. while (isset($repos[$name])) {
  160. $name .= '2';
  161. }
  162. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  163. }
  164. return $repos;
  165. }
  166. /**
  167. * Creates a Composer instance
  168. *
  169. * @param IOInterface $io IO instance
  170. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  171. * read from the default filename
  172. * @param bool $disablePlugins Whether plugins should not be loaded
  173. * @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer)
  174. * @throws \InvalidArgumentException
  175. * @throws \UnexpectedValueException
  176. * @return Composer
  177. */
  178. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true)
  179. {
  180. $cwd = $cwd ?: getcwd();
  181. // load Composer configuration
  182. if (null === $localConfig) {
  183. $localConfig = static::getComposerFile();
  184. }
  185. if (is_string($localConfig)) {
  186. $composerFile = $localConfig;
  187. $file = new JsonFile($localConfig, null, $io);
  188. if (!$file->exists()) {
  189. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  190. $message = 'Composer could not find a composer.json file in '.$cwd;
  191. } else {
  192. $message = 'Composer could not find the config file: '.$localConfig;
  193. }
  194. $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section';
  195. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  196. }
  197. $file->validateSchema(JsonFile::LAX_SCHEMA);
  198. $jsonParser = new JsonParser;
  199. try {
  200. $jsonParser->parse(file_get_contents($localConfig), JsonParser::DETECT_KEY_CONFLICTS);
  201. } catch (\Seld\JsonLint\DuplicateKeyException $e) {
  202. $details = $e->getDetails();
  203. $io->writeError('<warning>Key '.$details['key'].' is a duplicate in '.$localConfig.' at line '.$details['line'].'</warning>');
  204. }
  205. $localConfig = $file->read();
  206. }
  207. // Load config and override with local config/auth config
  208. $config = static::createConfig($io, $cwd);
  209. $config->merge($localConfig);
  210. if (isset($composerFile)) {
  211. if ($io && $io->isDebug()) {
  212. $io->writeError('Loading config file ' . $composerFile);
  213. }
  214. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  215. if ($localAuthFile->exists()) {
  216. if ($io && $io->isDebug()) {
  217. $io->writeError('Loading config file ' . $localAuthFile->getPath());
  218. }
  219. $config->merge(array('config' => $localAuthFile->read()));
  220. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  221. }
  222. }
  223. $vendorDir = $config->get('vendor-dir');
  224. $binDir = $config->get('bin-dir');
  225. // initialize composer
  226. $composer = new Composer();
  227. $composer->setConfig($config);
  228. if ($fullLoad) {
  229. // load auth configs into the IO instance
  230. $io->loadConfiguration($config);
  231. }
  232. // initialize event dispatcher
  233. $dispatcher = new EventDispatcher($composer, $io);
  234. $composer->setEventDispatcher($dispatcher);
  235. // initialize repository manager
  236. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  237. $composer->setRepositoryManager($rm);
  238. // load local repository
  239. $this->addLocalRepository($io, $rm, $vendorDir);
  240. // force-set the version of the global package if not defined as
  241. // guessing it adds no value and only takes time
  242. if (!$fullLoad && !isset($localConfig['version'])) {
  243. $localConfig['version'] = '1.0.0';
  244. }
  245. // load package
  246. $parser = new VersionParser;
  247. $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser);
  248. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser);
  249. $package = $loader->load($localConfig, 'Composer\Package\RootPackage', $cwd);
  250. $composer->setPackage($package);
  251. // initialize installation manager
  252. $im = $this->createInstallationManager();
  253. $composer->setInstallationManager($im);
  254. if ($fullLoad) {
  255. // initialize download manager
  256. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  257. $composer->setDownloadManager($dm);
  258. // initialize autoload generator
  259. $generator = new AutoloadGenerator($dispatcher, $io);
  260. $composer->setAutoloadGenerator($generator);
  261. }
  262. // add installers to the manager (must happen after download manager is created since they read it out of $composer)
  263. $this->createDefaultInstallers($im, $composer, $io);
  264. if ($fullLoad) {
  265. $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins);
  266. $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins);
  267. $composer->setPluginManager($pm);
  268. $pm->loadInstalledPlugins();
  269. // once we have plugins and custom installers we can
  270. // purge packages from local repos if they have been deleted on the filesystem
  271. if ($rm->getLocalRepository()) {
  272. $this->purgePackages($rm->getLocalRepository(), $im);
  273. }
  274. }
  275. // init locker if possible
  276. if ($fullLoad && isset($composerFile)) {
  277. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  278. ? substr($composerFile, 0, -4).'lock'
  279. : $composerFile . '.lock';
  280. $locker = new Package\Locker($io, new JsonFile($lockFile, null, $io), $rm, $im, file_get_contents($composerFile));
  281. $composer->setLocker($locker);
  282. }
  283. return $composer;
  284. }
  285. /**
  286. * @param IOInterface $io
  287. * @param Config $config
  288. * @param EventDispatcher $eventDispatcher
  289. * @return Repository\RepositoryManager
  290. */
  291. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  292. {
  293. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  294. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  295. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  296. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  297. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  298. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  299. $rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository');
  300. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  301. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  302. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  303. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  304. $rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
  305. return $rm;
  306. }
  307. /**
  308. * @param Repository\RepositoryManager $rm
  309. * @param string $vendorDir
  310. */
  311. protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, $vendorDir)
  312. {
  313. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json', null, $io)));
  314. }
  315. /**
  316. * @param Config $config
  317. * @return Composer|null
  318. */
  319. protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins)
  320. {
  321. if (realpath($config->get('home')) === getcwd()) {
  322. return;
  323. }
  324. $composer = null;
  325. try {
  326. $composer = self::createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), false);
  327. } catch (\Exception $e) {
  328. if ($io->isDebug()) {
  329. $io->writeError('Failed to initialize global composer: '.$e->getMessage());
  330. }
  331. }
  332. return $composer;
  333. }
  334. /**
  335. * @param IO\IOInterface $io
  336. * @param Config $config
  337. * @param EventDispatcher $eventDispatcher
  338. * @return Downloader\DownloadManager
  339. */
  340. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  341. {
  342. $cache = null;
  343. if ($config->get('cache-files-ttl') > 0) {
  344. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  345. }
  346. $dm = new Downloader\DownloadManager($io);
  347. switch ($config->get('preferred-install')) {
  348. case 'dist':
  349. $dm->setPreferDist(true);
  350. break;
  351. case 'source':
  352. $dm->setPreferSource(true);
  353. break;
  354. case 'auto':
  355. default:
  356. // noop
  357. break;
  358. }
  359. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  360. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  361. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  362. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  363. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  364. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  365. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  366. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  367. $dm->setDownloader('xz', new Downloader\XzDownloader($io, $config, $eventDispatcher, $cache));
  368. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  369. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  370. $dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $eventDispatcher, $cache));
  371. return $dm;
  372. }
  373. /**
  374. * @param Config $config The configuration
  375. * @param Downloader\DownloadManager $dm Manager use to download sources
  376. * @return Archiver\ArchiveManager
  377. */
  378. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  379. {
  380. if (null === $dm) {
  381. $io = new IO\NullIO();
  382. $io->loadConfiguration($config);
  383. $dm = $this->createDownloadManager($io, $config);
  384. }
  385. $am = new Archiver\ArchiveManager($dm);
  386. $am->addArchiver(new Archiver\PharArchiver);
  387. return $am;
  388. }
  389. /**
  390. * @param IOInterface $io
  391. * @param Composer $composer
  392. * @param Composer $globalComposer
  393. * @param bool $disablePlugins
  394. * @return Plugin\PluginManager
  395. */
  396. protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
  397. {
  398. return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
  399. }
  400. /**
  401. * @return Installer\InstallationManager
  402. */
  403. protected function createInstallationManager()
  404. {
  405. return new Installer\InstallationManager();
  406. }
  407. /**
  408. * @param Installer\InstallationManager $im
  409. * @param Composer $composer
  410. * @param IO\IOInterface $io
  411. */
  412. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  413. {
  414. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  415. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  416. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  417. $im->addInstaller(new Installer\MetapackageInstaller($io));
  418. }
  419. /**
  420. * @param WritableRepositoryInterface $repo repository to purge packages from
  421. * @param Installer\InstallationManager $im manager to check whether packages are still installed
  422. */
  423. protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im)
  424. {
  425. foreach ($repo->getPackages() as $package) {
  426. if (!$im->isPackageInstalled($repo, $package)) {
  427. $repo->removePackage($package);
  428. }
  429. }
  430. }
  431. /**
  432. * @param IOInterface $io IO instance
  433. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  434. * the default filename
  435. * @param bool $disablePlugins Whether plugins should not be loaded
  436. * @return Composer
  437. */
  438. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  439. {
  440. $factory = new static();
  441. return $factory->createComposer($io, $config, $disablePlugins);
  442. }
  443. /**
  444. * @param IOInterface $io IO instance
  445. * @param Config $config Config instance
  446. * @param array $options Array of options passed directly to RemoteFilesystem constructor
  447. * @return RemoteFilesystem
  448. */
  449. public static function createRemoteFilesystem(IOInterface $io, Config $config = null, $options = array())
  450. {
  451. $disableTls = false;
  452. if (isset($config) && $config->get('disable-tls') === true) {
  453. $io->write('<warning>You are running Composer with SSL/TLS protection disabled.</warning>');
  454. $disableTls = true;
  455. } elseif (!extension_loaded('openssl')) {
  456. throw new \RuntimeException('The openssl extension is required for SSL/TLS protection but is not available. '
  457. . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.');
  458. }
  459. $remoteFilesystemOptions = array();
  460. if ($disableTls === false) {
  461. if (isset($config) && !empty($config->get('cafile'))) {
  462. $remoteFilesystemOptions = array('ssl' => array('cafile' => $config->get('cafile')));
  463. }
  464. $remoteFilesystemOptions = array_merge_recursive($remoteFilesystemOptions, $options);
  465. }
  466. try {
  467. $remoteFilesystem = new RemoteFilesystem($io, $config, $remoteFilesystemOptions, $disableTls);
  468. } catch (TransportException $e) {
  469. if (preg_match('{cafile}', $e->getMessage())) {
  470. $io->write('<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>');
  471. $io->write('<error>A valid CA certificate file is required for SSL/TLS protection.</error>');
  472. if (PHP_VERSION_ID < 50600) {
  473. $io->write('<error>It is recommended you upgrade to PHP 5.6+ which can detect your system CA file automatically.</error>');
  474. }
  475. $io->write('<error>You can disable this error, at your own risk, by setting the \'disable-tls\' option to true.</error>');
  476. }
  477. throw $e;
  478. }
  479. return $remoteFilesystem;
  480. }
  481. }