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