]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
merge from testing
[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_TMP_DIR:
156             throw new ClientException(_('Missing a temporary folder.'));
157             return;
158         case UPLOAD_ERR_CANT_WRITE:
159             throw new ClientException(_('Failed to write file to disk.'));
160             return;
161         case UPLOAD_ERR_EXTENSION:
162             throw new ClientException(_('File upload stopped by extension.'));
163             return;
164         default:
165             throw new ClientException(_('System error uploading file.'));
166             return;
167         }
168
169         if (!MediaFile::respectsQuota($user, $_FILES['attach']['size'])) {
170
171             // Should never actually get here
172
173             @unlink($_FILES[$param]['tmp_name']);
174             throw new ClientException(_('File exceeds user\'s quota!'));
175             return;
176         }
177
178         $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name']);
179
180         $filename = null;
181
182         if (isset($mimetype)) {
183
184             $basename = basename($_FILES[$param]['name']);
185             $filename = File::filename($user->getProfile(), $basename, $mimetype);
186             $filepath = File::path($filename);
187
188             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
189
190             if (!$result) {
191                 throw new ClientException(_('File could not be moved to destination directory.'));
192                 return;
193             }
194
195         } else {
196             throw new ClientException(_('Could not determine file\'s mime-type!'));
197             return;
198         }
199
200         return new MediaFile($user, $filename, $mimetype);
201     }
202
203     static function fromFilehandle($fh, $user) {
204
205         $stream = stream_get_meta_data($fh);
206
207         if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
208
209             // Should never actually get here
210
211             throw new ClientException(_('File exceeds user\'s quota!'));
212             return;
213         }
214
215         $mimetype = MediaFile::getUploadedFileType($fh);
216
217         $filename = null;
218
219         if (isset($mimetype)) {
220
221             $filename = File::filename($user->getProfile(), "email", $mimetype);
222
223             $filepath = File::path($filename);
224
225             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
226
227             if (!$result) {
228                 throw new ClientException(_('File could not be moved to destination directory.' .
229                     $stream['uri'] . ' ' . $filepath));
230             }
231         } else {
232             throw new ClientException(_('Could not determine file\'s mime-type!'));
233             return;
234         }
235
236         return new MediaFile($user, $filename, $mimetype);
237     }
238
239     static function getUploadedFileType($f) {
240         require_once 'MIME/Type.php';
241
242         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
243         $cmd = common_config('attachments', 'filecommand');
244
245         $filetype = null;
246
247         if (is_string($f)) {
248
249             // assuming a filename
250
251             $filetype = MIME_Type::autoDetect($f);
252         } else {
253
254             // assuming a filehandle
255
256             $stream  = stream_get_meta_data($f);
257             $filetype = MIME_Type::autoDetect($stream['uri']);
258         }
259
260         if (in_array($filetype, common_config('attachments', 'supported'))) {
261             return $filetype;
262         }
263         $media = MIME_Type::getMedia($filetype);
264         if ('application' !== $media) {
265             $hint = sprintf(_(' Try using another %s format.'), $media);
266         } else {
267             $hint = '';
268         }
269         throw new ClientException(sprintf(
270             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
271     }
272
273     static function respectsQuota($user, $filesize)
274     {
275         $file = new File;
276         $result = $file->isRespectsQuota($user, $filesize);
277         if ($result === true) {
278             return true;
279         } else {
280             throw new ClientException($result);
281         }
282     }
283
284 }