]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
MediaFile thumbnail event hooks + VideoThumbnails plugin
[quix0rs-gnu-social.git] / lib / mediafile.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstraction for media files in general
6  *
7  * TODO: combine with ImageFile?
8  *
9  * PHP version 5
10  *
11  * LICENCE: This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Affero General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Affero General Public License for more details.
20  *
21  * You should have received a copy of the GNU Affero General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  *
24  * @category  Media
25  * @package   StatusNet
26  * @author    Robin Millette <robin@millette.info>
27  * @author    Zach Copley <zach@status.net>
28  * @copyright 2008-2009 StatusNet, Inc.
29  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
30  * @link      http://status.net/
31  */
32
33 if (!defined('STATUSNET') && !defined('LACONICA')) {
34     exit(1);
35 }
36
37 class MediaFile
38 {
39     protected $scoped   = null;
40
41     var $filename      = null;
42     var $fileRecord    = null;
43     var $fileurl       = null;
44     var $short_fileurl = null;
45     var $mimetype      = null;
46     var $thumbnailRecord = null;
47
48     function __construct(Profile $scoped, $filename = null, $mimetype = null)
49     {
50         $this->scoped = $scoped;
51
52         $this->filename   = $filename;
53         $this->mimetype   = $mimetype;
54         $this->fileRecord = $this->storeFile();
55         try {
56             $this->thumbnailRecord = $this->storeThumbnail();
57         } catch (UnsupportedMediaException $e) {
58             // FIXME: Add "unknown media" icon or something
59             $this->thumbnailRecord = null;
60         }
61
62         $this->fileurl = common_local_url('attachment',
63                                     array('attachment' => $this->fileRecord->id));
64
65         $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
66         $this->short_fileurl = common_shorten_url($this->fileurl);
67         $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
68     }
69
70     function attachToNotice($notice)
71     {
72         File_to_post::processNew($this->fileRecord->id, $notice->id);
73         $this->maybeAddRedir($this->fileRecord->id,
74                              common_local_url('file', array('notice' => $notice->id)));
75     }
76
77     public function getPath()
78     {
79         return File::path($this->filename);
80     }
81
82     function shortUrl()
83     {
84         return $this->short_fileurl;
85     }
86
87     function delete()
88     {
89         $filepath = File::path($this->filename);
90         @unlink($filepath);
91     }
92
93     function storeFile() {
94
95         $file = new File;
96
97         $file->filename = $this->filename;
98         $file->url      = File::url($this->filename);
99         $filepath       = File::path($this->filename);
100         $file->size     = filesize($filepath);
101         $file->date     = time();
102         $file->mimetype = $this->mimetype;
103
104         $file_id = $file->insert();
105
106         if (!$file_id) {
107             common_log_db_error($file, "INSERT", __FILE__);
108             // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
109             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
110         }
111
112         return $file;
113     }
114
115     /**
116      * Generate and store a thumbnail image for the uploaded file, if applicable.
117      *
118      * @return File_thumbnail or null
119      */
120     function storeThumbnail()
121     {
122         $imgPath = null;
123         $media = common_get_mime_media($this->mimetype);
124
125         if (Event::handle('CreateFileImageThumbnail', array($this, &$imgPath, $media))) {
126             switch ($media) {
127             case 'image':
128                 $imgPath = $this->getPath();
129                 break;
130             default: 
131                 throw new UnsupportedMediaException(_('Unsupported media format.'), $this->getPath());
132             }
133         }
134         if (!file_exists($imgPath)) {
135             throw new ServerException(sprintf('Thumbnail source is not stored locally: %s', $imgPath));
136         }
137
138         try {
139             $image = new ImageFile($this->fileRecord->id, $imgPath);
140         } catch (UnsupportedMediaException $e) {
141             // Avoid deleting the original
142             if ($image->getPath() != $this->getPath()) {
143                 $image->unlink();
144             }
145             throw $e;
146         }
147
148         $outname = File::filename($this->scoped, 'thumb-' . $this->filename, $this->mimetype);
149         $outpath = File::path($outname);
150
151         $maxWidth = common_config('attachments', 'thumb_width');
152         $maxHeight = common_config('attachments', 'thumb_height');
153         list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
154
155         $image->resizeTo($outpath, $width, $height);
156
157         // Avoid deleting the original
158         if ($image->getPath() != $this->getPath()) {
159             $image->unlink();
160         }
161         return File_thumbnail::saveThumbnail($this->fileRecord->id,
162                                       File::url($outname),
163                                       $width,
164                                       $height);
165     }
166
167     function scaleToFit($width, $height, $maxWidth, $maxHeight)
168     {
169         $aspect = $maxWidth / $maxHeight;
170         $w1 = $maxWidth;
171         $h1 = intval($height * $maxWidth / $width);
172         if ($h1 > $maxHeight) {
173             $w2 = intval($width * $maxHeight / $height);
174             $h2 = $maxHeight;
175             return array($w2, $h2);
176         }
177         return array($w1, $h1);
178     }
179
180     function rememberFile($file, $short)
181     {
182         $this->maybeAddRedir($file->id, $short);
183     }
184
185     function maybeAddRedir($file_id, $url)
186     {
187         $file_redir = File_redirection::getKV('url', $url);
188
189         if (empty($file_redir)) {
190
191             $file_redir = new File_redirection;
192             $file_redir->url = $url;
193             $file_redir->file_id = $file_id;
194
195             $result = $file_redir->insert();
196
197             if (!$result) {
198                 common_log_db_error($file_redir, "INSERT", __FILE__);
199                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
200                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
201             }
202         }
203     }
204
205     static function fromUpload($param = 'media', Profile $scoped)
206     {
207         if (is_null($scoped)) {
208             $scoped = Profile::current();
209         }
210
211         if (!isset($_FILES[$param]['error'])){
212             return;
213         }
214
215         switch ($_FILES[$param]['error']) {
216         case UPLOAD_ERR_OK: // success, jump out
217             break;
218         case UPLOAD_ERR_INI_SIZE:
219             // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
220             throw new ClientException(_('The uploaded file exceeds the ' .
221                 'upload_max_filesize directive in php.ini.'));
222         case UPLOAD_ERR_FORM_SIZE:
223             throw new ClientException(
224                 // TRANS: Client exception.
225                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
226                 ' that was specified in the HTML form.'));
227         case UPLOAD_ERR_PARTIAL:
228             @unlink($_FILES[$param]['tmp_name']);
229             // TRANS: Client exception.
230             throw new ClientException(_('The uploaded file was only' .
231                 ' partially uploaded.'));
232         case UPLOAD_ERR_NO_FILE:
233             // No file; probably just a non-AJAX submission.
234             return;
235         case UPLOAD_ERR_NO_TMP_DIR:
236             // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
237             throw new ClientException(_('Missing a temporary folder.'));
238         case UPLOAD_ERR_CANT_WRITE:
239             // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
240             throw new ClientException(_('Failed to write file to disk.'));
241         case UPLOAD_ERR_EXTENSION:
242             // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
243             throw new ClientException(_('File upload stopped by extension.'));
244         default:
245             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
246                 $_FILES[$param]['error']);
247             // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
248             throw new ClientException(_('System error uploading file.'));
249         }
250
251         // Throws exception if additional size does not respect quota
252         File::respectsQuota($scoped, $_FILES[$param]['size']);
253
254         $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
255                                                    $_FILES[$param]['name']);
256
257         $basename = basename($_FILES[$param]['name']);
258         $filename = File::filename($scoped, $basename, $mimetype);
259         $filepath = File::path($filename);
260
261         $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
262
263         if (!$result) {
264             // TRANS: Client exception thrown when a file upload operation fails because the file could
265             // TRANS: not be moved from the temporary folder to the permanent file location.
266             throw new ClientException(_('File could not be moved to destination directory.'));
267         }
268
269         return new MediaFile($scoped, $filename, $mimetype);
270     }
271
272     static function fromFilehandle($fh, Profile $scoped) {
273
274         $stream = stream_get_meta_data($fh);
275
276         File::respectsQuota($scoped, filesize($stream['uri']));
277
278         $mimetype = self::getUploadedMimeType($stream['uri']);
279
280         $filename = File::filename($scoped, "email", $mimetype);
281
282         $filepath = File::path($filename);
283
284         $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
285
286         if (!$result) {
287             // TRANS: Client exception thrown when a file upload operation fails because the file could
288             // TRANS: not be moved from the temporary folder to the permanent file location.
289             throw new ClientException(_('File could not be moved to destination directory.' .
290                 $stream['uri'] . ' ' . $filepath));
291         }
292
293         return new MediaFile($scoped, $filename, $mimetype);
294     }
295
296     /**
297      * Attempt to identify the content type of a given file.
298      * 
299      * @param string $filepath filesystem path as string (file must exist)
300      * @param string $originalFilename (optional) for extension-based detection
301      * @return string
302      * 
303      * @fixme this seems to tie a front-end error message in, kinda confusing
304      * 
305      * @throws ClientException if type is known, but not supported for local uploads
306      */
307     static function getUploadedMimeType($filepath, $originalFilename=false) {
308         // We only accept filenames to existing files
309         $mimelookup = new finfo(FILEINFO_MIME_TYPE);
310         $mimetype = $mimelookup->file($filepath);
311
312         // Unclear types are such that we can't really tell by the auto
313         // detect what they are (.bin, .exe etc. are just "octet-stream")
314         $unclearTypes = array('application/octet-stream',
315                               'application/vnd.ms-office',
316                               'application/zip',
317                               // TODO: for XML we could do better content-based sniffing too
318                               'text/xml');
319
320         $supported = common_config('attachments', 'supported');
321
322         // If we didn't match, or it is an unclear match
323         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
324             try {
325                 $type = common_supported_ext_to_mime($originalFilename);
326                 return $type;
327             } catch (Exception $e) {
328                 // Extension not found, so $mimetype is our best guess
329             }
330         }
331
332         // If $config['attachments']['supported'] equals boolean true, accept any mimetype
333         if ($supported === true || array_key_exists($mimetype, $supported)) {
334             // FIXME: Don't know if it always has a mimetype here because
335             // finfo->file CAN return false on error: http://php.net/finfo_file
336             // so if $supported === true, this may return something unexpected.
337             return $mimetype;
338         }
339
340         // We can conclude that we have failed to get the MIME type
341         $media = common_get_mime_media($mimetype);
342         if ('application' !== $media) {
343             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
344             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
345             // TRANS: the MIME type that was denied.
346             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
347             'Try using another %2$s format.'), $mimetype, $media);
348         } else {
349             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
350             // TRANS: %s is the file type that was denied.
351             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
352         }
353         throw new ClientException($hint);
354     }
355 }