]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
Add attachments 'thumb_width' and 'thumb_height' settings for inline thumbs, defaulti...
[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
40     var $filename      = null;
41     var $fileRecord    = null;
42     var $user          = null;
43     var $fileurl       = null;
44     var $short_fileurl = null;
45     var $mimetype      = null;
46
47     function __construct($user = null, $filename = null, $mimetype = null)
48     {
49         if ($user == null) {
50             $this->user = common_current_user();
51         } else {
52             $this->user = $user;
53         }
54
55         $this->filename   = $filename;
56         $this->mimetype   = $mimetype;
57         $this->fileRecord = $this->storeFile();
58         $this->thumbnailRecord = $this->storeThumbnail();
59
60         $this->fileurl = common_local_url('attachment',
61                                     array('attachment' => $this->fileRecord->id));
62
63         $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
64         $this->short_fileurl = common_shorten_url($this->fileurl);
65         $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
66     }
67
68     function attachToNotice($notice)
69     {
70         File_to_post::processNew($this->fileRecord->id, $notice->id);
71         $this->maybeAddRedir($this->fileRecord->id,
72                              common_local_url('file', array('notice' => $notice->id)));
73     }
74
75     function shortUrl()
76     {
77         return $this->short_fileurl;
78     }
79
80     function delete()
81     {
82         $filepath = File::path($this->filename);
83         @unlink($filepath);
84     }
85
86     function storeFile() {
87
88         $file = new File;
89
90         $file->filename = $this->filename;
91         $file->url      = File::url($this->filename);
92         $filepath       = File::path($this->filename);
93         $file->size     = filesize($filepath);
94         $file->date     = time();
95         $file->mimetype = $this->mimetype;
96
97         $file_id = $file->insert();
98
99         if (!$file_id) {
100             common_log_db_error($file, "INSERT", __FILE__);
101             // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
102             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
103         }
104
105         return $file;
106     }
107
108     /**
109      * Generate and store a thumbnail image for the uploaded file, if applicable.
110      *
111      * @return File_thumbnail or null
112      */
113     function storeThumbnail()
114     {
115         if (substr($this->mimetype, 0, strlen('image/')) != 'image/') {
116             // @fixme video thumbs would be nice!
117             return null;
118         }
119         try {
120             $image = new ImageFile($this->fileRecord->id,
121                                    File::path($this->filename));
122         } catch (Exception $e) {
123             // Unsupported image type.
124             return null;
125         }
126
127         $outname = File::filename($this->user->getProfile(), 'thumb-' . $this->filename, $this->mimetype);
128         $outpath = File::path($outname);
129
130         $width = common_config('attachments', 'thumb_width');
131         $height = common_config('attachments', 'thumb_height');
132
133         $image->resizeTo($outpath, $width, $height);
134         File_thumbnail::saveThumbnail($this->fileRecord->id,
135                                       File::url($outname),
136                                       $width,
137                                       $height);
138     }
139
140     function rememberFile($file, $short)
141     {
142         $this->maybeAddRedir($file->id, $short);
143     }
144
145     function maybeAddRedir($file_id, $url)
146     {
147         $file_redir = File_redirection::staticGet('url', $url);
148
149         if (empty($file_redir)) {
150
151             $file_redir = new File_redirection;
152             $file_redir->url = $url;
153             $file_redir->file_id = $file_id;
154
155             $result = $file_redir->insert();
156
157             if (!$result) {
158                 common_log_db_error($file_redir, "INSERT", __FILE__);
159                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
160                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
161             }
162         }
163     }
164
165     static function fromUpload($param = 'media', $user = null)
166     {
167         if (empty($user)) {
168             $user = common_current_user();
169         }
170
171         if (!isset($_FILES[$param]['error'])){
172             return;
173         }
174
175         switch ($_FILES[$param]['error']) {
176         case UPLOAD_ERR_OK: // success, jump out
177             break;
178         case UPLOAD_ERR_INI_SIZE:
179             // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
180             throw new ClientException(_('The uploaded file exceeds the ' .
181                 'upload_max_filesize directive in php.ini.'));
182             return;
183         case UPLOAD_ERR_FORM_SIZE:
184             throw new ClientException(
185                 // TRANS: Client exception.
186                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
187                 ' that was specified in the HTML form.'));
188             return;
189         case UPLOAD_ERR_PARTIAL:
190             @unlink($_FILES[$param]['tmp_name']);
191             // TRANS: Client exception.
192             throw new ClientException(_('The uploaded file was only' .
193                 ' partially uploaded.'));
194             return;
195         case UPLOAD_ERR_NO_FILE:
196             // No file; probably just a non-AJAX submission.
197             return;
198         case UPLOAD_ERR_NO_TMP_DIR:
199             // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
200             throw new ClientException(_('Missing a temporary folder.'));
201             return;
202         case UPLOAD_ERR_CANT_WRITE:
203             // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
204             throw new ClientException(_('Failed to write file to disk.'));
205             return;
206         case UPLOAD_ERR_EXTENSION:
207             // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
208             throw new ClientException(_('File upload stopped by extension.'));
209             return;
210         default:
211             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
212                 $_FILES[$param]['error']);
213             // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
214             throw new ClientException(_('System error uploading file.'));
215             return;
216         }
217
218         if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
219
220             // Should never actually get here
221
222             @unlink($_FILES[$param]['tmp_name']);
223             // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
224             throw new ClientException(_('File exceeds user\'s quota.'));
225             return;
226         }
227
228         $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
229                                                    $_FILES[$param]['name']);
230
231         $filename = null;
232
233         if (isset($mimetype)) {
234
235             $basename = basename($_FILES[$param]['name']);
236             $filename = File::filename($user->getProfile(), $basename, $mimetype);
237             $filepath = File::path($filename);
238
239             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
240
241             if (!$result) {
242                 // TRANS: Client exception thrown when a file upload operation fails because the file could
243                 // TRANS: not be moved from the temporary folder to the permanent file location.
244                 throw new ClientException(_('File could not be moved to destination directory.'));
245                 return;
246             }
247
248         } else {
249             // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
250             // TRANS: type of the uploaded file could not be determined.
251             throw new ClientException(_('Could not determine file\'s MIME type.'));
252             return;
253         }
254
255         return new MediaFile($user, $filename, $mimetype);
256     }
257
258     static function fromFilehandle($fh, $user) {
259
260         $stream = stream_get_meta_data($fh);
261
262         if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
263
264             // Should never actually get here
265
266             // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
267             throw new ClientException(_('File exceeds user\'s quota.'));
268             return;
269         }
270
271         $mimetype = MediaFile::getUploadedFileType($fh);
272
273         $filename = null;
274
275         if (isset($mimetype)) {
276
277             $filename = File::filename($user->getProfile(), "email", $mimetype);
278
279             $filepath = File::path($filename);
280
281             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
282
283             if (!$result) {
284                 // TRANS: Client exception thrown when a file upload operation fails because the file could
285                 // TRANS: not be moved from the temporary folder to the permanent file location.
286                 throw new ClientException(_('File could not be moved to destination directory.' .
287                     $stream['uri'] . ' ' . $filepath));
288             }
289         } else {
290             // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
291             // TRANS: type of the uploaded file could not be determined.
292             throw new ClientException(_('Could not determine file\'s MIME type.'));
293             return;
294         }
295
296         return new MediaFile($user, $filename, $mimetype);
297     }
298
299     /**
300      * Attempt to identify the content type of a given file.
301      * 
302      * @param mixed $f file handle resource, or filesystem path as string
303      * @param string $originalFilename (optional) for extension-based detection
304      * @return string
305      * 
306      * @fixme is this an internal or public method? It's called from GetFileAction
307      * @fixme this seems to tie a front-end error message in, kinda confusing
308      * @fixme this looks like it could return a PEAR_Error in some cases, if
309      *        type can't be identified and $config['attachments']['supported'] is true
310      * 
311      * @throws ClientException if type is known, but not supported for local uploads
312      */
313     static function getUploadedFileType($f, $originalFilename=false) {
314         require_once 'MIME/Type.php';
315         require_once 'MIME/Type/Extension.php';
316
317         // We have to disable auto handling of PEAR errors
318         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
319         $mte = new MIME_Type_Extension();
320
321         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
322         $cmd = common_config('attachments', 'filecommand');
323
324         $filetype = null;
325
326         // If we couldn't get a clear type from the file extension,
327         // we'll go ahead and try checking the content. Content checks
328         // are unambiguous for most image files, but nearly useless
329         // for office document formats.
330
331         if (is_string($f)) {
332
333             // assuming a filename
334
335             $filetype = MIME_Type::autoDetect($f);
336
337         } else {
338
339             // assuming a filehandle
340
341             $stream  = stream_get_meta_data($f);
342             $filetype = MIME_Type::autoDetect($stream['uri']);
343         }
344
345         // The content-based sources for MIME_Type::autoDetect()
346         // are wildly unreliable for office-type documents. If we've
347         // gotten an unclear reponse back or just couldn't identify it,
348         // we'll try detecting a type from its extension...
349         $unclearTypes = array('application/octet-stream',
350                               'application/vnd.ms-office',
351                               'application/zip');
352
353         if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
354             $type = $mte->getMIMEType($originalFilename);
355             if (is_string($type)) {
356                 $filetype = $type;
357             }
358         }
359
360         $supported = common_config('attachments', 'supported');
361         if (is_array($supported)) {
362             // Normalize extensions to mime types
363             foreach ($supported as $i => $entry) {
364                 if (strpos($entry, '/') === false) {
365                     common_log(LOG_INFO, "sample.$entry");
366                     $supported[$i] = $mte->getMIMEType("sample.$entry");
367                 }
368             }
369         }
370         if ($supported === true || in_array($filetype, $supported)) {
371             // Restore PEAR error handlers for our DB code...
372             PEAR::staticPopErrorHandling();
373             return $filetype;
374         }
375         $media = MIME_Type::getMedia($filetype);
376         if ('application' !== $media) {
377             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
378             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
379             // TRANS: the MIME type that was denied.
380             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
381             'Try using another %2$s format.'), $filetype, $media);
382         } else {
383             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
384             // TRANS: %s is the file type that was denied.
385             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
386         }
387         // Restore PEAR error handlers for our DB code...
388         PEAR::staticPopErrorHandling();
389         throw new ClientException($hint);
390     }
391
392     static function respectsQuota($user, $filesize)
393     {
394         $file = new File;
395         $result = $file->isRespectsQuota($user, $filesize);
396         if ($result === true) {
397             return true;
398         } else {
399             throw new ClientException($result);
400         }
401     }
402
403 }