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