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