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