]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.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             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['attach']['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
185         $filename = null;
186
187         if (isset($mimetype)) {
188
189             $basename = basename($_FILES[$param]['name']);
190             $filename = File::filename($user->getProfile(), $basename, $mimetype);
191             $filepath = File::path($filename);
192
193             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
194
195             if (!$result) {
196                 throw new ClientException(_('File could not be moved to destination directory.'));
197                 return;
198             }
199
200         } else {
201             throw new ClientException(_('Could not determine file\'s MIME type.'));
202             return;
203         }
204
205         return new MediaFile($user, $filename, $mimetype);
206     }
207
208     static function fromFilehandle($fh, $user) {
209
210         $stream = stream_get_meta_data($fh);
211
212         if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
213
214             // Should never actually get here
215
216             throw new ClientException(_('File exceeds user\'s quota.'));
217             return;
218         }
219
220         $mimetype = MediaFile::getUploadedFileType($fh);
221
222         $filename = null;
223
224         if (isset($mimetype)) {
225
226             $filename = File::filename($user->getProfile(), "email", $mimetype);
227
228             $filepath = File::path($filename);
229
230             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
231
232             if (!$result) {
233                 throw new ClientException(_('File could not be moved to destination directory.' .
234                     $stream['uri'] . ' ' . $filepath));
235             }
236         } else {
237             throw new ClientException(_('Could not determine file\'s MIME type.'));
238             return;
239         }
240
241         return new MediaFile($user, $filename, $mimetype);
242     }
243
244     static function getUploadedFileType($f) {
245         require_once 'MIME/Type.php';
246
247         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
248         $cmd = common_config('attachments', 'filecommand');
249
250         $filetype = null;
251
252         if (is_string($f)) {
253
254             // assuming a filename
255
256             $filetype = MIME_Type::autoDetect($f);
257         } else {
258
259             // assuming a filehandle
260
261             $stream  = stream_get_meta_data($f);
262             $filetype = MIME_Type::autoDetect($stream['uri']);
263         }
264
265         if (in_array($filetype, common_config('attachments', 'supported'))) {
266             return $filetype;
267         }
268         $media = MIME_Type::getMedia($filetype);
269         if ('application' !== $media) {
270             $hint = sprintf(_(' Try using another %s format.'), $media);
271         } else {
272             $hint = '';
273         }
274         throw new ClientException(sprintf(
275             _('%s is not a supported file type on this server.'), $filetype) . $hint);
276     }
277
278     static function respectsQuota($user, $filesize)
279     {
280         $file = new File;
281         $result = $file->isRespectsQuota($user, $filesize);
282         if ($result === true) {
283             return true;
284         } else {
285             throw new ClientException($result);
286         }
287     }
288
289 }