3 * GNU social - a federating social network
5 * Abstraction for media files
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.
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.
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/>.
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/
31 defined('GNUSOCIAL') || die();
34 * Class responsible for abstracting media files
39 public $filepath = null;
40 public $filename = null;
41 public $fileRecord = null;
42 public $fileurl = null;
43 public $short_fileurl = null;
44 public $mimetype = null;
47 * @param string $filepath The path of the file this media refers to. Required
48 * @param string $mimetype The mimetype of the file. Required
49 * @param $filehash The hash of the file, if known. Optional
50 * @param int|null $id The DB id of the file. Int if known, null if not.
51 * If null, it searches for it. If -1, it skips all DB
52 * interactions (useful for temporary objects)
53 * @throws ClientException
54 * @throws NoResultException
55 * @throws ServerException
57 public function __construct(string $filepath, string $mimetype, $filehash = null, $id = null)
59 $this->filepath = $filepath;
60 $this->filename = basename($this->filepath);
61 $this->mimetype = $mimetype;
62 $this->filehash = self::getHashOfFile($this->filepath, $filehash);
65 // If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB,
67 if ($this->id !== -1) {
68 if (!empty($this->id)) {
69 // If we have an id, load it
70 $this->fileRecord = new File();
71 $this->fileRecord->id = $this->id;
72 if (!$this->fileRecord->find(true)) {
73 // If we have set an ID, we need that ID to exist!
74 throw new NoResultException($this->fileRecord);
77 // Otherwise, store it
78 $this->fileRecord = $this->storeFile();
81 $this->fileurl = common_local_url(
83 array('attachment' => $this->fileRecord->id)
86 $this->short_fileurl = common_shorten_url($this->fileurl);
90 public function attachToNotice(Notice $notice)
92 File_to_post::processNew($this->fileRecord, $notice);
95 public function getPath()
97 return File::path($this->filename);
100 public function shortUrl()
102 return $this->short_fileurl;
105 public function getEnclosure()
107 return $this->getFile()->getEnclosure();
110 public function delete()
112 @unlink($this->filepath);
115 public function getFile()
117 if (!$this->fileRecord instanceof File) {
118 throw new ServerException('File record did not exist for MediaFile');
121 return $this->fileRecord;
125 * Calculate the hash of a file.
127 * This won't work for files >2GiB because PHP uses only 32bit.
128 * @param string $filepath
129 * @param string|null $filehash
131 * @throws ServerException
133 public static function getHashOfFile(string $filepath, $filehash = null)
135 assert(!empty($filepath), __METHOD__ . ": filepath cannot be null");
136 if ($filehash === null) {
137 // Calculate if we have an older upload method somewhere (Qvitter) that
138 // doesn't do this before calling new MediaFile on its local files...
139 $filehash = hash_file(File::FILEHASH_ALG, $filepath);
140 if ($filehash === false) {
141 throw new ServerException('Could not read file for hashing');
148 * Retrieve or insert as a file in the DB
150 * @return object File
151 * @throws ClientException
152 * @throws ServerException
154 protected function storeFile()
157 $file = File::getByHash($this->filehash);
158 // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
160 } catch (NoResultException $e) {
161 // Well, let's just continue below.
164 $fileurl = common_local_url('attachment_view', array('filehash' => $this->filehash));
168 $file->filename = $this->filename;
169 $file->urlhash = File::hashurl($fileurl);
170 $file->url = $fileurl;
171 $file->filehash = $this->filehash;
172 $file->size = filesize($this->filepath);
173 if ($file->size === false) {
174 throw new ServerException('Could not read file to get its size');
176 $file->date = time();
177 $file->mimetype = $this->mimetype;
179 $file_id = $file->insert();
181 if ($file_id===false) {
182 common_log_db_error($file, "INSERT", __FILE__);
183 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
184 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
187 // Set file geometrical properties if available
189 $image = ImageFile::fromFileObject($file);
190 $orig = clone($file);
191 $file->width = $image->width;
192 $file->height = $image->height;
193 $file->update($orig);
195 // We have to cleanup after ImageFile, since it
196 // may have generated a temporary file from a
197 // video support plugin or something.
198 // FIXME: Do this more automagically.
199 if ($image->getPath() != $file->getPath()) {
202 } catch (ServerException $e) {
203 // We just couldn't make out an image from the file. This
204 // does not have to be UnsupportedMediaException, as we can
205 // also get ServerException from files not existing etc.
212 * The maximum allowed file size, as a string
214 public static function maxFileSize()
216 $value = self::maxFileSizeInt();
217 if ($value > 1024 * 1024) {
218 $value = $value/(1024*1024);
219 // TRANS: Number of megabytes. %d is the number.
220 return sprintf(_m('%dMB', '%dMB', $value), $value);
221 } elseif ($value > 1024) {
222 $value = $value/1024;
223 // TRANS: Number of kilobytes. %d is the number.
224 return sprintf(_m('%dkB', '%dkB', $value), $value);
226 // TRANS: Number of bytes. %d is the number.
227 return sprintf(_m('%dB', '%dB', $value), $value);
232 * The maximum allowed file size, as an int
234 public static function maxFileSizeInt() : int
236 return common_config('attachments', 'file_quota');
240 * Encodes a file name and a file hash in the new file format, which is used to avoid
241 * having an extension in the file, removing trust in extensions, while keeping the original name
242 * @throws ClientException
244 public static function encodeFilename($original_name, string $filehash, $ext = null) : string
246 if (empty($original_name)) {
247 $original_name = _('Untitled attachment');
250 // If we're given an extension explicitly, use it, otherwise...
252 // get a replacement extension if configured, returns false if it's blocked,
253 // null if no extension
254 File::getSafeExtension($original_name);
255 if ($ext === false) {
256 throw new ClientException(_('Blacklisted file extension.'));
259 common_debug("EXT: " . print_r($ext, true));
262 // Remove dots if we have them (make sure they're not repeated)
263 $ext = preg_replace('/^\.+/', '', $ext);
264 $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
267 $enc_name = bin2hex($original_name);
268 return "{$enc_name}-{$filehash}";
272 * Decode the new filename format
273 * @return false | null | string on failure, no match (old format) or original file name, respectively
275 public static function decodeFilename(string $encoded_filename)
277 // The x is because it is using in thumbnails
278 $ret = preg_match('/^([^-x]+?)-[^-]+$/', $encoded_filename, $matches);
279 if ($ret === false) {
281 } elseif ($ret === 0) {
282 return null; // No match
284 $filename = hex2bin($matches[1]);
287 if (preg_match('/^(.+?)\.(.+)$/', $filename, $sub_matches) === 1) {
288 $ext = $sub_matches[2];
289 // Previously, there was a blacklisted extension array, which could have an alternative
290 // extension, such as phps, to replace php. We want to turn it back (this is deprecated,
291 // as it no longer makes sense, since we don't trust trust files based on extension,
292 // but keep the feature)
293 $blacklist = common_config('attachments', 'extblacklist');
294 if (is_array($blacklist)) {
295 foreach ($blacklist as $upload_ext => $safe_ext) {
296 if ($ext === $safe_ext) {
302 return "{$sub_matches[1]}.{$ext}";
304 // No extension, don't bother trying to replace it
311 * Create a new MediaFile or ImageFile object from an upload
313 * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
314 * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
315 * The filename has a new format:
316 * bin2hex("{$original_name}.{$ext}")."-{$filehash}"
317 * This format should be respected. Notice the dash, which is important to distinguish it from the previous
318 * format ("{$hash}.{$ext}")
320 * @param string $param
321 * @param Profile|null $scoped
322 * @return ImageFile|MediaFile
323 * @throws ClientException
324 * @throws NoResultException
325 * @throws NoUploadedMediaException
326 * @throws ServerException
327 * @throws UnsupportedMediaException
328 * @throws UseFileAsThumbnailException
330 public static function fromUpload(string $param='media', Profile $scoped=null)
332 // The existence of the "error" element means PHP has processed it properly even if it was ok.
333 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
334 throw new NoUploadedMediaException($param);
337 switch ($_FILES[$param]['error']) {
338 case UPLOAD_ERR_OK: // success, jump out
340 case UPLOAD_ERR_INI_SIZE:
341 case UPLOAD_ERR_FORM_SIZE:
342 // TRANS: Exception thrown when too large a file is uploaded.
343 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
344 throw new ClientException(sprintf(
345 _('That file is too big. The maximum file size is %s.'),
348 case UPLOAD_ERR_PARTIAL:
349 @unlink($_FILES[$param]['tmp_name']);
350 // TRANS: Client exception.
351 throw new ClientException(_('The uploaded file was only partially uploaded.'));
352 case UPLOAD_ERR_NO_FILE:
353 // No file; probably just a non-AJAX submission.
354 throw new NoUploadedMediaException($param);
355 case UPLOAD_ERR_NO_TMP_DIR:
356 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
357 throw new ClientException(_('Missing a temporary folder.'));
358 case UPLOAD_ERR_CANT_WRITE:
359 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
360 throw new ClientException(_('Failed to write file to disk.'));
361 case UPLOAD_ERR_EXTENSION:
362 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
363 throw new ClientException(_('File upload stopped by extension.'));
365 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
366 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
367 throw new ClientException(_('System error uploading file.'));
370 $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
373 $file = File::getByHash($filehash);
374 // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
375 // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
376 $filepath = $file->getPath();
377 $mimetype = $file->mimetype;
378 // XXX PHP: Upgrade to PHP 7.1
379 // catch (FileNotFoundException | NoResultException $e)
380 } catch (Exception $e) {
381 // We have to save the upload as a new local file. This is the normal course of action.
382 if ($scoped instanceof Profile) {
383 // Throws exception if additional size does not respect quota
384 // This test is only needed, of course, if we're uploading something new.
385 File::respectsQuota($scoped, $_FILES[$param]['size']);
388 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
389 $media = common_get_mime_media($mimetype);
391 $basename = basename($_FILES[$param]['name']);
393 if ($media === 'image') {
394 // Use -1 for the id to avoid adding this temporary file to the DB
395 $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
396 // Validate the image by reencoding it. Additionally normalizes old formats to PNG,
397 // keeping JPEG and GIF untouched
398 $outpath = $img->resizeTo($img->filepath);
399 $ext = image_type_to_extension($img->preferredType(), false);
402 $filename = self::encodeFilename($basename, $filehash, $ext);
403 $filepath = File::path($filename);
405 if ($media === 'image') {
406 $result = rename($outpath, $filepath);
408 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
411 // TRANS: Client exception thrown when a file upload operation fails because the file could
412 // TRANS: not be moved from the temporary folder to the permanent file location.
414 throw new ClientException(_('File could not be moved to destination directory.'));
417 if ($media === 'image') {
418 return new ImageFile(null, $filepath);
421 return new MediaFile($filepath, $mimetype, $filehash);
424 public static function fromFilehandle($fh, Profile $scoped=null)
426 $stream = stream_get_meta_data($fh);
427 // So far we're only handling filehandles originating from tmpfile(),
428 // so we can always do hash_file on $stream['uri'] as far as I can tell!
429 $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
432 $file = File::getByHash($filehash);
433 // Already have it, so let's reuse the locally stored File
434 // by using getPath we also check whether the file exists
435 // and throw a FileNotFoundException with the path if it doesn't.
436 $filename = basename($file->getPath());
437 $mimetype = $file->mimetype;
438 } catch (FileNotFoundException $e) {
439 // This happens if the file we have uploaded has disappeared
440 // from the local filesystem for some reason. Since we got the
441 // File object from a sha256 check in fromFilehandle, it's safe
442 // to just copy the uploaded data to disk!
444 fseek($fh, 0); // just to be sure, go to the beginning
445 // dump the contents of our filehandle to the path from our exception
446 // and report error if it failed.
447 if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
448 // TRANS: Client exception thrown when a file upload operation fails because the file could
449 // TRANS: not be moved from the temporary folder to the permanent file location.
450 throw new ClientException(_('File could not be moved to destination directory.'));
452 if (!chmod($e->path, 0664)) {
453 common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
456 $filename = basename($file->getPath());
457 $mimetype = $file->mimetype;
458 } catch (NoResultException $e) {
459 if ($scoped instanceof Profile) {
460 File::respectsQuota($scoped, filesize($stream['uri']));
463 $mimetype = self::getUploadedMimeType($stream['uri']);
465 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
466 $filepath = File::path($filename);
468 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
471 common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
472 // TRANS: Client exception thrown when a file upload operation fails because the file could
473 // TRANS: not be moved from the temporary folder to the permanent file location.
474 throw new ClientException(_('File could not be moved to destination directory.'));
478 return new MediaFile($filename, $mimetype, $filehash);
482 * Attempt to identify the content type of a given file.
484 * @param string $filepath filesystem path as string (file must exist)
485 * @param bool $originalFilename (optional) for extension-based detection
488 * @throws ClientException if type is known, but not supported for local uploads
489 * @throws ServerException
490 * @fixme this seems to tie a front-end error message in, kinda confusing
493 public static function getUploadedMimeType(string $filepath, $originalFilename=false)
495 // We only accept filenames to existing files
500 // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
501 $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
503 * Fileinfo extension - most reliable method
505 * Apparently XAMPP, CentOS, cPanel and who knows what
506 * other PHP distribution channels EXPLICITLY DISABLE
507 * ext/fileinfo, which is otherwise enabled by default
510 if (function_exists('finfo_file')) {
511 $finfo = @finfo_open(FILEINFO_MIME);
512 // It is possible that a FALSE value is returned, if there is no magic MIME database
513 // file found on the system
514 if (is_resource($finfo)) {
515 $mime = @finfo_file($finfo, $filepath);
517 /* According to the comments section of the PHP manual page,
518 * it is possible that this function returns an empty string
519 * for some files (e.g. if they don't exist in the magic MIME database)
521 if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
522 $mimetype = $matches[1];
526 /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
527 * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
528 * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
529 * than mime_content_type() as well, hence the attempts to try calling the command line with
530 * three different functions.
533 * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
534 * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
535 * due to security concerns, hence the function_usable() checks
537 if (DIRECTORY_SEPARATOR !== '\\') {
538 $cmd = 'file --brief --mime '.escapeshellarg($filepath).' 2>&1';
539 if (empty($mimetype) && function_exists('exec')) {
540 /* This might look confusing, as $mime is being populated with all of the output
541 * when set in the second parameter. However, we only need the last line, which is
542 * the actual return value of exec(), and as such - it overwrites anything that could
543 * already be set for $mime previously. This effectively makes the second parameter a
544 * dummy value, which is only put to allow us to get the return status code.
546 $mime = @exec($cmd, $mime, $return_status);
547 if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
548 $mimetype = $matches[1];
551 if (empty($mimetype) && function_exists('shell_exec')) {
552 $mime = @shell_exec($cmd);
553 if (strlen($mime) > 0) {
554 $mime = explode("\n", trim($mime));
555 if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
556 $mimetype = $matches[1];
560 if (empty($mimetype) && function_exists('popen')) {
561 $proc = @popen($cmd, 'r');
562 if (is_resource($proc)) {
563 $mime = @fread($proc, 512);
565 if ($mime !== false) {
566 $mime = explode("\n", trim($mime));
567 if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
568 $mimetype = $matches[1];
574 // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
575 if (empty($mimetype) && function_exists('mime_content_type')) {
576 $mimetype = @mime_content_type($filepath);
577 // It's possible that mime_content_type() returns FALSE or an empty string
578 if ($mimetype == false && strlen($mimetype) > 0) {
579 throw new ServerException(_m('Could not determine file\'s MIME type.'));
583 // Unclear types are such that we can't really tell by the auto
584 // detect what they are (.bin, .exe etc. are just "octet-stream")
585 $unclearTypes = array('application/octet-stream',
586 'application/vnd.ms-office',
589 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
590 // TODO: for XML we could do better content-based sniffing too
593 $supported = common_config('attachments', 'supported');
595 // If we didn't match, or it is an unclear match
596 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
598 $type = common_supported_filename_to_mime($originalFilename);
600 } catch (UnknownExtensionMimeException $e) {
601 // FIXME: I think we should keep the file extension here (supported should be === true here)
602 } catch (Exception $e) {
603 // Extension parsed but no connected mimetype, so $mimetype is our best guess
607 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
608 if ($supported === true || array_key_exists($mimetype, $supported)) {
609 // FIXME: Don't know if it always has a mimetype here because
610 // finfo->file CAN return false on error: http://php.net/finfo_file
611 // so if $supported === true, this may return something unexpected.
615 // We can conclude that we have failed to get the MIME type
616 $media = common_get_mime_media($mimetype);
617 if ('application' !== $media) {
618 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
619 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
620 // TRANS: the MIME type that was denied.
621 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
622 'Try using another %2$s format.'), $mimetype, $media);
624 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
625 // TRANS: %s is the file type that was denied.
626 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
628 throw new ClientException($hint);
632 * Title for a file, to display in the interface (if there's no better title) and
633 * for download filenames
634 * @param $file File object
637 public static function getDisplayName(File $file) : string {
638 if (empty($file->filename)) {
639 return _('Untitled attachment');
642 // New file name format is "{bin2hex(original_name.ext)}-{$hash}"
643 $filename = self::decodeFilename($file->filename);
645 // If there was an error in the match, something's wrong with some piece
646 // of code (could be a file with utf8 chars in the name)
647 $log_error_msg = "Invalid file name for File with id={$file->id} " .
648 "({$file->filename}). Some plugin probably did something wrong.";
649 if ($filename === false) {
650 common_log(LOG_ERR, $log_error_msg);
651 } elseif ($filename === null) {
652 // The old file name format was "{hash}.{ext}" so we didn't have a name
653 // This extracts the extension
654 $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
656 common_log(LOG_ERR, $log_error_msg);
657 return _('Untitled attachment');
660 // There's a blacklisted extension array, which could have an alternative
661 // extension, such as phps, to replace php. We want to turn it back
662 // (currently defaulted to empty, but let's keep the feature)
663 $blacklist = common_config('attachments', 'extblacklist');
664 if (is_array($blacklist)) {
665 foreach ($blacklist as $upload_ext => $safe_ext) {
666 if ($ext === $safe_ext) {
672 $filename = "untitled.{$ext}";