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