RemoteFilesystem.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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\Composer;
  13. use Composer\IO\IOInterface;
  14. use Composer\Downloader\TransportException;
  15. /**
  16. * @author François Pluchino <francois.pluchino@opendisplay.com>
  17. */
  18. class RemoteFilesystem
  19. {
  20. private $io;
  21. private $firstCall;
  22. private $bytesMax;
  23. private $originUrl;
  24. private $fileUrl;
  25. private $fileName;
  26. private $result;
  27. private $progress;
  28. private $lastProgress;
  29. private $options;
  30. /**
  31. * Constructor.
  32. *
  33. * @param IOInterface $io The IO instance
  34. * @param array $options The options
  35. */
  36. public function __construct(IOInterface $io, $options = array())
  37. {
  38. $this->io = $io;
  39. $this->options = $options;
  40. }
  41. /**
  42. * Copy the remote file in local.
  43. *
  44. * @param string $originUrl The origin URL
  45. * @param string $fileUrl The file URL
  46. * @param string $fileName the local filename
  47. * @param boolean $progress Display the progression
  48. * @param array $options Additional context options
  49. *
  50. * @return bool true
  51. */
  52. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  53. {
  54. $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  55. return $this->result;
  56. }
  57. /**
  58. * Get the content.
  59. *
  60. * @param string $originUrl The origin URL
  61. * @param string $fileUrl The file URL
  62. * @param boolean $progress Display the progression
  63. * @param array $options Additional context options
  64. *
  65. * @return string The content
  66. */
  67. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  68. {
  69. $this->get($originUrl, $fileUrl, $options, null, $progress);
  70. return $this->result;
  71. }
  72. /**
  73. * Get file content or copy action.
  74. *
  75. * @param string $originUrl The origin URL
  76. * @param string $fileUrl The file URL
  77. * @param array $additionalOptions context options
  78. * @param string $fileName the local filename
  79. * @param boolean $progress Display the progression
  80. *
  81. * @throws TransportException When the file could not be downloaded
  82. */
  83. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  84. {
  85. $this->bytesMax = 0;
  86. $this->result = null;
  87. $this->originUrl = $originUrl;
  88. $this->fileUrl = $fileUrl;
  89. $this->fileName = $fileName;
  90. $this->progress = $progress;
  91. $this->lastProgress = null;
  92. $options = $this->getOptionsForUrl($originUrl, $additionalOptions);
  93. $ctx = StreamContextFactory::getContext($options, array('notification' => array($this, 'callbackGet')));
  94. if ($this->progress) {
  95. $this->io->write(" Downloading: <comment>connection...</comment>", false);
  96. }
  97. $errorMessage = '';
  98. $errorCode = 0;
  99. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  100. if ($errorMessage) {
  101. $errorMessage .= "\n";
  102. }
  103. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  104. });
  105. try {
  106. $result = file_get_contents($fileUrl, false, $ctx);
  107. } catch (\Exception $e) {
  108. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  109. $e->setHeaders($http_response_header);
  110. }
  111. }
  112. if ($errorMessage && !ini_get('allow_url_fopen')) {
  113. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  114. }
  115. restore_error_handler();
  116. if (isset($e)) {
  117. throw $e;
  118. }
  119. // fix for 5.4.0 https://bugs.php.net/bug.php?id=61336
  120. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  121. $result = false;
  122. $errorCode = $match[1];
  123. }
  124. // decode gzip
  125. if (false !== $result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  126. $decode = false;
  127. foreach ($http_response_header as $header) {
  128. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  129. $decode = true;
  130. continue;
  131. } elseif (preg_match('{^HTTP/}i', $header)) {
  132. $decode = false;
  133. }
  134. }
  135. if ($decode) {
  136. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  137. $result = zlib_decode($result);
  138. } else {
  139. // work around issue with gzuncompress & co that do not work with all gzip checksums
  140. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  141. }
  142. }
  143. }
  144. if ($this->progress) {
  145. $this->io->overwrite(" Downloading: <comment>100%</comment>");
  146. }
  147. // handle copy command if download was successful
  148. if (false !== $result && null !== $fileName) {
  149. $errorMessage = '';
  150. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  151. if ($errorMessage) {
  152. $errorMessage .= "\n";
  153. }
  154. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  155. });
  156. $result = (bool) file_put_contents($fileName, $result);
  157. restore_error_handler();
  158. if (false === $result) {
  159. throw new TransportException('The "'.$fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  160. }
  161. }
  162. // avoid overriding if content was loaded by a sub-call to get()
  163. if (null === $this->result) {
  164. $this->result = $result;
  165. }
  166. if (false === $this->result) {
  167. $e = new TransportException('The "'.$fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  168. if (!empty($http_response_header[0])) {
  169. $e->setHeaders($http_response_header);
  170. }
  171. throw $e;
  172. }
  173. }
  174. /**
  175. * Get notification action.
  176. *
  177. * @param integer $notificationCode The notification code
  178. * @param integer $severity The severity level
  179. * @param string $message The message
  180. * @param integer $messageCode The message code
  181. * @param integer $bytesTransferred The loaded size
  182. * @param integer $bytesMax The total size
  183. */
  184. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  185. {
  186. switch ($notificationCode) {
  187. case STREAM_NOTIFY_FAILURE:
  188. throw new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.trim($message).')', $messageCode);
  189. break;
  190. case STREAM_NOTIFY_AUTH_REQUIRED:
  191. if (401 === $messageCode) {
  192. if (!$this->io->isInteractive()) {
  193. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console";
  194. throw new TransportException($message, 401);
  195. }
  196. $this->io->overwrite(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  197. $username = $this->io->ask(' Username: ');
  198. $password = $this->io->askAndHideAnswer(' Password: ');
  199. $this->io->setAuthorization($this->originUrl, $username, $password);
  200. $this->get($this->originUrl, $this->fileUrl, $this->fileName, $this->progress);
  201. }
  202. break;
  203. case STREAM_NOTIFY_AUTH_RESULT:
  204. if (403 === $messageCode) {
  205. throw new TransportException($message, 403);
  206. }
  207. break;
  208. case STREAM_NOTIFY_FILE_SIZE_IS:
  209. if ($this->bytesMax < $bytesMax) {
  210. $this->bytesMax = $bytesMax;
  211. }
  212. break;
  213. case STREAM_NOTIFY_PROGRESS:
  214. if ($this->bytesMax > 0 && $this->progress) {
  215. $progression = 0;
  216. if ($this->bytesMax > 0) {
  217. $progression = round($bytesTransferred / $this->bytesMax * 100);
  218. }
  219. if ((0 === $progression % 5) && $progression !== $this->lastProgress) {
  220. $this->lastProgress = $progression;
  221. $this->io->overwrite(" Downloading: <comment>$progression%</comment>", false);
  222. }
  223. }
  224. break;
  225. default:
  226. break;
  227. }
  228. }
  229. protected function getOptionsForUrl($originUrl, $additionalOptions)
  230. {
  231. $headers = array(
  232. sprintf(
  233. 'User-Agent: Composer/%s (%s; %s; PHP %s.%s.%s)',
  234. Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION,
  235. php_uname('s'),
  236. php_uname('r'),
  237. PHP_MAJOR_VERSION,
  238. PHP_MINOR_VERSION,
  239. PHP_RELEASE_VERSION
  240. )
  241. );
  242. if (extension_loaded('zlib')) {
  243. $headers[] = 'Accept-Encoding: gzip';
  244. }
  245. if ($this->io->hasAuthorization($originUrl)) {
  246. $auth = $this->io->getAuthorization($originUrl);
  247. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  248. $headers[] = 'Authorization: Basic '.$authStr;
  249. }
  250. $options = array_replace_recursive($this->options, $additionalOptions);
  251. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  252. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  253. }
  254. foreach ($headers as $header) {
  255. $options['http']['header'][] = $header;
  256. }
  257. return $options;
  258. }
  259. }