]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/StoreRemoteMedia/StoreRemoteMediaPlugin.php
Merge branch 'master' of git.gnu.io:gnu/gnu-social into nightly
[quix0rs-gnu-social.git] / plugins / StoreRemoteMedia / StoreRemoteMediaPlugin.php
1 <?php
2
3 if (!defined('GNUSOCIAL')) { exit(1); }
4
5 // FIXME: To support remote video/whatever files, this plugin needs reworking.
6
7 class StoreRemoteMediaPlugin extends Plugin
8 {
9     // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
10     // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
11     public $domain_whitelist = array(       // hostname => service provider
12                                     '^i\d*\.ytimg\.com$' => 'YouTube',
13                                     '^i\d*\.vimeocdn\.com$' => 'Vimeo',
14                                     );
15     public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
16     public $check_whitelist  = false;    // security/abuse precaution
17
18     protected $imgData = array();
19
20     // these should be declared protected everywhere
21     public function initialize()
22     {
23         parent::initialize();
24
25         $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
26     }
27
28     /**
29      * Save embedding information for a File, if applicable.
30      *
31      * Normally this event is called through File::saveNew()
32      *
33      * @param File   $file       The newly inserted File object.
34      * @param array  $redir_data lookup data eg from File_redirection::where()
35      * @param string $given_url
36      *
37      * @return boolean success
38      */
39     public function onStartFileSaveNew(array &$redir_data, $given_url)
40     {
41         // save given URL as title if it's a media file this plugin understands
42         // which will make it shown in the AttachmentList widgets
43
44         if (isset($redir_data['title']) && strlen($redir_data['title']>0)) {
45             // Title is already set
46             return true;
47         }
48         if (!isset($redir_data['type'])) {
49             // Unknown mimetype, it's not our job to figure out what it is.
50             return true;
51         }
52         switch (common_get_mime_media($redir_data['type'])) {
53         case 'image':
54             // Just to set something for now at least...
55             $redir_data['title'] = $given_url;
56             break;
57         }
58         
59         return true;
60     }
61
62     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
63     {
64         // If we are on a private node, we won't do any remote calls (just as a precaution until
65         // we can configure this from config.php for the private nodes)
66         if (common_config('site', 'private')) {
67             return true;
68         }
69
70         if ($media !== 'image') {
71             return true;
72         }
73
74         // If there is a local filename, it is either a local file already or has already been downloaded.
75         if (!empty($file->filename)) {
76             return true;
77         }
78
79         $this->checkWhitelist($file->getUrl());
80
81         // First we download the file to memory and test whether it's actually an image file
82         $imgData = HTTPClient::quickGet($file->getUrl());
83         common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->id, $file->url));
84         $info = @getimagesizefromstring($imgData);
85         if ($info === false) {
86             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
87         } elseif (!$info[0] || !$info[1]) {
88             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
89         }
90
91         $filehash = hash(File::FILEHASH_ALG, $imgData);
92         try {
93             // Exception will be thrown before $file is set to anything, so old $file value will be kept
94             $file = File::getByHash($filehash);
95
96             //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
97         } catch (NoResultException $e) {
98             $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
99             $fullpath = File::path($filename);
100
101             // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
102             if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
103                 throw new ServerException(_('Could not write downloaded file to disk.'));
104             }
105
106             // Updated our database for the file record
107             $orig = clone($file);
108             $file->filehash = $filehash;
109             $file->filename = $filename;
110             $file->width = $info[0];    // array indexes documented on php.net:
111             $file->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
112             // Throws exception on failure.
113             $file->updateWithKeys($orig, 'id');
114         }
115         // Get rid of the file from memory
116         unset($imgData);
117
118         $imgPath = $file->getPath();
119
120         return false;
121     }
122
123     /**
124      * @return boolean          false on no check made, provider name on success
125      * @throws ServerException  if check is made but fails
126      */
127     protected function checkWhitelist($url)
128     {
129         if (!$this->check_whitelist) {
130             return false;   // indicates "no check made"
131         }
132
133         $host = parse_url($url, PHP_URL_HOST);
134         foreach ($this->domain_whitelist as $regex => $provider) {
135             if (preg_match("/$regex/", $host)) {
136                 return $provider;    // we trust this source, return provider name
137             }
138         }
139
140         throw new ServerException(sprintf(_('Domain not in remote source whitelist: %s'), $host));
141     }
142
143     public function onPluginVersion(array &$versions)
144     {
145         $versions[] = array('name' => 'StoreRemoteMedia',
146                             'version' => GNUSOCIAL_VERSION,
147                             'author' => 'Mikael Nordfeldth',
148                             'homepage' => 'https://gnu.io/',
149                             'description' =>
150                             // TRANS: Plugin description.
151                             _m('Plugin for downloading remotely attached files to local server.'));
152         return true;
153     }
154 }