]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
common_fake_local_fancy_url to remove index.php/ from a local URL
[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, $filehash = null)
46     {
47         $this->scoped = $scoped;
48
49         $this->filename   = $filename;
50         $this->mimetype   = $mimetype;
51         $this->filehash   = $filehash;
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     public function attachToNotice(Notice $notice)
63     {
64         File_to_post::processNew($this->fileRecord, $notice);
65     }
66
67     public function getPath()
68     {
69         return File::path($this->filename);
70     }
71
72     function shortUrl()
73     {
74         return $this->short_fileurl;
75     }
76
77     function getEnclosure()
78     {
79         return $this->getFile()->getEnclosure();
80     }
81
82     function delete()
83     {
84         $filepath = File::path($this->filename);
85         @unlink($filepath);
86     }
87
88     public function getFile()
89     {
90         if (!$this->fileRecord instanceof File) {
91             throw new ServerException('File record did not exist for MediaFile');
92         }
93
94         return $this->fileRecord;
95     }
96
97     protected function storeFile()
98     {
99         $filepath       = File::path($this->filename);
100         if (!empty($this->filename) && $this->filehash === null) {
101             // Calculate if we have an older upload method somewhere (Qvitter) that
102             // doesn't do this before calling new MediaFile on its local files...
103             $this->filehash = hash_file(File::FILEHASH_ALG, $filepath);
104             if ($this->filehash === false) {
105                 throw new ServerException('Could not read file for hashing');
106             }
107         }
108
109         try {
110             $file = File::getByHash($this->filehash);
111             // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
112             return $file;
113         } catch (NoResultException $e) {
114             // Well, let's just continue below.
115         }
116
117         $fileurl = File::url($this->filename);
118
119         $file = new File;
120
121         $file->filename = $this->filename;
122         $file->urlhash  = File::hashurl($fileurl);
123         $file->url      = $fileurl;
124         $file->filehash = $this->filehash;
125         $file->size     = filesize($filepath);
126         if ($file->size === false) {
127             throw new ServerException('Could not read file to get its size');
128         }
129         $file->date     = time();
130         $file->mimetype = $this->mimetype;
131
132
133         $file_id = $file->insert();
134
135         if ($file_id===false) {
136             common_log_db_error($file, "INSERT", __FILE__);
137             // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
138             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
139         }
140
141         // Set file geometrical properties if available
142         try {
143             $image = ImageFile::fromFileObject($file);
144             $orig = clone($file);
145             $file->width = $image->width;
146             $file->height = $image->height;
147             $file->update($orig);
148
149             // We have to cleanup after ImageFile, since it
150             // may have generated a temporary file from a
151             // video support plugin or something.
152             // FIXME: Do this more automagically.
153             if ($image->getPath() != $file->getPath()) {
154                 $image->unlink();
155             }
156         } catch (ServerException $e) {
157             // We just couldn't make out an image from the file. This
158             // does not have to be UnsupportedMediaException, as we can
159             // also get ServerException from files not existing etc.
160         }
161
162         return $file;
163     }
164
165     function rememberFile($file, $short)
166     {
167         $this->maybeAddRedir($file->id, $short);
168     }
169
170     function maybeAddRedir($file_id, $url)
171     {
172         try {
173             $file_redir = File_redirection::getByUrl($url);
174         } catch (NoResultException $e) {
175             $file_redir = new File_redirection;
176             $file_redir->urlhash = File::hashurl($url);
177             $file_redir->url = $url;
178             $file_redir->file_id = $file_id;
179
180             $result = $file_redir->insert();
181
182             if ($result===false) {
183                 common_log_db_error($file_redir, "INSERT", __FILE__);
184                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
185                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
186             }
187         }
188     }
189
190     static function fromUpload($param='media', Profile $scoped=null)
191     {
192         if (is_null($scoped)) {
193             $scoped = Profile::current();
194         }
195
196         // The existence of the "error" element means PHP has processed it properly even if it was ok.
197         if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
198             throw new NoUploadedMediaException($param);
199         }
200
201         switch ($_FILES[$param]['error']) {
202             case UPLOAD_ERR_OK: // success, jump out
203                 break;
204             case UPLOAD_ERR_INI_SIZE:
205                 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
206                 throw new ClientException(_('The uploaded file exceeds the ' .
207                             'upload_max_filesize directive in php.ini.'));
208             case UPLOAD_ERR_FORM_SIZE:
209                 throw new ClientException(
210                         // TRANS: Client exception.
211                         _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
212                             ' that was specified in the HTML form.'));
213             case UPLOAD_ERR_PARTIAL:
214                 @unlink($_FILES[$param]['tmp_name']);
215                 // TRANS: Client exception.
216                 throw new ClientException(_('The uploaded file was only' .
217                             ' partially uploaded.'));
218             case UPLOAD_ERR_NO_FILE:
219                 // No file; probably just a non-AJAX submission.
220                 throw new NoUploadedMediaException($param);
221             case UPLOAD_ERR_NO_TMP_DIR:
222                 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
223                 throw new ClientException(_('Missing a temporary folder.'));
224             case UPLOAD_ERR_CANT_WRITE:
225                 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
226                 throw new ClientException(_('Failed to write file to disk.'));
227             case UPLOAD_ERR_EXTENSION:
228                 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
229                 throw new ClientException(_('File upload stopped by extension.'));
230             default:
231                 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
232                         $_FILES[$param]['error']);
233                 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
234                 throw new ClientException(_('System error uploading file.'));
235         }
236
237         // TODO: Make documentation clearer that this won't work for files >2GiB because
238         //       PHP is stupid in its 32bit head. But noone accepts 2GiB files with PHP
239         //       anyway... I hope.
240         $filehash = hash_file(File::FILEHASH_ALG, $_FILES[$param]['tmp_name']);
241
242         try {
243             $file = File::getByHash($filehash);
244             // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
245             $filename = $file->filename;
246             $mimetype = $file->mimetype;
247
248         } catch (NoResultException $e) {
249             // We have to save the upload as a new local file. This is the normal course of action.
250
251             // Throws exception if additional size does not respect quota
252             // This test is only needed, of course, if we're uploading something new.
253             File::respectsQuota($scoped, $_FILES[$param]['size']);
254
255             $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
256
257             switch (common_config('attachments', 'filename_base')) {
258             case 'upload':
259                 $basename = basename($_FILES[$param]['name']);
260                 $filename = File::filename($scoped, $basename, $mimetype);
261                 break;
262             case 'hash':
263             default:
264                 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype); 
265             }
266             $filepath = File::path($filename);
267
268             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
269
270             if (!$result) {
271                 // TRANS: Client exception thrown when a file upload operation fails because the file could
272                 // TRANS: not be moved from the temporary folder to the permanent file location.
273                 throw new ClientException(_('File could not be moved to destination directory.'));
274             }
275         }
276
277         return new MediaFile($scoped, $filename, $mimetype, $filehash);
278     }
279
280     static function fromFilehandle($fh, Profile $scoped) {
281         $stream = stream_get_meta_data($fh);
282         // So far we're only handling filehandles originating from tmpfile(),
283         // so we can always do hash_file on $stream['uri'] as far as I can tell!
284         $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
285
286         try {
287             $file = File::getByHash($filehash);
288             // Already have it, so let's reuse the locally stored File
289             $filename = $file->filename;
290             $mimetype = $file->mimetype;
291         } catch (NoResultException $e) {
292             File::respectsQuota($scoped, filesize($stream['uri']));
293
294             $mimetype = self::getUploadedMimeType($stream['uri']);
295
296             switch (common_config('attachments', 'filename_base')) {
297             case 'upload':
298                 $filename = File::filename($scoped, "email", $mimetype);
299                 break;
300             case 'hash':
301             default:
302                 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
303             }
304             $filepath = File::path($filename);
305
306             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
307
308             if (!$result) {
309                 // TRANS: Client exception thrown when a file upload operation fails because the file could
310                 // TRANS: not be moved from the temporary folder to the permanent file location.
311                 throw new ClientException(_('File could not be moved to destination directory.' .
312                     $stream['uri'] . ' ' . $filepath));
313             }
314         }
315
316         return new MediaFile($scoped, $filename, $mimetype, $filehash);
317     }
318
319     /**
320      * Attempt to identify the content type of a given file.
321      * 
322      * @param string $filepath filesystem path as string (file must exist)
323      * @param string $originalFilename (optional) for extension-based detection
324      * @return string
325      * 
326      * @fixme this seems to tie a front-end error message in, kinda confusing
327      * 
328      * @throws ClientException if type is known, but not supported for local uploads
329      */
330     static function getUploadedMimeType($filepath, $originalFilename=false) {
331         // We only accept filenames to existing files
332         $mimelookup = new finfo(FILEINFO_MIME_TYPE);
333         $mimetype = $mimelookup->file($filepath);
334
335         // Unclear types are such that we can't really tell by the auto
336         // detect what they are (.bin, .exe etc. are just "octet-stream")
337         $unclearTypes = array('application/octet-stream',
338                               'application/vnd.ms-office',
339                               'application/zip',
340                               'text/html',  // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
341                               // TODO: for XML we could do better content-based sniffing too
342                               'text/xml');
343
344         $supported = common_config('attachments', 'supported');
345
346         // If we didn't match, or it is an unclear match
347         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
348             try {
349                 $type = common_supported_ext_to_mime($originalFilename);
350                 return $type;
351             } catch (Exception $e) {
352                 // Extension not found, so $mimetype is our best guess
353             }
354         }
355
356         // If $config['attachments']['supported'] equals boolean true, accept any mimetype
357         if ($supported === true || array_key_exists($mimetype, $supported)) {
358             // FIXME: Don't know if it always has a mimetype here because
359             // finfo->file CAN return false on error: http://php.net/finfo_file
360             // so if $supported === true, this may return something unexpected.
361             return $mimetype;
362         }
363
364         // We can conclude that we have failed to get the MIME type
365         $media = common_get_mime_media($mimetype);
366         if ('application' !== $media) {
367             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
368             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
369             // TRANS: the MIME type that was denied.
370             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
371             'Try using another %2$s format.'), $mimetype, $media);
372         } else {
373             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
374             // TRANS: %s is the file type that was denied.
375             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
376         }
377         throw new ClientException($hint);
378     }
379 }