]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
Merge branch 'api-media-upload' into 0.9.x
[quix0rs-gnu-social.git] / lib / mediafile.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source mMediaFileicroblogging tool
4  *
5  * Abstraction for a media files in general
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Media
23  * @package   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @copyright 2008-2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 class MediaFile
35 {
36
37     var $filename      = null;
38     var $fileRecord    = null;
39     var $user          = null;
40     var $fileurl       = null;
41     var $short_fileurl = null;
42     var $mimetype      = null;
43
44     function __construct($user = null, $filename = null, $mimetype = null)
45     {
46         if ($user == null) {
47             $this->user = common_current_user();
48         }
49
50         $this->filename   = $filename;
51         $this->mimetype   = $mimetype;
52         $this->fileRecord = $this->storeFile();
53
54         $this->fileurl = common_local_url('attachment',
55                                     array('attachment' => $this->fileRecord->id));
56
57         $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
58         $this->short_fileurl = common_shorten_url($this->fileurl);
59         $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
60     }
61
62     function attachToNotice($notice)
63     {
64         File_to_post::processNew($this->fileRecord->id, $notice->id);
65         $this->maybeAddRedir($this->fileRecord->id,
66                              common_local_url('file', array('notice' => $notice->id)));
67     }
68
69     function shortUrl()
70     {
71         return $this->short_fileurl;
72     }
73
74     function delete()
75     {
76         $filepath = File::path($this->filename);
77         @unlink($filepath);
78     }
79
80     function storeFile() {
81
82         $file = new File;
83
84         $file->filename = $this->filename;
85         $file->url      = File::url($this->filename);
86         $filepath       = File::path($this->filename);
87         $file->size     = filesize($filepath);
88         $file->date     = time();
89         $file->mimetype = $this->mimetype;
90
91         $file_id = $file->insert();
92
93         if (!$file_id) {
94             common_log_db_error($file, "INSERT", __FILE__);
95             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
96         }
97
98         return $file;
99     }
100
101     function rememberFile($file, $short)
102     {
103         $this->maybeAddRedir($file->id, $short);
104     }
105
106     function maybeAddRedir($file_id, $url)
107     {
108         $file_redir = File_redirection::staticGet('url', $url);
109
110         if (empty($file_redir)) {
111
112             $file_redir = new File_redirection;
113             $file_redir->url = $url;
114             $file_redir->file_id = $file_id;
115
116             $result = $file_redir->insert();
117
118             if (!$result) {
119                 common_log_db_error($file_redir, "INSERT", __FILE__);
120                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
121             }
122         }
123     }
124
125     static function fromUpload($param = 'media', $user = null)
126     {
127         if (empty($user)) {
128             $user = common_current_user();
129         }
130
131         if (!isset($_FILES[$param]['error'])){
132             return;
133         }
134
135         switch ($_FILES[$param]['error']) {
136         case UPLOAD_ERR_OK: // success, jump out
137             break;
138         case UPLOAD_ERR_INI_SIZE:
139             throw new ClientException(_('The uploaded file exceeds the ' .
140                 'upload_max_filesize directive in php.ini.'));
141             return;
142         case UPLOAD_ERR_FORM_SIZE:
143             throw new ClientException(
144                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
145                 ' that was specified in the HTML form.'));
146             return;
147         case UPLOAD_ERR_PARTIAL:
148             @unlink($_FILES[$param]['tmp_name']);
149             throw new ClientException(_('The uploaded file was only' .
150                 ' partially uploaded.'));
151             return;
152         case UPLOAD_ERR_NO_TMP_DIR:
153             throw new ClientException(_('Missing a temporary folder.'));
154             return;
155         case UPLOAD_ERR_CANT_WRITE:
156             throw new ClientException(_('Failed to write file to disk.'));
157             return;
158         case UPLOAD_ERR_EXTENSION:
159             throw new ClientException(_('File upload stopped by extension.'));
160             return;
161         default:
162             throw new ClientException(_('System error uploading file.'));
163             return;
164         }
165
166         if (!MediaFile::respectsQuota($user, $_FILES['attach']['size'])) {
167
168             // Should never actually get here
169
170             @unlink($_FILES[$param]['tmp_name']);
171             throw new ClientException(_('File exceeds user\'s quota!'));
172             return;
173         }
174
175         $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name']);
176
177         $filename = null;
178
179         if (isset($mimetype)) {
180
181             $basename = basename($_FILES[$param]['name']);
182             $filename = File::filename($user->getProfile(), $basename, $mimetype);
183             $filepath = File::path($filename);
184
185             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
186
187             if (!$result) {
188                 throw new ClientException(_('File could not be moved to destination directory.'));
189                 return;
190             }
191
192         } else {
193             throw new ClientException(_('Could not determine file\'s mime-type!'));
194             return;
195         }
196
197         return new MediaFile($user, $filename, $mimetype);
198     }
199
200     static function fromFilehandle($fh, $user) {
201
202         $stream = stream_get_meta_data($fh);
203
204         if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
205
206             // Should never actually get here
207
208             throw new ClientException(_('File exceeds user\'s quota!'));
209             return;
210         }
211
212         $mimetype = MediaFile::getUploadedFileType($fh);
213
214         $filename = null;
215
216         if (isset($mimetype)) {
217
218             $filename = File::filename($user->getProfile(), "email", $mimetype);
219
220             $filepath = File::path($filename);
221
222             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
223
224             if (!$result) {
225                 throw new ClientException(_('File could not be moved to destination directory.' .
226                     $stream['uri'] . ' ' . $filepath));
227             }
228         } else {
229             throw new ClientException(_('Could not determine file\'s mime-type!'));
230             return;
231         }
232
233         return new MediaFile($user, $filename, $mimetype);
234     }
235
236     static function getUploadedFileType($f) {
237         require_once 'MIME/Type.php';
238
239         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
240         $cmd = common_config('attachments', 'filecommand');
241
242         $filetype = null;
243
244         if (is_string($f)) {
245
246             // assuming a filename
247
248             $filetype = MIME_Type::autoDetect($f);
249         } else {
250
251             // assuming a filehandle
252
253             $stream  = stream_get_meta_data($f);
254             $filetype = MIME_Type::autoDetect($stream['uri']);
255         }
256
257         if (in_array($filetype, common_config('attachments', 'supported'))) {
258             return $filetype;
259         }
260         $media = MIME_Type::getMedia($filetype);
261         if ('application' !== $media) {
262             $hint = sprintf(_(' Try using another %s format.'), $media);
263         } else {
264             $hint = '';
265         }
266         throw new ClientException(sprintf(
267             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
268     }
269
270     static function respectsQuota($user, $filesize)
271     {
272         $file = new File;
273         $result = $file->isRespectsQuota($user, $filesize);
274         if ($result === true) {
275             return true;
276         } else {
277             throw new ClientException($result);
278         }
279     }
280
281 }