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