123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673 |
- <?php
- defined('GNUSOCIAL') || die();
- class MediaFile
- {
- public $id = null;
- public $filepath = null;
- public $filename = null;
- public $fileRecord = null;
- public $fileurl = null;
- public $short_fileurl = null;
- public $mimetype = null;
-
- public function __construct(string $filepath, string $mimetype, $filehash = null, $id = null)
- {
- $this->filepath = $filepath;
- $this->filename = basename($this->filepath);
- $this->mimetype = $mimetype;
- $this->filehash = self::getHashOfFile($this->filepath, $filehash);
- $this->id = $id;
-
-
- if ($this->id !== -1) {
- if (!empty($this->id)) {
-
- $this->fileRecord = new File();
- $this->fileRecord->id = $this->id;
- if (!$this->fileRecord->find(true)) {
-
- throw new NoResultException($this->fileRecord);
- }
- } else {
-
- $this->fileRecord = $this->storeFile();
- }
- $this->fileurl = common_local_url(
- 'attachment',
- array('attachment' => $this->fileRecord->id)
- );
- $this->short_fileurl = common_shorten_url($this->fileurl);
- }
- }
- public function attachToNotice(Notice $notice)
- {
- File_to_post::processNew($this->fileRecord, $notice);
- }
- public function getPath()
- {
- return File::path($this->filename);
- }
- public function shortUrl()
- {
- return $this->short_fileurl;
- }
- public function getEnclosure()
- {
- return $this->getFile()->getEnclosure();
- }
- public function delete()
- {
- @unlink($this->filepath);
- }
- public function getFile()
- {
- if (!$this->fileRecord instanceof File) {
- throw new ServerException('File record did not exist for MediaFile');
- }
- return $this->fileRecord;
- }
-
- public static function getHashOfFile(string $filepath, $filehash = null)
- {
- assert(!empty($filepath), __METHOD__ . ": filepath cannot be null");
- if ($filehash === null) {
-
-
- $filehash = hash_file(File::FILEHASH_ALG, $filepath);
- if ($filehash === false) {
- throw new ServerException('Could not read file for hashing');
- }
- }
- return $filehash;
- }
-
- protected function storeFile()
- {
- try {
- $file = File::getByHash($this->filehash);
-
- return $file;
- } catch (NoResultException $e) {
-
- }
- $fileurl = common_local_url('attachment_view', array('filehash' => $this->filehash));
- $file = new File;
- $file->filename = $this->filename;
- $file->urlhash = File::hashurl($fileurl);
- $file->url = $fileurl;
- $file->filehash = $this->filehash;
- $file->size = filesize($this->filepath);
- if ($file->size === false) {
- throw new ServerException('Could not read file to get its size');
- }
- $file->date = time();
- $file->mimetype = $this->mimetype;
- $file_id = $file->insert();
- if ($file_id===false) {
- common_log_db_error($file, "INSERT", __FILE__);
-
- throw new ClientException(_m('There was a database error while saving your file. Please try again.'));
- }
-
- try {
- $image = ImageFile::fromFileObject($file);
- $orig = clone($file);
- $file->width = $image->width;
- $file->height = $image->height;
- $file->update($orig);
-
-
-
-
- if ($image->getPath() != $file->getPath()) {
- $image->unlink();
- }
- } catch (ServerException $e) {
-
-
-
- }
- return $file;
- }
-
- public static function maxFileSize()
- {
- $value = self::maxFileSizeInt();
- if ($value > 1024 * 1024) {
- $value = $value/(1024*1024);
-
- return sprintf(_m('%dMB', '%dMB', $value), $value);
- } elseif ($value > 1024) {
- $value = $value/1024;
-
- return sprintf(_m('%dkB', '%dkB', $value), $value);
- } else {
-
- return sprintf(_m('%dB', '%dB', $value), $value);
- }
- }
-
- public static function maxFileSizeInt() : int
- {
- return common_config('attachments', 'file_quota');
- }
-
- public static function encodeFilename($original_name, string $filehash, $ext = null) : string
- {
- if (empty($original_name)) {
- $original_name = _m('Untitled attachment');
- }
-
- $ext = $ext ?:
-
-
- File::getSafeExtension($original_name);
- if ($ext === false) {
- throw new ClientException(_m('Blacklisted file extension.'));
- }
- if (!empty($ext)) {
-
- $ext = preg_replace('/^\.+/', '', $ext);
- $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
- }
- $enc_name = bin2hex($original_name);
- return "{$enc_name}-{$filehash}";
- }
-
- public static function decodeFilename(string $encoded_filename)
- {
-
- $ret = preg_match('/^([^-x]+?)-[^-]+$/', $encoded_filename, $matches);
- if ($ret === false) {
- return false;
- } elseif ($ret === 0) {
- return null;
- } else {
- $filename = hex2bin($matches[1]);
-
- if (preg_match('/^(.+?)\.(.+)$/', $filename, $sub_matches) === 1) {
- $ext = $sub_matches[2];
-
-
-
-
- $blacklist = common_config('attachments', 'extblacklist');
- if (is_array($blacklist)) {
- foreach ($blacklist as $upload_ext => $safe_ext) {
- if ($ext === $safe_ext) {
- $ext = $upload_ext;
- break;
- }
- }
- }
- return "{$sub_matches[1]}.{$ext}";
- } else {
-
- return $filename;
- }
- }
- }
-
- public static function fromUpload(string $param='media', Profile $scoped=null)
- {
-
- if (!(isset($_FILES[$param]) && isset($_FILES[$param]['error']))) {
- throw new NoUploadedMediaException($param);
- }
- switch ($_FILES[$param]['error']) {
- case UPLOAD_ERR_OK:
- break;
- case UPLOAD_ERR_INI_SIZE:
- case UPLOAD_ERR_FORM_SIZE:
-
-
- throw new ClientException(sprintf(
- _m('That file is too big. The maximum file size is %s.'),
- self::maxFileSize()
- ));
- case UPLOAD_ERR_PARTIAL:
- @unlink($_FILES[$param]['tmp_name']);
-
- throw new ClientException(_m('The uploaded file was only partially uploaded.'));
- case UPLOAD_ERR_NO_FILE:
-
- throw new NoUploadedMediaException($param);
- case UPLOAD_ERR_NO_TMP_DIR:
-
- throw new ClientException(_m('Missing a temporary folder.'));
- case UPLOAD_ERR_CANT_WRITE:
-
- throw new ClientException(_m('Failed to write file to disk.'));
- case UPLOAD_ERR_EXTENSION:
-
- throw new ClientException(_m('File upload stopped by extension.'));
- default:
- common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
-
- throw new ClientException(_m('System error uploading file.'));
- }
- $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
- try {
- $file = File::getByHash($filehash);
-
-
- $filepath = $file->getPath();
- $mimetype = $file->mimetype;
- } catch (FileNotFoundException | NoResultException $e) {
-
- if ($scoped instanceof Profile) {
-
-
- File::respectsQuota($scoped, $_FILES[$param]['size']);
- }
- $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
- $media = common_get_mime_media($mimetype);
- $basename = basename($_FILES[$param]['name']);
- if ($media == 'image') {
-
- $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
-
-
- $outpath = $img->resizeTo($img->filepath);
- $ext = image_type_to_extension($img->preferredType(), false);
- }
- $filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename));
- $filepath = File::path($filename);
- if ($media == 'image') {
- $result = rename($outpath, $filepath);
- } else {
- $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
- }
- if (!$result) {
-
-
-
- throw new ClientException(_m('File could not be moved to destination directory.'));
- }
- if ($media == 'image') {
- return new ImageFile(null, $filepath);
- }
- }
- return new MediaFile($filepath, $mimetype, $filehash);
- }
- public static function fromFilehandle($fh, Profile $scoped=null)
- {
- $stream = stream_get_meta_data($fh);
-
-
- $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
- try {
- $file = File::getByHash($filehash);
-
-
-
- $filename = basename($file->getPath());
- $mimetype = $file->mimetype;
- } catch (FileNotFoundException $e) {
-
-
-
-
- fseek($fh, 0);
-
-
- if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
-
-
- throw new ClientException(_m('File could not be moved to destination directory.'));
- }
- if (!chmod($e->path, 0664)) {
- common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
- }
- $filename = basename($file->getPath());
- $mimetype = $file->mimetype;
- } catch (NoResultException $e) {
- if ($scoped instanceof Profile) {
- File::respectsQuota($scoped, filesize($stream['uri']));
- }
- $mimetype = self::getUploadedMimeType($stream['uri']);
- $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
- $filepath = File::path($filename);
- $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
- if (!$result) {
- common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
-
-
- throw new ClientException(_m('File could not be moved to destination directory.'));
- }
- }
- return new MediaFile($filename, $mimetype, $filehash);
- }
-
- public static function getUploadedMimeType(string $filepath, $originalFilename=false)
- {
-
- $mimetype = null;
-
-
- $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
-
- if (function_exists('finfo_file')) {
- $finfo = @finfo_open(FILEINFO_MIME);
-
-
- if (is_resource($finfo)) {
- $mime = @finfo_file($finfo, $filepath);
- finfo_close($finfo);
-
- if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
- $mimetype = $matches[1];
- }
- }
- }
-
- if (DIRECTORY_SEPARATOR !== '\\') {
- $cmd = 'file --brief --mime '.escapeshellarg($filepath).' 2>&1';
- if (empty($mimetype) && function_exists('exec')) {
-
- $mime = @exec($cmd, $mime, $return_status);
- if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
- $mimetype = $matches[1];
- }
- }
- if (empty($mimetype) && function_exists('shell_exec')) {
- $mime = @shell_exec($cmd);
- if (strlen($mime) > 0) {
- $mime = explode("\n", trim($mime));
- if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
- $mimetype = $matches[1];
- }
- }
- }
- if (empty($mimetype) && function_exists('popen')) {
- $proc = @popen($cmd, 'r');
- if (is_resource($proc)) {
- $mime = @fread($proc, 512);
- @pclose($proc);
- if ($mime !== false) {
- $mime = explode("\n", trim($mime));
- if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
- $mimetype = $matches[1];
- }
- }
- }
- }
- }
-
- if (empty($mimetype) && function_exists('mime_content_type')) {
- $mimetype = @mime_content_type($filepath);
-
- if ($mimetype == false && strlen($mimetype) > 0) {
- throw new ServerException(_m('Could not determine file\'s MIME type.'));
- }
- }
-
-
- $unclearTypes = array('application/octet-stream',
- 'application/vnd.ms-office',
- 'application/zip',
- 'text/plain',
- 'text/html',
-
- 'text/xml');
- $supported = common_config('attachments', 'supported');
-
- if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
- try {
- $type = common_supported_filename_to_mime($originalFilename);
- return $type;
- } catch (UnknownExtensionMimeException $e) {
-
- } catch (Exception $e) {
-
- }
- }
-
- if ($supported === true || array_key_exists($mimetype, $supported)) {
-
-
-
- return $mimetype;
- }
-
- $media = common_get_mime_media($mimetype);
- if ('application' !== $media) {
-
-
-
- $hint = sprintf(_m('"%1$s" is not a supported file type on this server. ' .
- 'Try using another %2$s format.'), $mimetype, $media);
- } else {
-
-
- $hint = sprintf(_m('"%s" is not a supported file type on this server.'), $mimetype);
- }
- throw new ClientException($hint);
- }
-
- public static function getDisplayName(File $file) : string {
- if (empty($file->filename)) {
- return _m('Untitled attachment');
- }
-
- $filename = self::decodeFilename($file->filename);
-
-
- $log_error_msg = "Invalid file name for File with id={$file->id} " .
- "({$file->filename}). Some plugin probably did something wrong.";
- if ($filename === false) {
- common_log(LOG_ERR, $log_error_msg);
- } elseif ($filename === null) {
-
-
- $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
- if ($ret !== 1) {
- common_log(LOG_ERR, $log_error_msg);
- return _m('Untitled attachment');
- }
- $ext = $matches[1];
-
-
-
- $blacklist = common_config('attachments', 'extblacklist');
- if (is_array($blacklist)) {
- foreach ($blacklist as $upload_ext => $safe_ext) {
- if ($ext === $safe_ext) {
- $ext = $upload_ext;
- break;
- }
- }
- }
- $filename = "untitled.{$ext}";
- }
- return $filename;
- }
- }
|