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