StoreRemoteMediaPlugin.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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('Oembed', array('param'=>'value', ...));
  8. // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
  9. public $domain_whitelist = array( // hostname => service provider
  10. '^i\d*\.ytimg\.com$' => 'YouTube',
  11. '^i\d*\.vimeocdn\.com$' => 'Vimeo',
  12. );
  13. public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
  14. public $check_whitelist = false; // security/abuse precaution
  15. public $domain_blacklist = array();
  16. public $check_blacklist = false;
  17. public $max_image_bytes = 10485760; // 10MiB max image size by default
  18. protected $imgData = array();
  19. // these should be declared protected everywhere
  20. public function initialize()
  21. {
  22. parent::initialize();
  23. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  24. }
  25. /**
  26. * Save embedding information for a File, if applicable.
  27. *
  28. * Normally this event is called through File::saveNew()
  29. *
  30. * @param File $file The abount-to-be-inserted File object.
  31. *
  32. * @return boolean success
  33. */
  34. public function onStartFileSaveNew(File &$file)
  35. {
  36. // save given URL as title if it's a media file this plugin understands
  37. // which will make it shown in the AttachmentList widgets
  38. if (isset($file->title) && strlen($file->title)>0) {
  39. // Title is already set
  40. return true;
  41. }
  42. if (!isset($file->mimetype)) {
  43. // Unknown mimetype, it's not our job to figure out what it is.
  44. return true;
  45. }
  46. switch (common_get_mime_media($file->mimetype)) {
  47. case 'image':
  48. // Just to set something for now at least...
  49. //$file->title = $file->mimetype;
  50. break;
  51. }
  52. return true;
  53. }
  54. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  55. {
  56. // If we are on a private node, we won't do any remote calls (just as a precaution until
  57. // we can configure this from config.php for the private nodes)
  58. if (common_config('site', 'private')) {
  59. return true;
  60. }
  61. if ($media !== 'image') {
  62. return true;
  63. }
  64. // If there is a local filename, it is either a local file already or has already been downloaded.
  65. if (!empty($file->filename)) {
  66. return true;
  67. }
  68. $remoteUrl = $file->getUrl();
  69. if (!$this->checkWhiteList($remoteUrl) ||
  70. !$this->checkBlackList($remoteUrl)) {
  71. return true;
  72. }
  73. try {
  74. /*
  75. $http = new HTTPClient();
  76. common_debug(sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $file->getID(), $remoteUrl));
  77. $head = $http->head($remoteUrl);
  78. $remoteUrl = $head->getEffectiveUrl(); // to avoid going through redirects again
  79. if (!$this->checkBlackList($remoteUrl)) {
  80. common_log(LOG_WARN, sprintf('%s: Non-blacklisted URL %s redirected to blacklisted URL %s', __CLASS__, $file->getUrl(), $remoteUrl));
  81. return true;
  82. }
  83. $headers = $head->getHeader();
  84. $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
  85. */
  86. $filesize = $file->getSize();
  87. if (empty($filesize)) {
  88. // file size not specified on remote server
  89. common_debug(sprintf('%s: Ignoring remote media because we did not get a content length for file id==%u', __CLASS__, $file->getID()));
  90. return true;
  91. } elseif ($filesize > $this->max_image_bytes) {
  92. //FIXME: When we perhaps start fetching videos etc. we'll need to differentiate max_image_bytes from that...
  93. // file too big according to plugin configuration
  94. common_debug(sprintf('%s: Skipping remote media because content length (%u) is larger than plugin configured max_image_bytes (%u) for file id==%u', __CLASS__, intval($filesize), $this->max_image_bytes, $file->getID()));
  95. return true;
  96. } elseif ($filesize > common_config('attachments', 'file_quota')) {
  97. // file too big according to site configuration
  98. common_debug(sprintf('%s: Skipping remote media because content length (%u) is larger than file_quota (%u) for file id==%u', __CLASS__, intval($filesize), common_config('attachments', 'file_quota'), $file->getID()));
  99. return true;
  100. }
  101. // Then we download the file to memory and test whether it's actually an image file
  102. common_debug(sprintf('Downloading remote file id==%u (should be size %u) with effective URL: %s', $file->getID(), $filesize, _ve($remoteUrl)));
  103. $imgData = HTTPClient::quickGet($remoteUrl);
  104. } catch (HTTP_Request2_ConnectionException $e) {
  105. common_log(LOG_ERR, __CLASS__.': '._ve(get_class($e)).' on URL: '._ve($file->getUrl()).' threw exception: '.$e->getMessage());
  106. return true;
  107. }
  108. $info = @getimagesizefromstring($imgData);
  109. if ($info === false) {
  110. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
  111. } elseif (!$info[0] || !$info[1]) {
  112. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  113. }
  114. $filehash = hash(File::FILEHASH_ALG, $imgData);
  115. try {
  116. // Exception will be thrown before $file is set to anything, so old $file value will be kept
  117. $file = File::getByHash($filehash);
  118. //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
  119. } catch (NoResultException $e) {
  120. $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
  121. $fullpath = File::path($filename);
  122. // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
  123. if (!file_exists($fullpath) && 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. $imgPath = $file->getPath();
  138. return false;
  139. }
  140. /**
  141. * @return boolean true if given url passes blacklist check
  142. */
  143. protected function checkBlackList($url)
  144. {
  145. if (!$this->check_blacklist) {
  146. return true;
  147. }
  148. $host = parse_url($url, PHP_URL_HOST);
  149. foreach ($this->domain_blacklist as $regex => $provider) {
  150. if (preg_match("/$regex/", $host)) {
  151. return false;
  152. }
  153. }
  154. return true;
  155. }
  156. /***
  157. * @return boolean true if given url passes whitelist check
  158. */
  159. protected function checkWhiteList($url)
  160. {
  161. if (!$this->check_whitelist) {
  162. return true;
  163. }
  164. $host = parse_url($url, PHP_URL_HOST);
  165. foreach ($this->domain_whitelist as $regex => $provider) {
  166. if (preg_match("/$regex/", $host)) {
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. public function onPluginVersion(array &$versions)
  173. {
  174. $versions[] = array('name' => 'StoreRemoteMedia',
  175. 'version' => self::PLUGIN_VERSION,
  176. 'author' => 'Mikael Nordfeldth',
  177. 'homepage' => 'https://gnu.io/',
  178. 'description' =>
  179. // TRANS: Plugin description.
  180. _m('Plugin for downloading remotely attached files to local server.'));
  181. return true;
  182. }
  183. }