StoreRemoteMediaPlugin.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <?php
  2. if (!defined('GNUSOCIAL')) { exit(1); }
  3. // FIXME: To support remote video/whatever files, this plugin needs reworking.
  4. class StoreRemoteMediaPlugin extends Plugin
  5. {
  6. const PLUGIN_VERSION = '2.0.0';
  7. // settings which can be set in config.php with addPlugin('Embed', array('param'=>'value', ...));
  8. // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
  9. public $domain_whitelist = [
  10. // hostname => service provider
  11. '^i\d*\.ytimg\.com$' => 'YouTube',
  12. '^i\d*\.vimeocdn\.com$' => 'Vimeo',
  13. ];
  14. public $append_whitelist = []; // fill this array as domain_whitelist to add more trusted sources
  15. public $check_whitelist = false; // security/abuse precaution
  16. public $domain_blacklist = [];
  17. public $check_blacklist = false;
  18. public $max_image_bytes = 10 * 1024 * 1024; // 10MiB max image size by default
  19. protected $imgData = [];
  20. // these should be declared protected everywhere
  21. public function initialize()
  22. {
  23. parent::initialize();
  24. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  25. }
  26. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  27. {
  28. // If we are on a private node, we won't do any remote calls (just as a precaution until
  29. // we can configure this from config.php for the private nodes)
  30. if (common_config('site', 'private')) {
  31. return true;
  32. }
  33. if ($media !== 'image') {
  34. return true;
  35. }
  36. // If there is a local filename, it is either a local file already or has already been downloaded.
  37. if (!empty($file->filename)) {
  38. return true;
  39. }
  40. $remoteUrl = $file->getUrl();
  41. if (empty($remoteUrl)) {
  42. return true;
  43. }
  44. if (!$this->checkWhiteList($remoteUrl) ||
  45. !$this->checkBlackList($remoteUrl)) {
  46. return true;
  47. }
  48. // Relative URL, something's off
  49. if (empty(parse_url($remoteUrl, PHP_URL_HOST))) {
  50. common_err("StoreRemoteMedia found a url without host (\"{$remoteUrl}\") for file with id = {$file->id}");
  51. return true;
  52. }
  53. try {
  54. $http = new HTTPClient();
  55. common_debug(sprintf('Performing HEAD request for remote file id==%u to avoid '.
  56. 'unnecessarily downloading too large files. URL: %s',
  57. $file->getID(), $remoteUrl));
  58. $url = $remoteUrl;
  59. $head = $http->head($remoteUrl);
  60. $remoteUrl = $head->getEffectiveUrl(); // to avoid going through redirects again
  61. if (empty($remoteUrl)) {
  62. common_log(LOG_ERR, "URL after redirects is somehow empty, for URL {$url}");
  63. return true;
  64. }
  65. if (!$this->checkBlackList($remoteUrl)) {
  66. common_log(LOG_WARN, sprintf('%s: Non-blacklisted URL %s redirected to blacklisted URL %s',
  67. __CLASS__, $file->getUrl(), $remoteUrl));
  68. return true;
  69. }
  70. $headers = $head->getHeader();
  71. $headers = array_change_key_case($headers, CASE_LOWER);
  72. $filesize = isset($headers['content-length']) ?: $file->getSize();
  73. if (empty($filesize)) {
  74. // file size not specified on remote server
  75. common_debug(sprintf('%s: Ignoring remote media because we did not get a ' .
  76. 'content length for file id==%u', __CLASS__, $file->getID()));
  77. return true;
  78. } elseif ($filesize > $this->max_image_bytes) {
  79. //FIXME: When we perhaps start fetching videos etc. we'll need to
  80. // differentiate max_image_bytes from that...
  81. // file too big according to plugin configuration
  82. common_debug(sprintf('%s: Skipping remote media because content length (%u) ' .
  83. 'is larger than plugin configured max_image_bytes (%u) ' .
  84. 'for file id==%u', __CLASS__, intval($filesize),
  85. $this->max_image_bytes, $file->getID()));
  86. return true;
  87. } elseif ($filesize > common_config('attachments', 'file_quota')) {
  88. // file too big according to site configuration
  89. common_debug(sprintf('%s: Skipping remote media because content length (%u) ' .
  90. 'is larger than file_quota (%u) for file id==%u',
  91. __CLASS__, intval($filesize),
  92. common_config('attachments', 'file_quota'), $file->getID()));
  93. return true;
  94. }
  95. // Then we download the file to memory and test whether it's actually an image file
  96. common_debug(sprintf('Downloading remote file id=%u (should be size %u) ' .
  97. 'with effective URL: %s', $file->getID(), $filesize, _ve($remoteUrl)));
  98. $imgData = HTTPClient::quickGet($remoteUrl);
  99. } catch (HTTP_Request2_ConnectionException $e) {
  100. common_log(LOG_ERR, __CLASS__.': '._ve(get_class($e)).' on URL: ' .
  101. _ve($file->getUrl()).' threw exception: '.$e->getMessage());
  102. return true;
  103. }
  104. $info = @getimagesizefromstring($imgData);
  105. if ($info === false) {
  106. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
  107. } elseif (!$info[0] || !$info[1]) {
  108. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  109. }
  110. $filehash = hash(File::FILEHASH_ALG, $imgData);
  111. try {
  112. // Exception will be thrown before $file is set to anything, so old $file value will be kept
  113. $file = File::getByHash($filehash);
  114. //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
  115. } catch (NoResultException $e) {
  116. $original_name = HTTPClient::get_filename($remoteUrl, $headers);
  117. $filename = MediaFile::encodeFilename($original_name, $filehash);
  118. $fullpath = File::path($filename);
  119. common_debug("StoreRemoteMedia retrieved url {$remoteUrl} for file with id={$file->id} " .
  120. "and will store in {$fullpath}");
  121. // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
  122. if ((!file_exists($fullpath) || substr($fullpath, 0, strlen(INSTALLDIR)) != INSTALLDIR) &&
  123. file_put_contents($fullpath, $imgData) === false) {
  124. throw new ServerException(_('Could not write downloaded file to disk.'));
  125. }
  126. // Updated our database for the file record
  127. $orig = clone($file);
  128. $file->filehash = $filehash;
  129. $file->filename = $filename;
  130. $file->width = $info[0]; // array indexes documented on php.net:
  131. $file->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  132. // Throws exception on failure.
  133. $file->updateWithKeys($orig);
  134. }
  135. // Get rid of the file from memory
  136. unset($imgData);
  137. // Output
  138. $imgPath = $file->getPath();
  139. return false;
  140. }
  141. /**
  142. * @return boolean true if given url passes blacklist check
  143. */
  144. protected function checkBlackList($url)
  145. {
  146. if (!$this->check_blacklist) {
  147. return true;
  148. }
  149. $host = parse_url($url, PHP_URL_HOST);
  150. foreach ($this->domain_blacklist as $regex => $provider) {
  151. if (preg_match("/$regex/", $host)) {
  152. return false;
  153. }
  154. }
  155. return true;
  156. }
  157. /***
  158. * @return boolean true if given url passes whitelist check
  159. */
  160. protected function checkWhiteList($url)
  161. {
  162. if (!$this->check_whitelist) {
  163. return true;
  164. }
  165. $host = parse_url($url, PHP_URL_HOST);
  166. foreach ($this->domain_whitelist as $regex => $provider) {
  167. if (preg_match("/$regex/", $host)) {
  168. return true;
  169. }
  170. }
  171. return false;
  172. }
  173. public function onPluginVersion(array &$versions): bool
  174. {
  175. $versions[] = array('name' => 'StoreRemoteMedia',
  176. 'version' => self::PLUGIN_VERSION,
  177. 'author' => 'Mikael Nordfeldth',
  178. 'homepage' => GNUSOCIAL_ENGINE_URL,
  179. 'description' =>
  180. // TRANS: Plugin description.
  181. _m('Plugin for downloading remotely attached files to local server.'));
  182. return true;
  183. }
  184. }