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.'));
260 // Remove dots if we have them (make sure they're not repeated)
261 $ext = preg_replace('/^\.+/', '', $ext);
262 $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
265 $enc_name = bin2hex($original_name);
266 return "{$enc_name}-{$filehash}";
270 * Decode the new filename format
271 * @return false | null | string on failure, no match (old format) or original file name, respectively
273 public static function decodeFilename(string $encoded_filename)
275 // The x is because it is using in thumbnails
276 $ret = preg_match('/^([^-x]+?)-[^-]+$/', $encoded_filename, $matches);
277 if ($ret === false) {
279 } elseif ($ret === 0) {
280 return null; // No match
282 $filename = hex2bin($matches[1]);
285 if (preg_match('/^(.+?)\.(.+)$/', $filename, $sub_matches) === 1) {
286 $ext = $sub_matches[2];
287 // Previously, there was a blacklisted extension array, which could have an alternative
288 // extension, such as phps, to replace php. We want to turn it back (this is deprecated,
289 // as it no longer makes sense, since we don't trust trust files based on extension,
290 // but keep the feature)
291 $blacklist = common_config('attachments', 'extblacklist');
292 if (is_array($blacklist)) {
293 foreach ($blacklist as $upload_ext => $safe_ext) {
294 if ($ext === $safe_ext) {
300 return "{$sub_matches[1]}.{$ext}";
302 // No extension, don't bother trying to replace it
309 * Create a new MediaFile or ImageFile object from an upload
311 * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
312 * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
313 * The filename has a new format:
314 * bin2hex("{$original_name}.{$ext}")."-{$filehash}"
315 * This format should be respected. Notice the dash, which is important to distinguish it from the previous
316 * format ("{$hash}.{$ext}")
318 * @param string $param
319 * @param Profile|null $scoped
320 * @return ImageFile|MediaFile
321 * @throws ClientException
322 * @throws NoResultException
323 * @throws NoUploadedMediaException
324 * @throws ServerException
325 * @throws UnsupportedMediaException
326 * @throws UseFileAsThumbnailException
328 public static function fromUpload(string $param='media', Profile $scoped=null)
330 // The existence of the "error" element means PHP has processed it properly even if it was ok.
331 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
332 throw new NoUploadedMediaException($param);
335 switch ($_FILES[$param]['error']) {
336 case UPLOAD_ERR_OK: // success, jump out
338 case UPLOAD_ERR_INI_SIZE:
339 case UPLOAD_ERR_FORM_SIZE:
340 // TRANS: Exception thrown when too large a file is uploaded.
341 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
342 throw new ClientException(sprintf(
343 _('That file is too big. The maximum file size is %s.'),
346 case UPLOAD_ERR_PARTIAL:
347 @unlink($_FILES[$param]['tmp_name']);
348 // TRANS: Client exception.
349 throw new ClientException(_('The uploaded file was only partially uploaded.'));
350 case UPLOAD_ERR_NO_FILE:
351 // No file; probably just a non-AJAX submission.
352 throw new NoUploadedMediaException($param);
353 case UPLOAD_ERR_NO_TMP_DIR:
354 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
355 throw new ClientException(_('Missing a temporary folder.'));
356 case UPLOAD_ERR_CANT_WRITE:
357 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
358 throw new ClientException(_('Failed to write file to disk.'));
359 case UPLOAD_ERR_EXTENSION:
360 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
361 throw new ClientException(_('File upload stopped by extension.'));
363 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
364 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
365 throw new ClientException(_('System error uploading file.'));
368 $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
371 $file = File::getByHash($filehash);
372 // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
373 // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
374 $filepath = $file->getPath();
375 $mimetype = $file->mimetype;
376 } catch (FileNotFoundException | NoResultException $e) {
377 // We have to save the upload as a new local file. This is the normal course of action.
378 if ($scoped instanceof Profile) {
379 // Throws exception if additional size does not respect quota
380 // This test is only needed, of course, if we're uploading something new.
381 File::respectsQuota($scoped, $_FILES[$param]['size']);
384 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
385 $media = common_get_mime_media($mimetype);
387 $basename = basename($_FILES[$param]['name']);
389 if ($media === 'image') {
390 // Use -1 for the id to avoid adding this temporary file to the DB
391 $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
392 // Validate the image by reencoding it. Additionally normalizes old formats to PNG,
393 // keeping JPEG and GIF untouched
394 $outpath = $img->resizeTo($img->filepath);
395 $ext = image_type_to_extension($img->preferredType(), false);
398 $filename = self::encodeFilename($basename, $filehash, $ext);
399 $filepath = File::path($filename);
401 if ($media === 'image') {
402 $result = rename($outpath, $filepath);
404 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
407 // TRANS: Client exception thrown when a file upload operation fails because the file could
408 // TRANS: not be moved from the temporary folder to the permanent file location.
410 throw new ClientException(_('File could not be moved to destination directory.'));
413 if ($media === 'image') {
414 return new ImageFile(null, $filepath);
417 return new MediaFile($filepath, $mimetype, $filehash);
420 public static function fromFilehandle($fh, Profile $scoped=null)
422 $stream = stream_get_meta_data($fh);
423 // So far we're only handling filehandles originating from tmpfile(),
424 // so we can always do hash_file on $stream['uri'] as far as I can tell!
425 $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
428 $file = File::getByHash($filehash);
429 // Already have it, so let's reuse the locally stored File
430 // by using getPath we also check whether the file exists
431 // and throw a FileNotFoundException with the path if it doesn't.
432 $filename = basename($file->getPath());
433 $mimetype = $file->mimetype;
434 } catch (FileNotFoundException $e) {
435 // This happens if the file we have uploaded has disappeared
436 // from the local filesystem for some reason. Since we got the
437 // File object from a sha256 check in fromFilehandle, it's safe
438 // to just copy the uploaded data to disk!
440 fseek($fh, 0); // just to be sure, go to the beginning
441 // dump the contents of our filehandle to the path from our exception
442 // and report error if it failed.
443 if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
444 // TRANS: Client exception thrown when a file upload operation fails because the file could
445 // TRANS: not be moved from the temporary folder to the permanent file location.
446 throw new ClientException(_('File could not be moved to destination directory.'));
448 if (!chmod($e->path, 0664)) {
449 common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
452 $filename = basename($file->getPath());
453 $mimetype = $file->mimetype;
454 } catch (NoResultException $e) {
455 if ($scoped instanceof Profile) {
456 File::respectsQuota($scoped, filesize($stream['uri']));
459 $mimetype = self::getUploadedMimeType($stream['uri']);
461 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
462 $filepath = File::path($filename);
464 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
467 common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
468 // TRANS: Client exception thrown when a file upload operation fails because the file could
469 // TRANS: not be moved from the temporary folder to the permanent file location.
470 throw new ClientException(_('File could not be moved to destination directory.'));
474 return new MediaFile($filename, $mimetype, $filehash);
478 * Attempt to identify the content type of a given file.
480 * @param string $filepath filesystem path as string (file must exist)
481 * @param bool $originalFilename (optional) for extension-based detection
484 * @throws ClientException if type is known, but not supported for local uploads
485 * @throws ServerException
486 * @fixme this seems to tie a front-end error message in, kinda confusing
489 public static function getUploadedMimeType(string $filepath, $originalFilename=false)
491 // We only accept filenames to existing files
496 // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
497 $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
499 * Fileinfo extension - most reliable method
501 * Apparently XAMPP, CentOS, cPanel and who knows what
502 * other PHP distribution channels EXPLICITLY DISABLE
503 * ext/fileinfo, which is otherwise enabled by default
506 if (function_exists('finfo_file')) {
507 $finfo = @finfo_open(FILEINFO_MIME);
508 // It is possible that a FALSE value is returned, if there is no magic MIME database
509 // file found on the system
510 if (is_resource($finfo)) {
511 $mime = @finfo_file($finfo, $filepath);
513 /* According to the comments section of the PHP manual page,
514 * it is possible that this function returns an empty string
515 * for some files (e.g. if they don't exist in the magic MIME database)
517 if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
518 $mimetype = $matches[1];
522 /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
523 * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
524 * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
525 * than mime_content_type() as well, hence the attempts to try calling the command line with
526 * three different functions.
529 * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
530 * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
531 * due to security concerns, hence the function_usable() checks
533 if (DIRECTORY_SEPARATOR !== '\\') {
534 $cmd = 'file --brief --mime '.escapeshellarg($filepath).' 2>&1';
535 if (empty($mimetype) && function_exists('exec')) {
536 /* This might look confusing, as $mime is being populated with all of the output
537 * when set in the second parameter. However, we only need the last line, which is
538 * the actual return value of exec(), and as such - it overwrites anything that could
539 * already be set for $mime previously. This effectively makes the second parameter a
540 * dummy value, which is only put to allow us to get the return status code.
542 $mime = @exec($cmd, $mime, $return_status);
543 if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
544 $mimetype = $matches[1];
547 if (empty($mimetype) && function_exists('shell_exec')) {
548 $mime = @shell_exec($cmd);
549 if (strlen($mime) > 0) {
550 $mime = explode("\n", trim($mime));
551 if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
552 $mimetype = $matches[1];
556 if (empty($mimetype) && function_exists('popen')) {
557 $proc = @popen($cmd, 'r');
558 if (is_resource($proc)) {
559 $mime = @fread($proc, 512);
561 if ($mime !== false) {
562 $mime = explode("\n", trim($mime));
563 if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
564 $mimetype = $matches[1];
570 // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
571 if (empty($mimetype) && function_exists('mime_content_type')) {
572 $mimetype = @mime_content_type($filepath);
573 // It's possible that mime_content_type() returns FALSE or an empty string
574 if ($mimetype == false && strlen($mimetype) > 0) {
575 throw new ServerException(_m('Could not determine file\'s MIME type.'));
579 // Unclear types are such that we can't really tell by the auto
580 // detect what they are (.bin, .exe etc. are just "octet-stream")
581 $unclearTypes = array('application/octet-stream',
582 'application/vnd.ms-office',
585 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
586 // TODO: for XML we could do better content-based sniffing too
589 $supported = common_config('attachments', 'supported');
591 // If we didn't match, or it is an unclear match
592 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
594 $type = common_supported_filename_to_mime($originalFilename);
596 } catch (UnknownExtensionMimeException $e) {
597 // FIXME: I think we should keep the file extension here (supported should be === true here)
598 } catch (Exception $e) {
599 // Extension parsed but no connected mimetype, so $mimetype is our best guess
603 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
604 if ($supported === true || array_key_exists($mimetype, $supported)) {
605 // FIXME: Don't know if it always has a mimetype here because
606 // finfo->file CAN return false on error: http://php.net/finfo_file
607 // so if $supported === true, this may return something unexpected.
611 // We can conclude that we have failed to get the MIME type
612 $media = common_get_mime_media($mimetype);
613 if ('application' !== $media) {
614 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
615 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
616 // TRANS: the MIME type that was denied.
617 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
618 'Try using another %2$s format.'), $mimetype, $media);
620 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
621 // TRANS: %s is the file type that was denied.
622 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
624 throw new ClientException($hint);
628 * Title for a file, to display in the interface (if there's no better title) and
629 * for download filenames
630 * @param $file File object
633 public static function getDisplayName(File $file) : string {
634 if (empty($file->filename)) {
635 return _('Untitled attachment');
638 // New file name format is "{bin2hex(original_name.ext)}-{$hash}"
639 $filename = self::decodeFilename($file->filename);
641 // If there was an error in the match, something's wrong with some piece
642 // of code (could be a file with utf8 chars in the name)
643 $log_error_msg = "Invalid file name for File with id={$file->id} " .
644 "({$file->filename}). Some plugin probably did something wrong.";
645 if ($filename === false) {
646 common_log(LOG_ERR, $log_error_msg);
647 } elseif ($filename === null) {
648 // The old file name format was "{hash}.{ext}" so we didn't have a name
649 // This extracts the extension
650 $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
652 common_log(LOG_ERR, $log_error_msg);
653 return _('Untitled attachment');
656 // There's a blacklisted extension array, which could have an alternative
657 // extension, such as phps, to replace php. We want to turn it back
658 // (currently defaulted to empty, but let's keep the feature)
659 $blacklist = common_config('attachments', 'extblacklist');
660 if (is_array($blacklist)) {
661 foreach ($blacklist as $upload_ext => $safe_ext) {
662 if ($ext === $safe_ext) {
668 $filename = "untitled.{$ext}";