]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
caa902de5dfeb13c18413372769198b9af209241
[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         $maxWidth = common_config('attachments', 'thumb_width');
131         $maxHeight = common_config('attachments', 'thumb_height');
132         list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
133
134         $image->resizeTo($outpath, $width, $height);
135         File_thumbnail::saveThumbnail($this->fileRecord->id,
136                                       File::url($outname),
137                                       $width,
138                                       $height);
139     }
140
141     function scaleToFit($width, $height, $maxWidth, $maxHeight)
142     {
143         $aspect = $maxWidth / $maxHeight;
144         $w1 = $maxWidth;
145         $h1 = intval($height * $maxWidth / $width);
146         if ($h1 > $maxHeight) {
147             $w2 = intval($width * $maxHeight / $height);
148             $h2 = $maxHeight;
149             return array($w2, $h2);
150         }
151         return array($w1, $h1);
152     }
153
154     function rememberFile($file, $short)
155     {
156         $this->maybeAddRedir($file->id, $short);
157     }
158
159     function maybeAddRedir($file_id, $url)
160     {
161         $file_redir = File_redirection::staticGet('url', $url);
162
163         if (empty($file_redir)) {
164
165             $file_redir = new File_redirection;
166             $file_redir->url = $url;
167             $file_redir->file_id = $file_id;
168
169             $result = $file_redir->insert();
170
171             if (!$result) {
172                 common_log_db_error($file_redir, "INSERT", __FILE__);
173                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
174                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
175             }
176         }
177     }
178
179     static function fromUpload($param = 'media', $user = null)
180     {
181         if (empty($user)) {
182             $user = common_current_user();
183         }
184
185         if (!isset($_FILES[$param]['error'])){
186             return;
187         }
188
189         switch ($_FILES[$param]['error']) {
190         case UPLOAD_ERR_OK: // success, jump out
191             break;
192         case UPLOAD_ERR_INI_SIZE:
193             // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
194             throw new ClientException(_('The uploaded file exceeds the ' .
195                 'upload_max_filesize directive in php.ini.'));
196             return;
197         case UPLOAD_ERR_FORM_SIZE:
198             throw new ClientException(
199                 // TRANS: Client exception.
200                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
201                 ' that was specified in the HTML form.'));
202             return;
203         case UPLOAD_ERR_PARTIAL:
204             @unlink($_FILES[$param]['tmp_name']);
205             // TRANS: Client exception.
206             throw new ClientException(_('The uploaded file was only' .
207                 ' partially uploaded.'));
208             return;
209         case UPLOAD_ERR_NO_FILE:
210             // No file; probably just a non-AJAX submission.
211             return;
212         case UPLOAD_ERR_NO_TMP_DIR:
213             // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
214             throw new ClientException(_('Missing a temporary folder.'));
215             return;
216         case UPLOAD_ERR_CANT_WRITE:
217             // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
218             throw new ClientException(_('Failed to write file to disk.'));
219             return;
220         case UPLOAD_ERR_EXTENSION:
221             // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
222             throw new ClientException(_('File upload stopped by extension.'));
223             return;
224         default:
225             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
226                 $_FILES[$param]['error']);
227             // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
228             throw new ClientException(_('System error uploading file.'));
229             return;
230         }
231
232         if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
233
234             // Should never actually get here
235
236             @unlink($_FILES[$param]['tmp_name']);
237             // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
238             throw new ClientException(_('File exceeds user\'s quota.'));
239             return;
240         }
241
242         $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
243                                                    $_FILES[$param]['name']);
244
245         $filename = null;
246
247         if (isset($mimetype)) {
248
249             $basename = basename($_FILES[$param]['name']);
250             $filename = File::filename($user->getProfile(), $basename, $mimetype);
251             $filepath = File::path($filename);
252
253             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
254
255             if (!$result) {
256                 // TRANS: Client exception thrown when a file upload operation fails because the file could
257                 // TRANS: not be moved from the temporary folder to the permanent file location.
258                 throw new ClientException(_('File could not be moved to destination directory.'));
259                 return;
260             }
261
262         } else {
263             // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
264             // TRANS: type of the uploaded file could not be determined.
265             throw new ClientException(_('Could not determine file\'s MIME type.'));
266             return;
267         }
268
269         return new MediaFile($user, $filename, $mimetype);
270     }
271
272     static function fromFilehandle($fh, $user) {
273
274         $stream = stream_get_meta_data($fh);
275
276         if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
277
278             // Should never actually get here
279
280             // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
281             throw new ClientException(_('File exceeds user\'s quota.'));
282             return;
283         }
284
285         $mimetype = MediaFile::getUploadedFileType($fh);
286
287         $filename = null;
288
289         if (isset($mimetype)) {
290
291             $filename = File::filename($user->getProfile(), "email", $mimetype);
292
293             $filepath = File::path($filename);
294
295             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
296
297             if (!$result) {
298                 // TRANS: Client exception thrown when a file upload operation fails because the file could
299                 // TRANS: not be moved from the temporary folder to the permanent file location.
300                 throw new ClientException(_('File could not be moved to destination directory.' .
301                     $stream['uri'] . ' ' . $filepath));
302             }
303         } else {
304             // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
305             // TRANS: type of the uploaded file could not be determined.
306             throw new ClientException(_('Could not determine file\'s MIME type.'));
307             return;
308         }
309
310         return new MediaFile($user, $filename, $mimetype);
311     }
312
313     /**
314      * Attempt to identify the content type of a given file.
315      * 
316      * @param mixed $f file handle resource, or filesystem path as string
317      * @param string $originalFilename (optional) for extension-based detection
318      * @return string
319      * 
320      * @fixme is this an internal or public method? It's called from GetFileAction
321      * @fixme this seems to tie a front-end error message in, kinda confusing
322      * @fixme this looks like it could return a PEAR_Error in some cases, if
323      *        type can't be identified and $config['attachments']['supported'] is true
324      * 
325      * @throws ClientException if type is known, but not supported for local uploads
326      */
327     static function getUploadedFileType($f, $originalFilename=false) {
328         require_once 'MIME/Type.php';
329         require_once 'MIME/Type/Extension.php';
330
331         // We have to disable auto handling of PEAR errors
332         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
333         $mte = new MIME_Type_Extension();
334
335         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
336         $cmd = common_config('attachments', 'filecommand');
337
338         $filetype = null;
339
340         // If we couldn't get a clear type from the file extension,
341         // we'll go ahead and try checking the content. Content checks
342         // are unambiguous for most image files, but nearly useless
343         // for office document formats.
344
345         if (is_string($f)) {
346
347             // assuming a filename
348
349             $filetype = MIME_Type::autoDetect($f);
350
351         } else {
352
353             // assuming a filehandle
354
355             $stream  = stream_get_meta_data($f);
356             $filetype = MIME_Type::autoDetect($stream['uri']);
357         }
358
359         // The content-based sources for MIME_Type::autoDetect()
360         // are wildly unreliable for office-type documents. If we've
361         // gotten an unclear reponse back or just couldn't identify it,
362         // we'll try detecting a type from its extension...
363         $unclearTypes = array('application/octet-stream',
364                               'application/vnd.ms-office',
365                               'application/zip',
366                               // TODO: for XML we could do better content-based sniffing too
367                               'text/xml');
368
369         if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
370             $type = $mte->getMIMEType($originalFilename);
371             if (is_string($type)) {
372                 $filetype = $type;
373             }
374         }
375
376         $supported = common_config('attachments', 'supported');
377         if (is_array($supported)) {
378             // Normalize extensions to mime types
379             foreach ($supported as $i => $entry) {
380                 if (strpos($entry, '/') === false) {
381                     common_log(LOG_INFO, "sample.$entry");
382                     $supported[$i] = $mte->getMIMEType("sample.$entry");
383                 }
384             }
385         }
386         if ($supported === true || in_array($filetype, $supported)) {
387             // Restore PEAR error handlers for our DB code...
388             PEAR::staticPopErrorHandling();
389             return $filetype;
390         }
391         $media = MIME_Type::getMedia($filetype);
392         if ('application' !== $media) {
393             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
394             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
395             // TRANS: the MIME type that was denied.
396             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
397             'Try using another %2$s format.'), $filetype, $media);
398         } else {
399             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
400             // TRANS: %s is the file type that was denied.
401             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
402         }
403         // Restore PEAR error handlers for our DB code...
404         PEAR::staticPopErrorHandling();
405         throw new ClientException($hint);
406     }
407
408     static function respectsQuota($user, $filesize)
409     {
410         $file = new File;
411         $result = $file->isRespectsQuota($user, $filesize);
412         if ($result === true) {
413             return true;
414         } else {
415             throw new ClientException($result);
416         }
417     }
418
419 }