]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
31868daec8a0418bff11a0745bb4f209ffb94d2f
[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         common_debug('in MediaFile constructor');
51
52         $this->filename = $filename;
53         $this->mimetype = $mimetype;
54
55         common_debug('storing file');
56         $this->fileRecord = $this->storeFile();
57         common_debug('finished storing file');
58
59         $this->fileurl = common_local_url('attachment',
60                                     array('attachment' => $this->fileRecord->id));
61
62         common_debug('$this->fileurl() = ' . $this->fileurl);
63
64         // not sure this is necessary -- Zach
65         $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
66
67         common_debug('shortening file url');
68         $this->short_fileurl = common_shorten_url($this->fileurl);
69         common_debug('shortened file url =  ' . $short_fileurl);
70
71         // Also, not sure this is necessary -- Zach
72         $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
73
74         common_debug("MediaFile: end of constructor");
75     }
76
77     function attachToNotice($notice)
78     {
79         common_debug('MediaFile::attachToNotice() -- doing File_to_post');
80         File_to_post::processNew($this->fileRecord->id, $notice->id);
81         common_debug('MediaFile done doing File_to_post');
82
83         $this->maybeAddRedir($this->fileRecord->id,
84                              common_local_url('file', array('notice' => $notice->id)));
85     }
86
87     function shortUrl()
88     {
89         return $this->short_fileurl;
90     }
91
92     function delete()
93     {
94         $filepath = File::path($this->filename);
95         @unlink($filepath);
96     }
97
98     function storeFile() {
99
100         $file = new File;
101         $file->filename = $this->filename;
102
103         common_debug('storing ' . $this->filename);
104
105         $file->url = File::url($this->filename);
106         common_debug('file->url = ' . $file->url);
107
108         $filepath = File::path($this->filename);
109         common_debug('filepath = ' . $filepath);
110
111         $file->size = filesize($filepath);
112         $file->date = time();
113         $file->mimetype = $this->mimetype;
114
115         $file_id = $file->insert();
116
117         if (!$file_id) {
118
119             common_debug("storeFile: problem inserting new file");
120             common_log_db_error($file, "INSERT", __FILE__);
121             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
122         }
123
124         common_debug('finished storing file');
125
126         return $file;
127     }
128
129     function rememberFile($file, $short)
130     {
131         $this->maybeAddRedir($file->id, $short);
132     }
133
134     function maybeAddRedir($file_id, $url)
135     {
136
137         common_debug("maybeAddRedir: looking up url: $url for file id $file_id");
138
139         $file_redir = File_redirection::staticGet('url', $url);
140
141         if (empty($file_redir)) {
142
143             common_debug("maybeAddRedir: $url is not in the db");
144
145             $file_redir = new File_redirection;
146             $file_redir->url = $url;
147             $file_redir->file_id = $file_id;
148
149             $result = $file_redir->insert();
150
151             if (!$result) {
152                 common_log_db_error($file_redir, "INSERT", __FILE__);
153                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
154             }
155         } else {
156
157             common_debug("maybeAddRedir: no need to add $url, it's already in the db");
158         }
159     }
160
161     static function fromUpload($param = 'media', $user = null)
162     {
163         common_debug("fromUpload: param = $param");
164
165         if (empty($user)) {
166             $user = common_current_user();
167         }
168
169         if (!isset($_FILES[$param]['error'])){
170             common_debug('no file found');
171             return;
172         }
173
174         switch ($_FILES[$param]['error']) {
175         case UPLOAD_ERR_OK: // success, jump out
176             break;
177         case UPLOAD_ERR_INI_SIZE:
178             throw new ClientException(_('The uploaded file exceeds the ' .
179                 'upload_max_filesize directive in php.ini.'));
180             return;
181         case UPLOAD_ERR_FORM_SIZE:
182             throw new ClientException(
183                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
184                 ' that was specified in the HTML form.'));
185             return;
186         case UPLOAD_ERR_PARTIAL:
187             @unlink($_FILES[$param]['tmp_name']);
188             throw new ClientException(_('The uploaded file was only' .
189                 ' partially uploaded.'));
190             return;
191         case UPLOAD_ERR_NO_TMP_DIR:
192             throw new ClientException(_('Missing a temporary folder.'));
193             return;
194         case UPLOAD_ERR_CANT_WRITE:
195             throw new ClientException(_('Failed to write file to disk.'));
196             return;
197         case UPLOAD_ERR_EXTENSION:
198             throw new ClientException(_('File upload stopped by extension.'));
199             return;
200         default:
201             throw new ClientException(_('System error uploading file.'));
202             return;
203         }
204
205         if (!MediaFile::respectsQuota($user, $_FILES['attach']['size'])) {
206
207             // Should never actually get here
208
209             @unlink($_FILES[$param]['tmp_name']);
210             throw new ClientException(_('File exceeds user\'s quota!'));
211             return;
212         }
213
214         $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name']);
215
216         $filename = null;
217
218         if (isset($mimetype)) {
219
220             $basename = basename($_FILES[$param]['name']);
221             $filename = File::filename($user->getProfile(), $basename, $mimetype);
222             $filepath = File::path($filename);
223
224             common_debug("filepath = " . $filepath);
225
226             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
227
228             if (!$result) {
229                 throw new ClientException(_('File could not be moved to destination directory.'));
230                 return;
231             }
232
233         } else {
234             throw new ClientException(_('Could not determine file\'s mime-type!'));
235             return;
236         }
237
238         return new MediaFile($user, $filename, $mimetype);
239     }
240
241     static function fromFilehandle($fh, $user) {
242
243         $stream = stream_get_meta_data($fh);
244
245         if (MediaFile::respectsQuota($user, filesize($stream['uri']))) {
246
247             // Should never actually get here
248
249             throw new ClientException(_('File exceeds user\'s quota!'));
250             return;
251         }
252
253         $mimetype = MediaFile::getUploadedFileType($fh);
254
255         $filename = null;
256
257         if (isset($mimetype)) {
258
259             $filename = File::filename($user->getProfile(), "email", $mimetype);
260
261             $filepath = File::path($filename);
262
263             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
264
265             if (!$result) {
266                 throw new ClientException(_('File could not be moved to destination directory.' .
267                     $stream['uri'] . ' ' . $filepath));
268             }
269         } else {
270             throw new ClientException(_('Could not determine file\'s mime-type!'));
271             return;
272         }
273
274         return new MediaFile($user, $filename, $mimetype);
275     }
276
277     static function getUploadedFileType($f) {
278         require_once 'MIME/Type.php';
279
280         common_debug("in getUploadedFileType");
281
282         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
283         $cmd = common_config('attachments', 'filecommand');
284
285         $filetype = null;
286
287         if (is_string($f)) {
288
289             // assuming a filename
290
291             $filetype = MIME_Type::autoDetect($f);
292         } else {
293
294             // assuming a filehandle
295
296             $stream  = stream_get_meta_data($f);
297             $filetype = MIME_Type::autoDetect($stream['uri']);
298         }
299
300         if (in_array($filetype, common_config('attachments', 'supported'))) {
301             return $filetype;
302         }
303         $media = MIME_Type::getMedia($filetype);
304         if ('application' !== $media) {
305             $hint = sprintf(_(' Try using another %s format.'), $media);
306         } else {
307             $hint = '';
308         }
309         throw new ClientException(sprintf(
310             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
311     }
312
313     static function respectsQuota($user, $filesize)
314     {
315         $file = new File;
316         $result = $file->isRespectsQuota($user, $filesize);
317         if ($result === true) {
318             return true;
319         } else {
320             throw new ClientException($result);
321         }
322     }
323
324 }