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