StoreRemoteMediaPlugin.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. $file->fetch();
  115. //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
  116. } catch (NoResultException $e) {
  117. $original_name = HTTPClient::get_filename($remoteUrl, $headers);
  118. $filename = MediaFile::encodeFilename($original_name, $filehash);
  119. $fullpath = File::path($filename);
  120. common_debug("StoreRemoteMedia retrieved url {$remoteUrl} for file with id={$file->id} " .
  121. "and will store in {$fullpath}");
  122. // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
  123. if ((!file_exists($fullpath) || substr($fullpath, 0, strlen(INSTALLDIR)) != INSTALLDIR) &&
  124. file_put_contents($fullpath, $imgData) === false) {
  125. throw new ServerException(_('Could not write downloaded file to disk.'));
  126. }
  127. // Updated our database for the file record
  128. $orig = clone($file);
  129. $file->filehash = $filehash;
  130. $file->filename = $filename;
  131. $file->width = $info[0]; // array indexes documented on php.net:
  132. $file->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  133. // Throws exception on failure.
  134. $file->updateWithKeys($orig);
  135. }
  136. // Get rid of the file from memory
  137. unset($imgData);
  138. // Output
  139. $imgPath = $file->getPath();
  140. return false;
  141. }
  142. /**
  143. * @return boolean true if given url passes blacklist check
  144. */
  145. protected function checkBlackList($url)
  146. {
  147. if (!$this->check_blacklist) {
  148. return true;
  149. }
  150. $host = parse_url($url, PHP_URL_HOST);
  151. foreach ($this->domain_blacklist as $regex => $provider) {
  152. if (preg_match("/$regex/", $host)) {
  153. return false;
  154. }
  155. }
  156. return true;
  157. }
  158. /***
  159. * @return boolean true if given url passes whitelist check
  160. */
  161. protected function checkWhiteList($url)
  162. {
  163. if (!$this->check_whitelist) {
  164. return true;
  165. }
  166. $host = parse_url($url, PHP_URL_HOST);
  167. foreach ($this->domain_whitelist as $regex => $provider) {
  168. if (preg_match("/$regex/", $host)) {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. public function onPluginVersion(array &$versions): bool
  175. {
  176. $versions[] = array('name' => 'StoreRemoteMedia',
  177. 'version' => self::PLUGIN_VERSION,
  178. 'author' => 'Mikael Nordfeldth',
  179. 'homepage' => GNUSOCIAL_ENGINE_URL,
  180. 'description' =>
  181. // TRANS: Plugin description.
  182. _m('Plugin for downloading remotely attached files to local server.'));
  183. return true;
  184. }
  185. }