Factory.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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. $rfs = Factory::createRemoteFilesystem($io);
  186. if (is_string($localConfig)) {
  187. $composerFile = $localConfig;
  188. $rfs = Factory::createRemoteFilesystem($io);
  189. $file = new JsonFile($localConfig, $rfs);
  190. if (!$file->exists()) {
  191. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  192. $message = 'Composer could not find a composer.json file in '.$cwd;
  193. } else {
  194. $message = 'Composer could not find the config file: '.$localConfig;
  195. }
  196. $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section';
  197. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  198. }
  199. $file->validateSchema(JsonFile::LAX_SCHEMA);
  200. $jsonParser = new JsonParser;
  201. try {
  202. $jsonParser->parse(file_get_contents($localConfig), JsonParser::DETECT_KEY_CONFLICTS);
  203. } catch (\Seld\JsonLint\DuplicateKeyException $e) {
  204. $details = $e->getDetails();
  205. $io->writeError('<warning>Key '.$details['key'].' is a duplicate in '.$localConfig.' at line '.$details['line'].'</warning>');
  206. }
  207. $localConfig = $file->read();
  208. }
  209. // Load config and override with local config/auth config
  210. $config = static::createConfig($io, $cwd);
  211. $config->merge($localConfig);
  212. if (isset($composerFile)) {
  213. if ($io && $io->isDebug()) {
  214. $io->writeError('Loading config file ' . $composerFile);
  215. }
  216. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  217. if ($localAuthFile->exists()) {
  218. if ($io && $io->isDebug()) {
  219. $io->writeError('Loading config file ' . $localAuthFile->getPath());
  220. }
  221. $config->merge(array('config' => $localAuthFile->read()));
  222. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  223. }
  224. }
  225. $vendorDir = $config->get('vendor-dir');
  226. $binDir = $config->get('bin-dir');
  227. // initialize composer
  228. $composer = new Composer();
  229. $composer->setConfig($config);
  230. if ($fullLoad) {
  231. // load auth configs into the IO instance
  232. $io->loadConfiguration($config);
  233. }
  234. // initialize event dispatcher
  235. $dispatcher = new EventDispatcher($composer, $io);
  236. $composer->setEventDispatcher($dispatcher);
  237. // initialize repository manager
  238. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  239. $composer->setRepositoryManager($rm);
  240. // load local repository
  241. $this->addLocalRepository($rm, $vendorDir);
  242. // force-set the version of the global package if not defined as
  243. // guessing it adds no value and only takes time
  244. if (!$fullLoad && !isset($localConfig['version'])) {
  245. $localConfig['version'] = '1.0.0';
  246. }
  247. // load package
  248. $parser = new VersionParser;
  249. $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser);
  250. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser);
  251. $package = $loader->load($localConfig, 'Composer\Package\RootPackage', $cwd);
  252. $composer->setPackage($package);
  253. // initialize installation manager
  254. $im = $this->createInstallationManager();
  255. $composer->setInstallationManager($im);
  256. if ($fullLoad) {
  257. // initialize download manager
  258. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  259. $composer->setDownloadManager($dm);
  260. // initialize autoload generator
  261. $generator = new AutoloadGenerator($dispatcher, $io);
  262. $composer->setAutoloadGenerator($generator);
  263. }
  264. // add installers to the manager (must happen after download manager is created since they read it out of $composer)
  265. $this->createDefaultInstallers($im, $composer, $io);
  266. if ($fullLoad) {
  267. $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins);
  268. $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins);
  269. $composer->setPluginManager($pm);
  270. $pm->loadInstalledPlugins();
  271. // once we have plugins and custom installers we can
  272. // purge packages from local repos if they have been deleted on the filesystem
  273. if ($rm->getLocalRepository()) {
  274. $this->purgePackages($rm->getLocalRepository(), $im);
  275. }
  276. }
  277. // init locker if possible
  278. if ($fullLoad && isset($composerFile)) {
  279. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  280. ? substr($composerFile, 0, -4).'lock'
  281. : $composerFile . '.lock';
  282. $locker = new Package\Locker($io, new JsonFile($lockFile, $rfs), $rm, $im, file_get_contents($composerFile));
  283. $composer->setLocker($locker);
  284. }
  285. return $composer;
  286. }
  287. /**
  288. * @param IOInterface $io
  289. * @param Config $config
  290. * @param EventDispatcher $eventDispatcher
  291. * @return Repository\RepositoryManager
  292. */
  293. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  294. {
  295. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  296. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  297. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  298. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  299. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  300. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  301. $rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository');
  302. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  303. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  304. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  305. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  306. $rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
  307. return $rm;
  308. }
  309. /**
  310. * @param Repository\RepositoryManager $rm
  311. * @param string $vendorDir
  312. */
  313. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  314. {
  315. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  316. }
  317. /**
  318. * @param Config $config
  319. * @return Composer|null
  320. */
  321. protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins)
  322. {
  323. if (realpath($config->get('home')) === getcwd()) {
  324. return;
  325. }
  326. $composer = null;
  327. try {
  328. $composer = self::createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), false);
  329. } catch (\Exception $e) {
  330. if ($io->isDebug()) {
  331. $io->writeError('Failed to initialize global composer: '.$e->getMessage());
  332. }
  333. }
  334. return $composer;
  335. }
  336. /**
  337. * @param IO\IOInterface $io
  338. * @param Config $config
  339. * @param EventDispatcher $eventDispatcher
  340. * @return Downloader\DownloadManager
  341. */
  342. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  343. {
  344. $cache = null;
  345. if ($config->get('cache-files-ttl') > 0) {
  346. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  347. }
  348. $dm = new Downloader\DownloadManager($io);
  349. switch ($config->get('preferred-install')) {
  350. case 'dist':
  351. $dm->setPreferDist(true);
  352. break;
  353. case 'source':
  354. $dm->setPreferSource(true);
  355. break;
  356. case 'auto':
  357. default:
  358. // noop
  359. break;
  360. }
  361. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  362. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  363. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  364. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  365. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  366. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  367. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  368. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  369. $dm->setDownloader('xz', new Downloader\XzDownloader($io, $config, $eventDispatcher, $cache));
  370. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  371. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  372. $dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $eventDispatcher, $cache));
  373. return $dm;
  374. }
  375. /**
  376. * @param Config $config The configuration
  377. * @param Downloader\DownloadManager $dm Manager use to download sources
  378. * @return Archiver\ArchiveManager
  379. */
  380. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  381. {
  382. if (null === $dm) {
  383. $io = new IO\NullIO();
  384. $io->loadConfiguration($config);
  385. $dm = $this->createDownloadManager($io, $config);
  386. }
  387. $am = new Archiver\ArchiveManager($dm);
  388. $am->addArchiver(new Archiver\PharArchiver);
  389. return $am;
  390. }
  391. /**
  392. * @param IOInterface $io
  393. * @param Composer $composer
  394. * @param Composer $globalComposer
  395. * @param bool $disablePlugins
  396. * @return Plugin\PluginManager
  397. */
  398. protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
  399. {
  400. return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
  401. }
  402. /**
  403. * @return Installer\InstallationManager
  404. */
  405. protected function createInstallationManager()
  406. {
  407. return new Installer\InstallationManager();
  408. }
  409. /**
  410. * @param Installer\InstallationManager $im
  411. * @param Composer $composer
  412. * @param IO\IOInterface $io
  413. */
  414. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  415. {
  416. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  417. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  418. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  419. $im->addInstaller(new Installer\MetapackageInstaller($io));
  420. }
  421. /**
  422. * @param WritableRepositoryInterface $repo repository to purge packages from
  423. * @param Installer\InstallationManager $im manager to check whether packages are still installed
  424. */
  425. protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im)
  426. {
  427. foreach ($repo->getPackages() as $package) {
  428. if (!$im->isPackageInstalled($repo, $package)) {
  429. $repo->removePackage($package);
  430. }
  431. }
  432. }
  433. /**
  434. * @param IOInterface $io IO instance
  435. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  436. * the default filename
  437. * @param bool $disablePlugins Whether plugins should not be loaded
  438. * @return Composer
  439. */
  440. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  441. {
  442. $factory = new static();
  443. return $factory->createComposer($io, $config, $disablePlugins);
  444. }
  445. /**
  446. * @param IOInterface $io IO instance
  447. * @param Config $config Config instance
  448. * @param array $options Array of options passed directly to RemoteFilesystem constructor
  449. * @return RemoteFilesystem
  450. */
  451. public static function createRemoteFilesystem(IOInterface $io, Config $config = null, $options = array())
  452. {
  453. $disableTls = false;
  454. if (isset($config) && $config->get('disable-tls') === true) {
  455. $io->write('<warning>You are running Composer with SSL/TLS protection disabled.</warning>');
  456. $disableTls = true;
  457. } elseif (!extension_loaded('openssl')) {
  458. throw new \RuntimeException('The openssl extension is required for SSL/TLS protection but is not available. '
  459. . '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.');
  460. }
  461. $remoteFilesystemOptions = array();
  462. if ($disableTls === false) {
  463. if (isset($config) && !empty($config->get('cafile'))) {
  464. $remoteFilesystemOptions = array('ssl' => array('cafile' => $config->get('cafile')));
  465. }
  466. $remoteFilesystemOptions = array_merge_recursive($remoteFilesystemOptions, $options);
  467. }
  468. try {
  469. $remoteFilesystem = new RemoteFilesystem($io, $config, $remoteFilesystemOptions, $disableTls);
  470. } catch (TransportException $e) {
  471. if (preg_match('{cafile}', $e->getMessage())) {
  472. $io->write('<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>');
  473. $io->write('<error>A valid CA certificate file is required for SSL/TLS protection.</error>');
  474. if (PHP_VERSION_ID < 50600) {
  475. $io->write('<error>It is recommended you upgrade to PHP 5.6+ which can detect your system CA file automatically.</error>');
  476. }
  477. $io->write('<error>You can disable this error, at your own risk, by setting the \'disable-tls\' option to true.</error>');
  478. }
  479. throw $e;
  480. }
  481. return $remoteFilesystem;
  482. }
  483. }