]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
e1a9d1247c9001f5b29d164317db5fffcd5ca830
[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('GNUSOCIAL')) { exit(1); }
34
35 class MediaFile
36 {
37     protected $scoped   = null;
38
39     var $filename      = null;
40     var $fileRecord    = null;
41     var $fileurl       = null;
42     var $short_fileurl = null;
43     var $mimetype      = null;
44
45     function __construct(Profile $scoped, $filename = null, $mimetype = null)
46     {
47         $this->scoped = $scoped;
48
49         $this->filename   = $filename;
50         $this->mimetype   = $mimetype;
51         $this->fileRecord = $this->storeFile();
52
53         $this->fileurl = common_local_url('attachment',
54                                     array('attachment' => $this->fileRecord->id));
55
56         $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
57         $this->short_fileurl = common_shorten_url($this->fileurl);
58         $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
59     }
60
61     public function attachToNotice(Notice $notice)
62     {
63         File_to_post::processNew($this->fileRecord->id, $notice->id);
64         $this->maybeAddRedir($this->fileRecord->id,
65                              common_local_url('file', array('notice' => $notice->id)));
66     }
67
68     public function getPath()
69     {
70         return File::path($this->filename);
71     }
72
73     function shortUrl()
74     {
75         return $this->short_fileurl;
76     }
77
78     function delete()
79     {
80         $filepath = File::path($this->filename);
81         @unlink($filepath);
82     }
83
84     function storeFile() {
85
86         $file = new File;
87
88         $file->filename = $this->filename;
89         $file->url      = File::url($this->filename);
90         $filepath       = File::path($this->filename);
91         $file->size     = filesize($filepath);
92         $file->date     = time();
93         $file->mimetype = $this->mimetype;
94
95         $file_id = $file->insert();
96
97         if (!$file_id) {
98             common_log_db_error($file, "INSERT", __FILE__);
99             // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
100             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
101         }
102
103         return $file;
104     }
105
106     function rememberFile($file, $short)
107     {
108         $this->maybeAddRedir($file->id, $short);
109     }
110
111     function maybeAddRedir($file_id, $url)
112     {
113         $file_redir = File_redirection::getKV('url', $url);
114
115         if (empty($file_redir)) {
116
117             $file_redir = new File_redirection;
118             $file_redir->url = $url;
119             $file_redir->file_id = $file_id;
120
121             $result = $file_redir->insert();
122
123             if (!$result) {
124                 common_log_db_error($file_redir, "INSERT", __FILE__);
125                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
126                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
127             }
128         }
129     }
130
131     static function fromUpload($param = 'media', Profile $scoped)
132     {
133         if (is_null($scoped)) {
134             $scoped = Profile::current();
135         }
136
137         if (!isset($_FILES[$param]['error'])){
138             return;
139         }
140
141         switch ($_FILES[$param]['error']) {
142         case UPLOAD_ERR_OK: // success, jump out
143             break;
144         case UPLOAD_ERR_INI_SIZE:
145             // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
146             throw new ClientException(_('The uploaded file exceeds the ' .
147                 'upload_max_filesize directive in php.ini.'));
148         case UPLOAD_ERR_FORM_SIZE:
149             throw new ClientException(
150                 // TRANS: Client exception.
151                 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
152                 ' that was specified in the HTML form.'));
153         case UPLOAD_ERR_PARTIAL:
154             @unlink($_FILES[$param]['tmp_name']);
155             // TRANS: Client exception.
156             throw new ClientException(_('The uploaded file was only' .
157                 ' partially uploaded.'));
158         case UPLOAD_ERR_NO_FILE:
159             // No file; probably just a non-AJAX submission.
160             return;
161         case UPLOAD_ERR_NO_TMP_DIR:
162             // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
163             throw new ClientException(_('Missing a temporary folder.'));
164         case UPLOAD_ERR_CANT_WRITE:
165             // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
166             throw new ClientException(_('Failed to write file to disk.'));
167         case UPLOAD_ERR_EXTENSION:
168             // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
169             throw new ClientException(_('File upload stopped by extension.'));
170         default:
171             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
172                 $_FILES[$param]['error']);
173             // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
174             throw new ClientException(_('System error uploading file.'));
175         }
176
177         // Throws exception if additional size does not respect quota
178         File::respectsQuota($scoped, $_FILES[$param]['size']);
179
180         $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
181                                                    $_FILES[$param]['name']);
182
183         $basename = basename($_FILES[$param]['name']);
184         $filename = File::filename($scoped, $basename, $mimetype);
185         $filepath = File::path($filename);
186
187         $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
188
189         if (!$result) {
190             // TRANS: Client exception thrown when a file upload operation fails because the file could
191             // TRANS: not be moved from the temporary folder to the permanent file location.
192             throw new ClientException(_('File could not be moved to destination directory.'));
193         }
194
195         return new MediaFile($scoped, $filename, $mimetype);
196     }
197
198     static function fromFilehandle($fh, Profile $scoped) {
199
200         $stream = stream_get_meta_data($fh);
201
202         File::respectsQuota($scoped, filesize($stream['uri']));
203
204         $mimetype = self::getUploadedMimeType($stream['uri']);
205
206         $filename = File::filename($scoped, "email", $mimetype);
207
208         $filepath = File::path($filename);
209
210         $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
211
212         if (!$result) {
213             // TRANS: Client exception thrown when a file upload operation fails because the file could
214             // TRANS: not be moved from the temporary folder to the permanent file location.
215             throw new ClientException(_('File could not be moved to destination directory.' .
216                 $stream['uri'] . ' ' . $filepath));
217         }
218
219         return new MediaFile($scoped, $filename, $mimetype);
220     }
221
222     /**
223      * Attempt to identify the content type of a given file.
224      * 
225      * @param string $filepath filesystem path as string (file must exist)
226      * @param string $originalFilename (optional) for extension-based detection
227      * @return string
228      * 
229      * @fixme this seems to tie a front-end error message in, kinda confusing
230      * 
231      * @throws ClientException if type is known, but not supported for local uploads
232      */
233     static function getUploadedMimeType($filepath, $originalFilename=false) {
234         // We only accept filenames to existing files
235         $mimelookup = new finfo(FILEINFO_MIME_TYPE);
236         $mimetype = $mimelookup->file($filepath);
237
238         // Unclear types are such that we can't really tell by the auto
239         // detect what they are (.bin, .exe etc. are just "octet-stream")
240         $unclearTypes = array('application/octet-stream',
241                               'application/vnd.ms-office',
242                               'application/zip',
243                               // TODO: for XML we could do better content-based sniffing too
244                               'text/xml');
245
246         $supported = common_config('attachments', 'supported');
247
248         // If we didn't match, or it is an unclear match
249         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
250             try {
251                 $type = common_supported_ext_to_mime($originalFilename);
252                 return $type;
253             } catch (Exception $e) {
254                 // Extension not found, so $mimetype is our best guess
255             }
256         }
257
258         // If $config['attachments']['supported'] equals boolean true, accept any mimetype
259         if ($supported === true || array_key_exists($mimetype, $supported)) {
260             // FIXME: Don't know if it always has a mimetype here because
261             // finfo->file CAN return false on error: http://php.net/finfo_file
262             // so if $supported === true, this may return something unexpected.
263             return $mimetype;
264         }
265
266         // We can conclude that we have failed to get the MIME type
267         $media = common_get_mime_media($mimetype);
268         if ('application' !== $media) {
269             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
270             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
271             // TRANS: the MIME type that was denied.
272             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
273             'Try using another %2$s format.'), $mimetype, $media);
274         } else {
275             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
276             // TRANS: %s is the file type that was denied.
277             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
278         }
279         throw new ClientException($hint);
280     }
281 }