123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912 |
- <?php
- defined('GNUSOCIAL') || die();
- require_once INSTALLDIR . '/lib/util/tempfile.php';
- class MediaFile
- {
- public $id;
- public $filepath;
- public $filename;
- public $fileRecord;
- public $fileurl;
- public $short_fileurl;
- public $mimetype;
-
- public function __construct(?string $filepath = null, string $mimetype, ?string $filehash = null, ?int $id = null, ?string $fileurl = null)
- {
- $this->filepath = $filepath;
- $this->filename = basename($this->filepath);
- $this->mimetype = $mimetype;
- $this->filehash = is_null($filepath) ? null : self::getHashOfFile($this->filepath, $filehash);
- $this->id = $id;
- $this->fileurl = $fileurl;
-
-
- 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();
- }
- }
- }
-
- public static function fromFileObject(File $file)
- {
- $filepath = null;
- try {
- $filepath = $file->getPath();
- } catch (Exception $e) {}
- return new self($filepath, common_get_mime_media($file->mimetype), $file->filehash, $file->getID());
- }
- public function attachToNotice(Notice $notice)
- {
- File_to_post::processNew($this->fileRecord, $notice);
- }
- public function getPath()
- {
- return File::path($this->filename);
- }
-
- public function getUrl(?bool $use_local=null): ?string
- {
- if ($use_local !== false) {
- if (empty($this->fileurl)) {
-
- return common_local_url('attachment_view', ['filehash' => $this->filehash]);
- }
- }
-
- return $this->fileurl;
- }
- public function shortUrl()
- {
- return common_shorten_url($this->getUrl());
- }
- public function getEnclosure()
- {
- return $this->getFile()->getEnclosure();
- }
- public function delete($useWhere=false)
- {
- if (!is_null($this->fileRecord)) {
- $this->fileRecord->delete($useWhere);
- }
- @unlink($this->filepath);
- }
- public function unlink()
- {
- $this->filename = null;
-
- if (!empty($this->filepath) && file_exists($this->filepath)) {
- $deleted = @unlink($this->filepath);
- if (!$deleted) {
- common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', $this->filepath));
- }
- }
- $this->fileRecord->unlink();
- }
- 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);
- if (is_null($this->fileurl) && is_null($file->getUrl(false))) {
-
- return $file;
- }
- } catch (NoResultException $e) {
-
- }
- $file = new File;
- $file->filename = $this->filename;
- $file->url = $this->fileurl;
- $file->urlhash = is_null($file->url) ? null : File::hashurl($file->url);
- $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);
- }
-
- $pretty_name = substr(trim($original_name), 0, 30);
- $enc_name = bin2hex($pretty_name);
- return "{$enc_name}-{$filehash}";
- }
-
- public static function decodeFilename(string $encoded_filename)
- {
-
-
-
-
- $ret = preg_match('/^(.*-)?([^-]+)-[^-]+$/', $encoded_filename, $matches);
- if ($ret === false) {
- return false;
- } elseif ($ret === 0 || !ctype_xdigit($matches[2])) {
- return null;
- } else {
- $filename = hex2bin($matches[2]);
-
- 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], $_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']));
- $fileid = null;
- try {
- $file = File::getByHash($filehash);
-
- while ($file->fetch()) {
- if ($file->getUrl(false)) {
-
- continue;
- }
- try {
- return ImageFile::fromFileObject($file);
- } catch (UnsupportedMediaException $e) {
- return MediaFile::fromFileObject($file);
- }
- }
-
- if (common_config('attachments', 'prefer_remote')) {
-
- $filepath = $file->getPath();
-
- $mimetype = $file->mimetype;
- $fileid = $file->getID();
- } else {
- throw new FileNotFoundException('This isn\'t a path.');
-
-
-
-
-
- }
- } 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, $filehash);
- }
- }
- return new self($filepath, $mimetype, $filehash, $fileid);
- }
-
- public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null)
- {
- if (!common_valid_http_url($url)) {
-
- throw new ServerException(sprintf('Invalid remote media URL %s.', $url));
- }
- $http = new HTTPClient();
- common_debug(sprintf('Performing HEAD request for incoming activity to avoid ' .
- 'unnecessarily downloading too large files. URL: %s',
- $url));
- $head = $http->head($url);
- $url = $head->getEffectiveUrl();
- if (empty($url)) {
- throw new ServerException(sprintf('URL after redirects is somehow empty, for URL %s.', $url));
- }
- $headers = $head->getHeader();
- $headers = array_change_key_case($headers, CASE_LOWER);
- if (array_key_exists('content-length', $headers)) {
- $fileQuota = common_config('attachments', 'file_quota');
- $fileSize = $headers['content-length'];
- if ($fileSize > $fileQuota) {
-
-
-
- $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
-
-
-
-
- throw new ClientException(
- sprintf(
- _m(
- 'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
- 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
- $fileQuota
- ),
- $fileQuota,
- $fileSizeText
- )
- );
- }
- } else {
- throw new ServerException(sprintf('Invalid remote media URL headers %s.', $url));
- }
- unset($head);
- unset($headers);
- $tempfile = new TemporaryFile('gs-mediafile');
- fwrite($tempfile->getResource(), HTTPClient::quickGet($url));
- fflush($tempfile->getResource());
- $filehash = strtolower(self::getHashOfFile($tempfile->getRealPath()));
- try {
- $file = File::getByUrl($url);
-
- $filepath = $file->getPath();
- $mimetype = $file->mimetype;
- } catch (FileNotFoundException | NoResultException $e) {
-
-
- if ($scoped instanceof Profile) {
-
-
- File::respectsQuota($scoped, filesize($tempfile->getRealPath()));
- }
- $mimetype = self::getUploadedMimeType(
- $tempfile->getRealPath(),
- $name ?? false
- );
- $media = common_get_mime_media($mimetype);
- $basename = basename($name ?? ('media' . common_timestamp()));
- if ($media === 'image') {
-
- $img = new ImageFile(-1, $tempfile->getRealPath());
-
-
-
- $outpath = $img->resizeTo($img->filepath);
- $ext = image_type_to_extension($img->preferredType(), false);
- }
- $filename = self::encodeFilename(
- $basename,
- $filehash,
- $ext ?? File::getSafeExtension($basename)
- );
- $filepath = File::path($filename);
- if ($media === 'image') {
- $result = rename($outpath, $filepath);
- } else {
- try {
- $tempfile->commit($filepath);
- $result = true;
- } catch (TemporaryFileException $e) {
- $result = false;
- }
- }
- if (!$result) {
-
-
- throw new ServerException(_m('File could not be moved to destination directory.'));
- }
- if ($media === 'image') {
- return new ImageFile($file_id, $filepath, $filehash, $url);
- }
- }
- return new self($filepath, $mimetype, $filehash, $file_id, $url);
- }
- public static function fromFileInfo(SplFileInfo $finfo, Profile $scoped = null)
- {
- $filehash = hash_file(File::FILEHASH_ALG, $finfo->getRealPath());
- try {
- $file = File::getByHash($filehash);
- $file->fetch();
-
-
-
- $filename = basename($file->getPath());
- $mimetype = $file->mimetype;
- } catch (FileNotFoundException $e) {
-
-
-
-
-
-
- if (file_put_contents($e->path, file_get_contents($finfo->getRealPath())) === false) {
-
-
- 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($finfo->getRealPath()));
- }
- $mimetype = self::getUploadedMimeType($finfo->getRealPath());
- $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
- $filepath = File::path($filename);
- $result = copy($finfo->getRealPath(), $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 self($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 = ['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;
- }
- }
|