StoreRemoteMediaPlugin.php 8.6 KB

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