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