StoreRemoteMediaPlugin.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. protected $imgData = array();
  17. // these should be declared protected everywhere
  18. public function initialize()
  19. {
  20. parent::initialize();
  21. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  22. }
  23. /**
  24. * Save embedding information for a File, if applicable.
  25. *
  26. * Normally this event is called through File::saveNew()
  27. *
  28. * @param File $file The abount-to-be-inserted File object.
  29. *
  30. * @return boolean success
  31. */
  32. public function onStartFileSaveNew(File &$file)
  33. {
  34. // save given URL as title if it's a media file this plugin understands
  35. // which will make it shown in the AttachmentList widgets
  36. if (isset($file->title) && strlen($file->title)>0) {
  37. // Title is already set
  38. return true;
  39. }
  40. if (!isset($file->mimetype)) {
  41. // Unknown mimetype, it's not our job to figure out what it is.
  42. return true;
  43. }
  44. switch (common_get_mime_media($file->mimetype)) {
  45. case 'image':
  46. // Just to set something for now at least...
  47. $file->title = $file->mimetype;
  48. break;
  49. }
  50. return true;
  51. }
  52. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  53. {
  54. // If we are on a private node, we won't do any remote calls (just as a precaution until
  55. // we can configure this from config.php for the private nodes)
  56. if (common_config('site', 'private')) {
  57. return true;
  58. }
  59. if ($media !== 'image') {
  60. return true;
  61. }
  62. // If there is a local filename, it is either a local file already or has already been downloaded.
  63. if (!empty($file->filename)) {
  64. return true;
  65. }
  66. if (!$this->checkWhiteList($file->getUrl()) ||
  67. !$this->checkBlackList($file->getUrl())) {
  68. return true;
  69. }
  70. // First we download the file to memory and test whether it's actually an image file
  71. common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->getID(), _ve($file->getUrl())));
  72. try {
  73. $imgData = HTTPClient::quickGet($file->getUrl());
  74. } catch (HTTP_Request2_ConnectionException $e) {
  75. common_log(LOG_ERR, __CLASS__.': quickGet on URL: '._ve($file->getUrl()).' threw exception: '.$e->getMessage());
  76. return true;
  77. }
  78. $info = @getimagesizefromstring($imgData);
  79. if ($info === false) {
  80. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $file->getUrl());
  81. } elseif (!$info[0] || !$info[1]) {
  82. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  83. }
  84. $filehash = hash(File::FILEHASH_ALG, $imgData);
  85. try {
  86. // Exception will be thrown before $file is set to anything, so old $file value will be kept
  87. $file = File::getByHash($filehash);
  88. //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
  89. } catch (NoResultException $e) {
  90. $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
  91. $fullpath = File::path($filename);
  92. // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
  93. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  94. throw new ServerException(_('Could not write downloaded file to disk.'));
  95. }
  96. // Updated our database for the file record
  97. $orig = clone($file);
  98. $file->filehash = $filehash;
  99. $file->filename = $filename;
  100. $file->width = $info[0]; // array indexes documented on php.net:
  101. $file->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  102. // Throws exception on failure.
  103. $file->updateWithKeys($orig);
  104. }
  105. // Get rid of the file from memory
  106. unset($imgData);
  107. $imgPath = $file->getPath();
  108. return false;
  109. }
  110. /**
  111. * @return boolean true if given url passes blacklist check
  112. */
  113. protected function checkBlackList($url)
  114. {
  115. if (!$this->check_blacklist) {
  116. return true;
  117. }
  118. $host = parse_url($url, PHP_URL_HOST);
  119. foreach ($this->domain_blacklist as $regex => $provider) {
  120. if (preg_match("/$regex/", $host)) {
  121. return false;
  122. }
  123. }
  124. return true;
  125. }
  126. /***
  127. * @return boolean true if given url passes whitelist check
  128. */
  129. protected function checkWhiteList($url)
  130. {
  131. if (!$this->check_whitelist) {
  132. return true;
  133. }
  134. $host = parse_url($url, PHP_URL_HOST);
  135. foreach ($this->domain_whitelist as $regex => $provider) {
  136. if (preg_match("/$regex/", $host)) {
  137. return true;
  138. }
  139. }
  140. return false;
  141. }
  142. public function onPluginVersion(array &$versions)
  143. {
  144. $versions[] = array('name' => 'StoreRemoteMedia',
  145. 'version' => GNUSOCIAL_VERSION,
  146. 'author' => 'Mikael Nordfeldth',
  147. 'homepage' => 'https://gnu.io/',
  148. 'description' =>
  149. // TRANS: Plugin description.
  150. _m('Plugin for downloading remotely attached files to local server.'));
  151. return true;
  152. }
  153. }