FileDownloader.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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\Downloader;
  12. use Composer\IO\IOInterface;
  13. use Composer\Package\PackageInterface;
  14. use Composer\Util\Filesystem;
  15. /**
  16. * Base downloader for file packages
  17. *
  18. * @author Kirill chEbba Chebunin <iam@chebba.org>
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. * @author François Pluchino <francois.pluchino@opendisplay.com>
  21. */
  22. abstract class FileDownloader implements DownloaderInterface
  23. {
  24. protected $io;
  25. private $bytesMax;
  26. private $firstCall;
  27. private $url;
  28. private $fileUrl;
  29. private $fileName;
  30. /**
  31. * Constructor.
  32. *
  33. * @param IOInterface $io The IO instance
  34. */
  35. public function __construct(IOInterface $io)
  36. {
  37. $this->io = $io;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function getInstallationSource()
  43. {
  44. return 'dist';
  45. }
  46. /**
  47. * {@inheritDoc}
  48. */
  49. public function download(PackageInterface $package, $path)
  50. {
  51. $this->firstCall = true;
  52. $this->url = $package->getSourceUrl();
  53. $this->fileUrl = $package->getDistUrl();
  54. // init the progress bar
  55. $this->bytesMax = 0;
  56. $url = $package->getDistUrl();
  57. $checksum = $package->getDistSha1Checksum();
  58. if (!is_dir($path)) {
  59. if (file_exists($path)) {
  60. throw new \UnexpectedValueException($path.' exists and is not a directory');
  61. }
  62. if (!mkdir($path, 0777, true)) {
  63. throw new \UnexpectedValueException($path.' does not exist and could not be created');
  64. }
  65. }
  66. $fileName = rtrim($path.'/'.md5(time().rand()).'.'.pathinfo($url, PATHINFO_EXTENSION), '.');
  67. $this->fileName = $fileName;
  68. $this->io->write(" - Package <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)");
  69. if (!extension_loaded('openssl') && (0 === strpos($url, 'https:') || 0 === strpos($url, 'http://github.com'))) {
  70. // bypass https for github if openssl is disabled
  71. if (preg_match('{^https?://(github.com/[^/]+/[^/]+/(zip|tar)ball/[^/]+)$}i', $url, $match)) {
  72. $url = 'http://nodeload.'.$match[1];
  73. } else {
  74. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  75. }
  76. }
  77. $this->copy($this->url, $this->fileName, $this->fileUrl);
  78. $this->io->write('');
  79. if (!file_exists($fileName)) {
  80. throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
  81. .' directory is writable and you have internet connectivity');
  82. }
  83. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  84. throw new \UnexpectedValueException('The checksum verification of the archive failed (downloaded from '.$url.')');
  85. }
  86. $this->io->write(' Unpacking archive');
  87. $this->extract($fileName, $path);
  88. $this->io->write(' Cleaning up');
  89. unlink($fileName);
  90. // If we have only a one dir inside it suppose to be a package itself
  91. $contentDir = glob($path . '/*');
  92. if (1 === count($contentDir)) {
  93. $contentDir = $contentDir[0];
  94. foreach (array_merge(glob($contentDir . '/.*'), glob($contentDir . '/*')) as $file) {
  95. if (trim(basename($file), '.')) {
  96. rename($file, $path . '/' . basename($file));
  97. }
  98. }
  99. rmdir($contentDir);
  100. }
  101. $this->io->write('');
  102. }
  103. /**
  104. * {@inheritDoc}
  105. */
  106. public function update(PackageInterface $initial, PackageInterface $target, $path)
  107. {
  108. $fs = new Filesystem();
  109. $fs->removeDirectory($path);
  110. $this->download($target, $path);
  111. }
  112. /**
  113. * {@inheritDoc}
  114. */
  115. public function remove(PackageInterface $package, $path)
  116. {
  117. $fs = new Filesystem();
  118. $fs->removeDirectory($path);
  119. }
  120. /**
  121. * Get notification action.
  122. *
  123. * @param integer $notificationCode The notification code
  124. * @param integer $severity The severity level
  125. * @param string $message The message
  126. * @param integer $messageCode The message code
  127. * @param integer $bytesTransferred The loaded size
  128. * @param integer $bytesMax The total size
  129. */
  130. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  131. {
  132. switch ($notificationCode) {
  133. case STREAM_NOTIFY_AUTH_REQUIRED:
  134. case STREAM_NOTIFY_FAILURE:
  135. // for private repository returning 404 error when the authorization is incorrect
  136. $auth = $this->io->getAuthorization($this->url);
  137. $ps = $this->firstCall && 404 === $messageCode
  138. && null === $this->io->getLastUsername()
  139. && null === $auth['username'];
  140. if (404 === $messageCode && !$this->firstCall) {
  141. throw new \RuntimeException("The '" . $this->fileUrl . "' URL not found");
  142. }
  143. $this->firstCall = false;
  144. // get authorization informations
  145. if (401 === $messageCode || $ps) {
  146. if (!$this->io->isInteractive()) {
  147. $mess = "The '" . $this->fileUrl . "' URL not found";
  148. if (401 === $code || $ps) {
  149. $mess = "The '" . $this->fileUrl . "' URL required the authorization.\nYou must be used the interactive console";
  150. }
  151. throw new \RuntimeException($mess);
  152. }
  153. $this->io->overwrite(' Authorization required:');
  154. $username = $this->io->ask(' Username: ');
  155. $password = $this->io->askAndHideAnswer(' Password: ');
  156. $this->io->setAuthorization($this->url, $username, $password);
  157. $this->copy($this->url, $this->fileName, $this->fileUrl);
  158. }
  159. break;
  160. case STREAM_NOTIFY_FILE_SIZE_IS:
  161. if ($this->bytesMax < $bytesMax) {
  162. $this->bytesMax = $bytesMax;
  163. }
  164. break;
  165. case STREAM_NOTIFY_PROGRESS:
  166. if ($this->bytesMax > 0) {
  167. $progression = 0;
  168. if ($this->bytesMax > 0) {
  169. $progression = round($bytesTransferred / $this->bytesMax * 100);
  170. }
  171. if (0 === $progression % 5) {
  172. $this->io->overwrite(" Downloading: <comment>$progression%</comment>", false);
  173. }
  174. }
  175. break;
  176. default:
  177. break;
  178. }
  179. }
  180. protected function copy($url, $fileName, $fileUrl)
  181. {
  182. // Handle system proxy
  183. $params = array('http' => array());
  184. if (isset($_SERVER['HTTP_PROXY'])) {
  185. // http(s):// is not supported in proxy
  186. $proxy = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $_SERVER['HTTP_PROXY']);
  187. if (0 === strpos($proxy, 'ssl:') && !extension_loaded('openssl')) {
  188. throw new \RuntimeException('You must enable the openssl extension to use a proxy over https');
  189. }
  190. $params['http'] = array(
  191. 'proxy' => $proxy,
  192. 'request_fulluri' => true,
  193. );
  194. }
  195. if ($this->io->hasAuthorization($url)) {
  196. $auth = $this->io->getAuthorization($url);
  197. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  198. $params['http'] = array_merge($params['http'], array('header' => "Authorization: Basic $authStr\r\n"));
  199. }
  200. $ctx = stream_context_create($params);
  201. stream_context_set_params($ctx, array("notification" => array($this, 'callbackGet')));
  202. $this->io->overwrite(" Downloading: <comment>connection...</comment>", false);
  203. @copy($fileUrl, $fileName, $ctx);
  204. $this->io->overwrite(" Downloading", false);
  205. }
  206. /**
  207. * Extract file to directory
  208. *
  209. * @param string $file Extracted file
  210. * @param string $path Directory
  211. *
  212. * @throws \UnexpectedValueException If can not extract downloaded file to path
  213. */
  214. protected abstract function extract($file, $path);
  215. }