]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
Handle reuploads via filehandle better if original is missing
[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             $basename = basename($_FILES[$param]['name']);
257
258             switch (common_config('attachments', 'filename_base')) {
259             case 'upload':
260                 $filename = File::filename($scoped, $basename, $mimetype);
261                 break;
262             case 'hash':
263             default:
264                 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype, $basename);
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             // by using getPath we also check whether the file exists
290             // and throw a FileNotFoundException with the path if it doesn't.
291             $filename = basename($file->getPath());
292             $mimetype = $file->mimetype;
293         } catch (FileNotFoundException $e) {
294             // This happens if the file we have uploaded has disappeared
295             // from the local filesystem for some reason. Since we got the
296             // File object from a sha256 check in fromFilehandle, it's safe
297             // to just copy the uploaded data to disk!
298
299             fseek($fh, 0);  // just to be sure, go to the beginning
300             // dump the contents of our filehandle to the path from our exception
301             // and report error if it failed.
302             if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
303                 // TRANS: Client exception thrown when a file upload operation fails because the file could
304                 // TRANS: not be moved from the temporary folder to the permanent file location.
305                 throw new ClientException(_('File could not be moved to destination directory.'));
306             }
307             if (!chmod($e->path, 0664)) {
308                 common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
309             }
310
311             $filename = basename($file->getPath());
312             $mimetype = $file->mimetype;
313
314         } catch (NoResultException $e) {
315             File::respectsQuota($scoped, filesize($stream['uri']));
316
317             $mimetype = self::getUploadedMimeType($stream['uri']);
318
319             switch (common_config('attachments', 'filename_base')) {
320             case 'upload':
321                 $filename = File::filename($scoped, "email", $mimetype);
322                 break;
323             case 'hash':
324             default:
325                 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
326             }
327             $filepath = File::path($filename);
328
329             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
330
331             if (!$result) {
332                 common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
333                 // TRANS: Client exception thrown when a file upload operation fails because the file could
334                 // TRANS: not be moved from the temporary folder to the permanent file location.
335                 throw new ClientException(_('File could not be moved to destination directory.' ));
336             }
337         }
338
339         return new MediaFile($scoped, $filename, $mimetype, $filehash);
340     }
341
342     /**
343      * Attempt to identify the content type of a given file.
344      * 
345      * @param string $filepath filesystem path as string (file must exist)
346      * @param string $originalFilename (optional) for extension-based detection
347      * @return string
348      * 
349      * @fixme this seems to tie a front-end error message in, kinda confusing
350      * 
351      * @throws ClientException if type is known, but not supported for local uploads
352      */
353     static function getUploadedMimeType($filepath, $originalFilename=false) {
354         // We only accept filenames to existing files
355         $mimelookup = new finfo(FILEINFO_MIME_TYPE);
356         $mimetype = $mimelookup->file($filepath);
357
358         // Unclear types are such that we can't really tell by the auto
359         // detect what they are (.bin, .exe etc. are just "octet-stream")
360         $unclearTypes = array('application/octet-stream',
361                               'application/vnd.ms-office',
362                               'application/zip',
363                               'text/html',  // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
364                               // TODO: for XML we could do better content-based sniffing too
365                               'text/xml');
366
367         $supported = common_config('attachments', 'supported');
368
369         // If we didn't match, or it is an unclear match
370         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
371             try {
372                 $type = common_supported_ext_to_mime($originalFilename);
373                 return $type;
374             } catch (Exception $e) {
375                 // Extension not found, so $mimetype is our best guess
376             }
377         }
378
379         // If $config['attachments']['supported'] equals boolean true, accept any mimetype
380         if ($supported === true || array_key_exists($mimetype, $supported)) {
381             // FIXME: Don't know if it always has a mimetype here because
382             // finfo->file CAN return false on error: http://php.net/finfo_file
383             // so if $supported === true, this may return something unexpected.
384             return $mimetype;
385         }
386
387         // We can conclude that we have failed to get the MIME type
388         $media = common_get_mime_media($mimetype);
389         if ('application' !== $media) {
390             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
391             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
392             // TRANS: the MIME type that was denied.
393             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
394             'Try using another %2$s format.'), $mimetype, $media);
395         } else {
396             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
397             // TRANS: %s is the file type that was denied.
398             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
399         }
400         throw new ClientException($hint);
401     }
402 }