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