PageRenderTime 31ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Atomic Projects/vendor/composer/composer/src/Composer/Util/Git.php

https://gitlab.com/imamul68e/137619_PHP31
PHP | 329 lines | 243 code | 51 blank | 35 comment | 54 complexity | 678c0d7a867975317f13a86ab167831c MD5 | raw file
  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\Util;
  12. use Composer\Config;
  13. use Composer\IO\IOInterface;
  14. /**
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. */
  17. class Git
  18. {
  19. private static $version;
  20. /** @var IOInterface */
  21. protected $io;
  22. /** @var Config */
  23. protected $config;
  24. /** @var ProcessExecutor */
  25. protected $process;
  26. /** @var Filesystem */
  27. protected $filesystem;
  28. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process, Filesystem $fs)
  29. {
  30. $this->io = $io;
  31. $this->config = $config;
  32. $this->process = $process;
  33. $this->filesystem = $fs;
  34. }
  35. public function runCommand($commandCallable, $url, $cwd, $initialClone = false)
  36. {
  37. // Ensure we are allowed to use this URL by config
  38. $this->config->prohibitUrlByConfig($url, $this->io);
  39. if ($initialClone) {
  40. $origCwd = $cwd;
  41. $cwd = null;
  42. }
  43. if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) {
  44. throw new \InvalidArgumentException('The source URL '.$url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
  45. }
  46. if (!$initialClone) {
  47. // capture username/password from URL if there is one
  48. $this->process->execute('git remote -v', $output, $cwd);
  49. if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match)) {
  50. $this->io->setAuthentication($match[3], urldecode($match[1]), urldecode($match[2]));
  51. }
  52. }
  53. $protocols = $this->config->get('github-protocols');
  54. if (!is_array($protocols)) {
  55. throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
  56. }
  57. // public github, autoswitch protocols
  58. if (preg_match('{^(?:https?|git)://'.self::getGitHubDomainsRegex($this->config).'/(.*)}', $url, $match)) {
  59. $messages = array();
  60. foreach ($protocols as $protocol) {
  61. if ('ssh' === $protocol) {
  62. $protoUrl = "git@" . $match[1] . ":" . $match[2];
  63. } else {
  64. $protoUrl = $protocol ."://" . $match[1] . "/" . $match[2];
  65. }
  66. if (0 === $this->process->execute(call_user_func($commandCallable, $protoUrl), $ignoredOutput, $cwd)) {
  67. return;
  68. }
  69. $messages[] = '- ' . $protoUrl . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
  70. if ($initialClone) {
  71. $this->filesystem->removeDirectory($origCwd);
  72. }
  73. }
  74. // failed to checkout, first check git accessibility
  75. $this->throwException('Failed to clone ' . $url .' via '.implode(', ', $protocols).' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
  76. }
  77. // if we have a private github url and the ssh protocol is disabled then we skip it and directly fallback to https
  78. $bypassSshForGitHub = preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true);
  79. $command = call_user_func($commandCallable, $url);
  80. $auth = null;
  81. if ($bypassSshForGitHub || 0 !== $this->process->execute($command, $ignoredOutput, $cwd)) {
  82. // private github repository without git access, try https with auth
  83. if (preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url, $match)) {
  84. if (!$this->io->hasAuthentication($match[1])) {
  85. $gitHubUtil = new GitHub($this->io, $this->config, $this->process);
  86. $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
  87. if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  88. $gitHubUtil->authorizeOAuthInteractively($match[1], $message);
  89. }
  90. }
  91. if ($this->io->hasAuthentication($match[1])) {
  92. $auth = $this->io->getAuthentication($match[1]);
  93. $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git';
  94. $command = call_user_func($commandCallable, $authUrl);
  95. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  96. return;
  97. }
  98. }
  99. } elseif (preg_match('{^https://(bitbucket\.org)/(.*)(\.git)?$}U', $url, $match)) { //bitbucket oauth
  100. $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process);
  101. if (!$this->io->hasAuthentication($match[1])) {
  102. $message = 'Enter your Bitbucket credentials to access private repos';
  103. if (!$bitbucketUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  104. $bitbucketUtil->authorizeOAuthInteractively($match[1], $message);
  105. $token = $bitbucketUtil->getToken();
  106. $this->io->setAuthentication($match[1], 'x-token-auth', $token['access_token']);
  107. }
  108. } else { //We're authenticating with a locally stored consumer.
  109. $auth = $this->io->getAuthentication($match[1]);
  110. //We already have an access_token from a previous request.
  111. if ($auth['username'] !== 'x-token-auth') {
  112. $token = $bitbucketUtil->requestToken($match[1], $auth['username'], $auth['password']);
  113. if (! empty($token)) {
  114. $this->io->setAuthentication($match[1], 'x-token-auth', $token['access_token']);
  115. }
  116. }
  117. }
  118. if ($this->io->hasAuthentication($match[1])) {
  119. $auth = $this->io->getAuthentication($match[1]);
  120. $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git';
  121. $command = call_user_func($commandCallable, $authUrl);
  122. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  123. return;
  124. }
  125. } else { // Falling back to ssh
  126. $sshUrl = 'git@bitbucket.org:' . $match[2] . '.git';
  127. $this->io->writeError(' No bitbucket authentication configured. Falling back to ssh.');
  128. $command = call_user_func($commandCallable, $sshUrl);
  129. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  130. return;
  131. }
  132. }
  133. } elseif ($this->isAuthenticationFailure($url, $match)) { // private non-github repo that failed to authenticate
  134. if (strpos($match[2], '@')) {
  135. list($authParts, $match[2]) = explode('@', $match[2], 2);
  136. }
  137. $storeAuth = false;
  138. if ($this->io->hasAuthentication($match[2])) {
  139. $auth = $this->io->getAuthentication($match[2]);
  140. } elseif ($this->io->isInteractive()) {
  141. $defaultUsername = null;
  142. if (isset($authParts) && $authParts) {
  143. if (false !== strpos($authParts, ':')) {
  144. list($defaultUsername, ) = explode(':', $authParts, 2);
  145. } else {
  146. $defaultUsername = $authParts;
  147. }
  148. }
  149. $this->io->writeError(' Authentication required (<info>'.parse_url($url, PHP_URL_HOST).'</info>):');
  150. $auth = array(
  151. 'username' => $this->io->ask(' Username: ', $defaultUsername),
  152. 'password' => $this->io->askAndHideAnswer(' Password: '),
  153. );
  154. $storeAuth = $this->config->get('store-auths');
  155. }
  156. if ($auth) {
  157. $authUrl = $match[1].rawurlencode($auth['username']).':'.rawurlencode($auth['password']).'@'.$match[2].$match[3];
  158. $command = call_user_func($commandCallable, $authUrl);
  159. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  160. $this->io->setAuthentication($match[2], $auth['username'], $auth['password']);
  161. $authHelper = new AuthHelper($this->io, $this->config);
  162. $authHelper->storeAuth($match[2], $storeAuth);
  163. return;
  164. }
  165. }
  166. }
  167. if ($initialClone) {
  168. $this->filesystem->removeDirectory($origCwd);
  169. }
  170. $this->throwException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(), $url);
  171. }
  172. }
  173. public function syncMirror($url, $dir)
  174. {
  175. // update the repo if it is a valid git repository
  176. if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') {
  177. try {
  178. $commandCallable = function ($url) {
  179. return sprintf('git remote set-url origin %s && git remote update --prune origin', ProcessExecutor::escape($url));
  180. };
  181. $this->runCommand($commandCallable, $url, $dir);
  182. } catch (\Exception $e) {
  183. return false;
  184. }
  185. return true;
  186. }
  187. // clean up directory and do a fresh clone into it
  188. $this->filesystem->removeDirectory($dir);
  189. $commandCallable = function ($url) use ($dir) {
  190. return sprintf('git clone --mirror %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir));
  191. };
  192. $this->runCommand($commandCallable, $url, $dir, true);
  193. return true;
  194. }
  195. private function isAuthenticationFailure($url, &$match)
  196. {
  197. if (!preg_match('{(https?://)([^/]+)(.*)$}i', $url, $match)) {
  198. return false;
  199. }
  200. $authFailures = array(
  201. 'fatal: Authentication failed',
  202. 'remote error: Invalid username or password.',
  203. 'error: 401 Unauthorized'
  204. );
  205. foreach ($authFailures as $authFailure) {
  206. if (strpos($this->process->getErrorOutput(), $authFailure) !== false) {
  207. return true;
  208. }
  209. }
  210. return false;
  211. }
  212. public static function cleanEnv()
  213. {
  214. if (ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars'), 'GIT_ASKPASS')) {
  215. throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer');
  216. }
  217. // added in git 1.7.1, prevents prompting the user for username/password
  218. if (getenv('GIT_ASKPASS') !== 'echo') {
  219. putenv('GIT_ASKPASS=echo');
  220. unset($_SERVER['GIT_ASKPASS']);
  221. }
  222. // clean up rogue git env vars in case this is running in a git hook
  223. if (getenv('GIT_DIR')) {
  224. putenv('GIT_DIR');
  225. unset($_SERVER['GIT_DIR']);
  226. }
  227. if (getenv('GIT_WORK_TREE')) {
  228. putenv('GIT_WORK_TREE');
  229. unset($_SERVER['GIT_WORK_TREE']);
  230. }
  231. // Run processes with predictable LANGUAGE
  232. if (getenv('LANGUAGE') !== 'C') {
  233. putenv('LANGUAGE=C');
  234. }
  235. // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940
  236. putenv("DYLD_LIBRARY_PATH");
  237. unset($_SERVER['DYLD_LIBRARY_PATH']);
  238. }
  239. public static function getGitHubDomainsRegex(Config $config)
  240. {
  241. return '('.implode('|', array_map('preg_quote', $config->get('github-domains'))).')';
  242. }
  243. public static function sanitizeUrl($message)
  244. {
  245. return preg_replace_callback('{://(?P<user>[^@]+?):(?P<password>.+?)@}', function ($m) {
  246. if (preg_match('{^[a-f0-9]{12,}$}', $m[1])) {
  247. return '://***:***@';
  248. }
  249. return '://'.$m[1].':***@';
  250. }, $message);
  251. }
  252. private function throwException($message, $url)
  253. {
  254. // git might delete a directory when it fails and php will not know
  255. clearstatcache();
  256. if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
  257. throw new \RuntimeException(self::sanitizeUrl('Failed to clone '.$url.', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()));
  258. }
  259. throw new \RuntimeException(self::sanitizeUrl($message));
  260. }
  261. /**
  262. * Retrieves the current git version.
  263. *
  264. * @return string|null The git version number.
  265. */
  266. public function getVersion()
  267. {
  268. if (isset(self::$version)) {
  269. return self::$version;
  270. }
  271. if (0 !== $this->process->execute('git --version', $output)) {
  272. return;
  273. }
  274. if (preg_match('/^git version (\d+(?:\.\d+)+)/m', $output, $matches)) {
  275. return self::$version = $matches[1];
  276. }
  277. }
  278. }