]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
[MEDIA] ImageFile now extends MediaFile and validates images more aggressively.
[quix0rs-gnu-social.git] / lib / mediafile.php
1 <?php
2 /**
3  * GNU social - a federating social network
4  *
5  * Abstraction for media files
6  *
7  * LICENCE: This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Media
21  * @package   GNUsocial
22  * @author    Robin Millette <robin@millette.info>
23  * @author    Miguel Dantas <biodantas@gmail.com>
24  * @author    Zach Copley <zach@status.net>
25  * @author    Mikael Nordfeldth <mmn@hethane.se>
26  * @copyright 2008-2009, 2019 Free Software Foundation http://fsf.org
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      https://www.gnu.org/software/social/
29  */
30
31 if (!defined('GNUSOCIAL')) { exit(1); }
32
33
34 /**
35  * Class responsible for abstracting media files
36  */
37 class MediaFile
38 {
39     public $id            = null;
40     public $filepath      = null;
41     public $filename      = null;
42     public $fileRecord    = null;
43     public $fileurl       = null;
44     public $short_fileurl = null;
45     public $mimetype      = null;
46
47     /**
48      * @param string $filepath The path of the file this media refers to. Required
49      * @param string $mimetype The mimetype of the file. Required
50      * @param $filehash        The hash of the file, if known. Optional
51      * @param int|null $id     The DB id of the file. Int if known, null if not.
52      *                         If null, it searches for it. If -1, it skips all DB
53      *                         interactions (useful for temporary objects)
54      * @throws ClientException
55      * @throws NoResultException
56      * @throws ServerException
57      */
58     public function __construct(string $filepath, string $mimetype, $filehash = null, $id = null)
59     {
60         $this->filepath = $filepath;
61         $this->filename = basename($this->filepath);
62         $this->mimetype = $mimetype;
63         $this->filehash = self::getHashOfFile($this->filepath, $filehash);
64         $this->id       = $id;
65
66         // If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB,
67         // or add redirects
68         if ($this->id !== -1) {
69             if (!empty($this->id)) {
70                 // If we have an id, load it
71                 $this->fileRecord = new File();
72                 $this->fileRecord->id = $this->id;
73                 if (!$this->fileRecord->find(true)) {
74                     // If we have set an ID, we need that ID to exist!
75                     throw new NoResultException($this->fileRecord);
76                 }
77             } else {
78                 // Otherwise, store it
79                 $this->fileRecord = $this->storeFile();
80             }
81
82             $this->fileurl = common_local_url(
83                 'attachment',
84                 array('attachment' => $this->fileRecord->id)
85             );
86
87             $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
88             $this->short_fileurl = common_shorten_url($this->fileurl);
89             $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
90         }
91     }
92
93     public function attachToNotice(Notice $notice)
94     {
95         File_to_post::processNew($this->fileRecord, $notice);
96     }
97
98     public function getPath()
99     {
100         return File::path($this->filename);
101     }
102
103     function shortUrl()
104     {
105         return $this->short_fileurl;
106     }
107
108     function getEnclosure()
109     {
110         return $this->getFile()->getEnclosure();
111     }
112
113     function delete()
114     {
115         @unlink($this->filepath);
116     }
117
118     public function getFile()
119     {
120         if (!$this->fileRecord instanceof File) {
121             throw new ServerException('File record did not exist for MediaFile');
122         }
123
124         return $this->fileRecord;
125     }
126
127     /**
128      * Calculate the hash of a file.
129      *
130      * This won't work for files >2GiB because PHP uses only 32bit.
131      * @param string $filepath
132      * @param string|null $filehash
133      * @return string
134      * @throws ServerException
135      */
136     public static function getHashOfFile(string $filepath, $filehash = null)
137     {
138         assert(!empty($filepath), __METHOD__ . ": filepath cannot be null");
139         if ($filehash === null) {
140             // Calculate if we have an older upload method somewhere (Qvitter) that
141             // doesn't do this before calling new MediaFile on its local files...
142             $filehash = hash_file(File::FILEHASH_ALG, $filepath);
143             if ($filehash === false) {
144                 throw new ServerException('Could not read file for hashing');
145             }
146         }
147         return $filehash;
148     }
149
150     /**
151      * Retrieve or insert as a file in the DB
152      *
153      * @return object File
154      * @throws ClientException
155      * @throws ServerException
156      */
157     protected function storeFile()
158     {
159         try {
160             $file = File::getByHash($this->filehash);
161             // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
162             return $file;
163         } catch (NoResultException $e) {
164             // Well, let's just continue below.
165         }
166
167         $fileurl = File::url($this->filename);
168
169         $file = new File;
170
171         $file->filename = $this->filename;
172         $file->urlhash  = File::hashurl($fileurl);
173         $file->url      = $fileurl;
174         $file->filehash = $this->filehash;
175         $file->size     = filesize($this->filepath);
176         if ($file->size === false) {
177             throw new ServerException('Could not read file to get its size');
178         }
179         $file->date     = time();
180         $file->mimetype = $this->mimetype;
181
182         $file_id = $file->insert();
183
184         if ($file_id===false) {
185             common_log_db_error($file, "INSERT", __FILE__);
186             // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
187             throw new ClientException(_('There was a database error while saving your file. Please try again.'));
188         }
189
190         // Set file geometrical properties if available
191         try {
192             $image = ImageFile::fromFileObject($file);
193             $orig = clone($file);
194             $file->width = $image->width;
195             $file->height = $image->height;
196             $file->update($orig);
197
198             // We have to cleanup after ImageFile, since it
199             // may have generated a temporary file from a
200             // video support plugin or something.
201             // FIXME: Do this more automagically.
202             if ($image->getPath() != $file->getPath()) {
203                 $image->unlink();
204             }
205         } catch (ServerException $e) {
206             // We just couldn't make out an image from the file. This
207             // does not have to be UnsupportedMediaException, as we can
208             // also get ServerException from files not existing etc.
209         }
210
211         return $file;
212     }
213
214     function rememberFile($file, $short)
215     {
216         $this->maybeAddRedir($file->id, $short);
217     }
218
219     /**
220      * Adds Redir if needed.
221      *
222      * @param $file_id
223      * @param $url
224      * @return bool false if no need to add, true if added
225      * @throws ClientException If failed adding
226      */
227     public function maybeAddRedir($file_id, $url)
228     {
229         try {
230             File_redirection::getByUrl($url);
231             return false;
232         } catch (NoResultException $e) {
233             $file_redir = new File_redirection;
234             $file_redir->urlhash = File::hashurl($url);
235             $file_redir->url = $url;
236             $file_redir->file_id = $file_id;
237
238             $result = $file_redir->insert();
239
240             if ($result===false) {
241                 common_log_db_error($file_redir, "INSERT", __FILE__);
242                 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
243                 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
244             }
245             return $result;
246         }
247     }
248
249     /**
250      * The maximum allowed file size, as a string
251      */
252     static function maxFileSize()
253     {
254         $value = self::maxFileSizeInt();
255         if ($value > 1024 * 1024) {
256             $value = $value/(1024*1024);
257             // TRANS: Number of megabytes. %d is the number.
258             return sprintf(_m('%dMB','%dMB',$value),$value);
259         } else if ($value > 1024) {
260             $value = $value/1024;
261             // TRANS: Number of kilobytes. %d is the number.
262             return sprintf(_m('%dkB','%dkB',$value),$value);
263         } else {
264             // TRANS: Number of bytes. %d is the number.
265             return sprintf(_m('%dB','%dB',$value),$value);
266         }
267     }
268
269     /**
270      * The maximum allowed file size, as an int
271      */
272     static function maxFileSizeInt()
273     {
274         return min(self::sizeStrToInt(ini_get('post_max_size')),
275                    self::sizeStrToInt(ini_get('upload_max_filesize')),
276                    self::sizeStrToInt(ini_get('memory_limit')));
277     }
278
279     /**
280      * Convert a string representing a file size (with units), to an int
281      * @param $str
282      * @return bool|int|string
283      */
284     public static function sizeStrToInt($str)
285     {
286         $unit = substr($str, -1);
287         $num = substr($str, 0, -1);
288         switch(strtoupper($unit)){
289         case 'G':
290             $num *= 1024;
291         case 'M':
292             $num *= 1024;
293         case 'K':
294             $num *= 1024;
295         }
296         return $num;
297     }
298
299     /**
300      * Create a new MediaFile or ImageFile object from an upload
301      *
302      * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
303      * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
304      * @param string $param
305      * @param Profile|null $scoped
306      * @return ImageFile|MediaFile
307      * @throws ClientException
308      * @throws NoResultException
309      * @throws NoUploadedMediaException
310      * @throws ServerException
311      * @throws UnsupportedMediaException
312      * @throws UseFileAsThumbnailException
313      */
314     public static function fromUpload(string $param='media', Profile $scoped=null)
315     {
316         // The existence of the "error" element means PHP has processed it properly even if it was ok.
317         if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
318             throw new NoUploadedMediaException($param);
319         }
320
321         switch ($_FILES[$param]['error']) {
322             case UPLOAD_ERR_OK: // success, jump out
323                 break;
324             case UPLOAD_ERR_INI_SIZE:
325             case UPLOAD_ERR_FORM_SIZE:
326                 // TRANS: Exception thrown when too large a file is uploaded.
327                 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
328                 throw new ClientException(sprintf(_('That file is too big. The maximum file size is %s.'),
329                                                   self::maxFileSize()));
330             case UPLOAD_ERR_PARTIAL:
331                 @unlink($_FILES[$param]['tmp_name']);
332                 // TRANS: Client exception.
333                 throw new ClientException(_('The uploaded file was only partially uploaded.'));
334             case UPLOAD_ERR_NO_FILE:
335                 // No file; probably just a non-AJAX submission.
336                 throw new NoUploadedMediaException($param);
337             case UPLOAD_ERR_NO_TMP_DIR:
338                 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
339                 throw new ClientException(_('Missing a temporary folder.'));
340             case UPLOAD_ERR_CANT_WRITE:
341                 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
342                 throw new ClientException(_('Failed to write file to disk.'));
343             case UPLOAD_ERR_EXTENSION:
344                 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
345                 throw new ClientException(_('File upload stopped by extension.'));
346             default:
347                 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
348                 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
349                 throw new ClientException(_('System error uploading file.'));
350         }
351
352         $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
353
354         try {
355             $file = File::getByHash($filehash);
356             // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
357             // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
358             $filepath = $file->getPath();
359             $mimetype = $file->mimetype;
360         // XXX PHP: Upgrade to PHP 7.1
361         // catch (FileNotFoundException | NoResultException $e)
362         } catch (Exception $e) {
363             // We have to save the upload as a new local file. This is the normal course of action.
364             if ($scoped instanceof Profile) {
365                 // Throws exception if additional size does not respect quota
366                 // This test is only needed, of course, if we're uploading something new.
367                 File::respectsQuota($scoped, $_FILES[$param]['size']);
368             }
369
370             $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
371             $media = common_get_mime_media($mimetype);
372
373             $basename = basename($_FILES[$param]['name']);
374             $filename = $filehash . '.' . File::guessMimeExtension($mimetype, $basename);
375             $filepath = File::path($filename);
376             $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
377
378             if (!$result) {
379                 // TRANS: Client exception thrown when a file upload operation fails because the file could
380                 // TRANS: not be moved from the temporary folder to the permanent file location.
381                 // UX: too specific
382                 throw new ClientException(_('File could not be moved to destination directory.'));
383             }
384
385             if ($media === 'image') {
386                 // Use -1 for the id to avoid adding this temporary file to the DB
387                 $img = new ImageFile(-1, $filepath);
388                 // Validate the image by reencoding it. Additionally normalizes old formats to PNG,
389                 // keeping JPEG and GIF untouched
390                 $outpath = $img->resizeTo($img->filepath);
391                 $ext = image_type_to_extension($img->preferredType());
392                 $filename = $filehash . $ext;
393                 $filepath = File::path($filename);
394                 $result = rename($outpath, $filepath);
395                 return new ImageFile(null, $filepath);
396             }
397         }
398         return new MediaFile($filepath, $mimetype, $filehash);
399     }
400
401     static function fromFilehandle($fh, Profile $scoped=null) {
402         $stream = stream_get_meta_data($fh);
403         // So far we're only handling filehandles originating from tmpfile(),
404         // so we can always do hash_file on $stream['uri'] as far as I can tell!
405         $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
406
407         try {
408             $file = File::getByHash($filehash);
409             // Already have it, so let's reuse the locally stored File
410             // by using getPath we also check whether the file exists
411             // and throw a FileNotFoundException with the path if it doesn't.
412             $filename = basename($file->getPath());
413             $mimetype = $file->mimetype;
414         } catch (FileNotFoundException $e) {
415             // This happens if the file we have uploaded has disappeared
416             // from the local filesystem for some reason. Since we got the
417             // File object from a sha256 check in fromFilehandle, it's safe
418             // to just copy the uploaded data to disk!
419
420             fseek($fh, 0);  // just to be sure, go to the beginning
421             // dump the contents of our filehandle to the path from our exception
422             // and report error if it failed.
423             if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
424                 // TRANS: Client exception thrown when a file upload operation fails because the file could
425                 // TRANS: not be moved from the temporary folder to the permanent file location.
426                 throw new ClientException(_('File could not be moved to destination directory.'));
427             }
428             if (!chmod($e->path, 0664)) {
429                 common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
430             }
431
432             $filename = basename($file->getPath());
433             $mimetype = $file->mimetype;
434
435         } catch (NoResultException $e) {
436             if ($scoped instanceof Profile) {
437                 File::respectsQuota($scoped, filesize($stream['uri']));
438             }
439
440             $mimetype = self::getUploadedMimeType($stream['uri']);
441
442             $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
443             $filepath = File::path($filename);
444
445             $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
446
447             if (!$result) {
448                 common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
449                 // TRANS: Client exception thrown when a file upload operation fails because the file could
450                 // TRANS: not be moved from the temporary folder to the permanent file location.
451                 throw new ClientException(_('File could not be moved to destination directory.' ));
452             }
453         }
454
455         return new MediaFile($filename, $mimetype, $filehash);
456     }
457
458     /**
459      * Attempt to identify the content type of a given file.
460      *
461      * @param string $filepath filesystem path as string (file must exist)
462      * @param bool $originalFilename (optional) for extension-based detection
463      * @return string
464      *
465      * @throws ClientException if type is known, but not supported for local uploads
466      * @throws ServerException
467      * @fixme this seems to tie a front-end error message in, kinda confusing
468      *
469      */
470     static function getUploadedMimeType(string $filepath, $originalFilename=false) {
471         // We only accept filenames to existing files
472
473         $mimetype = null;
474
475         // From CodeIgniter
476         // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
477         $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
478         /**
479          * Fileinfo extension - most reliable method
480          *
481          * Apparently XAMPP, CentOS, cPanel and who knows what
482          * other PHP distribution channels EXPLICITLY DISABLE
483          * ext/fileinfo, which is otherwise enabled by default
484          * since PHP 5.3 ...
485          */
486         if (function_exists('finfo_file'))
487         {
488             $finfo = @finfo_open(FILEINFO_MIME);
489             // It is possible that a FALSE value is returned, if there is no magic MIME database
490             // file found on the system
491             if (is_resource($finfo))
492             {
493                 $mime = @finfo_file($finfo, $filepath);
494                 finfo_close($finfo);
495                 /* According to the comments section of the PHP manual page,
496                  * it is possible that this function returns an empty string
497                  * for some files (e.g. if they don't exist in the magic MIME database)
498                  */
499                 if (is_string($mime) && preg_match($regexp, $mime, $matches))
500                 {
501                     $mimetype = $matches[1];
502                 }
503             }
504         }
505         /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
506          * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
507          * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
508          * than mime_content_type() as well, hence the attempts to try calling the command line with
509          * three different functions.
510          *
511          * Notes:
512          *  - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
513          *  - many system admins would disable the exec(), shell_exec(), popen() and similar functions
514          *    due to security concerns, hence the function_usable() checks
515          */
516         if (DIRECTORY_SEPARATOR !== '\\') {
517             $cmd = 'file --brief --mime '.escapeshellarg($filepath).' 2>&1';
518             if (function_exists('exec')) {
519                 /* This might look confusing, as $mime is being populated with all of the output
520                  * when set in the second parameter. However, we only need the last line, which is
521                  * the actual return value of exec(), and as such - it overwrites anything that could
522                  * already be set for $mime previously. This effectively makes the second parameter a
523                  * dummy value, which is only put to allow us to get the return status code.
524                  */
525                 $mime = @exec($cmd, $mime, $return_status);
526                 if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
527                     $mimetype = $matches[1];
528                 }
529             }
530             if (function_exists('shell_exec')) {
531                 $mime = @shell_exec($cmd);
532                 if (strlen($mime) > 0) {
533                     $mime = explode("\n", trim($mime));
534                     if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
535                         $mimetype = $matches[1];
536                     }
537                 }
538             }
539             if (function_exists('popen')) {
540                 $proc = @popen($cmd, 'r');
541                 if (is_resource($proc)) {
542                     $mime = @fread($proc, 512);
543                     @pclose($proc);
544                     if ($mime !== false) {
545                         $mime = explode("\n", trim($mime));
546                         if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
547                             $mimetype = $matches[1];
548                         }
549                     }
550                 }
551             }
552         }
553         // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
554         if (function_exists('mime_content_type'))
555         {
556             $mimetype = @mime_content_type($filepath);
557             // It's possible that mime_content_type() returns FALSE or an empty string
558             if ($mimetype == false && strlen($mimetype) > 0)
559             {
560                 throw new ServerException(_m('Could not determine file\'s MIME type.'));
561             }
562         }
563
564         // Unclear types are such that we can't really tell by the auto
565         // detect what they are (.bin, .exe etc. are just "octet-stream")
566         $unclearTypes = array('application/octet-stream',
567                               'application/vnd.ms-office',
568                               'application/zip',
569                               'text/plain',
570                               'text/html',  // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
571                               // TODO: for XML we could do better content-based sniffing too
572                               'text/xml');
573
574         $supported = common_config('attachments', 'supported');
575
576         // If we didn't match, or it is an unclear match
577         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
578             try {
579                 $type = common_supported_filename_to_mime($originalFilename);
580                 return $type;
581             } catch (UnknownExtensionMimeException $e) {
582                 // FIXME: I think we should keep the file extension here (supported should be === true here)
583             } catch (Exception $e) {
584                 // Extension parsed but no connected mimetype, so $mimetype is our best guess
585             }
586         }
587
588         // If $config['attachments']['supported'] equals boolean true, accept any mimetype
589         if ($supported === true || array_key_exists($mimetype, $supported)) {
590             // FIXME: Don't know if it always has a mimetype here because
591             // finfo->file CAN return false on error: http://php.net/finfo_file
592             // so if $supported === true, this may return something unexpected.
593             return $mimetype;
594         }
595
596         // We can conclude that we have failed to get the MIME type
597         $media = common_get_mime_media($mimetype);
598         if ('application' !== $media) {
599             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
600             // TRANS: %1$s is the file type that was denied, %2$s is the application part of
601             // TRANS: the MIME type that was denied.
602             $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
603             'Try using another %2$s format.'), $mimetype, $media);
604         } else {
605             // TRANS: Client exception thrown trying to upload a forbidden MIME type.
606             // TRANS: %s is the file type that was denied.
607             $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
608         }
609         throw new ClientException($hint);
610     }
611 }