[FORMATING] Ran php-cs-fixer on lib/mediafile.php, lib/imagefile.php and classes/File.php

This commit is contained in:
Miguel Dantas 2019-06-09 23:26:48 +01:00
parent b224d93098
commit 20c73f0596
3 changed files with 202 additions and 129 deletions

View File

@ -80,8 +80,8 @@ class File extends Managed_DataObject
); );
} }
public static function isProtected($url) { public static function isProtected($url)
{
$protected_urls_exps = array( $protected_urls_exps = array(
'https://www.facebook.com/login.php', 'https://www.facebook.com/login.php',
common_path('main/login') common_path('main/login')
@ -152,16 +152,27 @@ class File extends Managed_DataObject
$file = new File; $file = new File;
$file->url = $given_url; $file->url = $given_url;
if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected']; if (!empty($redir_data['protected'])) {
if (!empty($redir_data['title'])) $file->title = $redir_data['title']; $file->protected = $redir_data['protected'];
if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type']; }
if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']); if (!empty($redir_data['title'])) {
if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']); $file->title = $redir_data['title'];
}
if (!empty($redir_data['type'])) {
$file->mimetype = $redir_data['type'];
}
if (!empty($redir_data['size'])) {
$file->size = intval($redir_data['size']);
}
if (isset($redir_data['time']) && $redir_data['time'] > 0) {
$file->date = intval($redir_data['time']);
}
$file->saveFile(); $file->saveFile();
return $file; return $file;
} }
public function saveFile() { public function saveFile()
{
$this->urlhash = self::hashurl($this->url); $this->urlhash = self::hashurl($this->url);
if (!Event::handle('StartFileSaveNew', array(&$this))) { if (!Event::handle('StartFileSaveNew', array(&$this))) {
@ -193,7 +204,8 @@ class File extends Managed_DataObject
* *
* @throws ServerException on failure * @throws ServerException on failure
*/ */
public static function processNew($given_url, Notice $notice=null, $followRedirects=true) { public static function processNew($given_url, Notice $notice=null, $followRedirects=true)
{
if (empty($given_url)) { if (empty($given_url)) {
throw new ServerException('No given URL to process'); throw new ServerException('No given URL to process');
} }
@ -222,7 +234,8 @@ class File extends Managed_DataObject
return $file; return $file;
} }
public static function respectsQuota(Profile $scoped, $fileSize) { public static function respectsQuota(Profile $scoped, $fileSize)
{
if ($fileSize > common_config('attachments', 'file_quota')) { if ($fileSize > common_config('attachments', 'file_quota')) {
// TRANS: Message used to be inserted as %2$s in the text "No file may // TRANS: Message used to be inserted as %2$s in the text "No file may
// TRANS: be larger than %1$d byte and the file you sent was %2$s.". // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
@ -235,10 +248,16 @@ class File extends Managed_DataObject
// TRANS: %2$s is the proper form of "n bytes". This is the only ways to have // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
// TRANS: gettext support multiple plurals in the same message, unfortunately... // TRANS: gettext support multiple plurals in the same message, unfortunately...
throw new ClientException( 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.', 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.', '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
$fileQuota, $fileSizeText)); ),
$fileQuota,
$fileSizeText
)
);
} }
$file = new File; $file = new File;
@ -251,10 +270,15 @@ class File extends Managed_DataObject
// TRANS: Message given if an upload would exceed user quota. // TRANS: Message given if an upload would exceed user quota.
// TRANS: %d (number) is the user quota in bytes and is used for plural. // TRANS: %d (number) is the user quota in bytes and is used for plural.
throw new ClientException( throw new ClientException(
sprintf(_m('A file this large would exceed your user quota of %d byte.', sprintf(
_m(
'A file this large would exceed your user quota of %d byte.',
'A file this large would exceed your user quota of %d bytes.', 'A file this large would exceed your user quota of %d bytes.',
common_config('attachments', 'user_quota')), common_config('attachments', 'user_quota')
common_config('attachments', 'user_quota'))); ),
common_config('attachments', 'user_quota')
)
);
} }
$query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())'; $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
$file->query($query); $file->query($query);
@ -264,10 +288,15 @@ class File extends Managed_DataObject
// TRANS: Message given id an upload would exceed a user's monthly quota. // TRANS: Message given id an upload would exceed a user's monthly quota.
// TRANS: $d (number) is the monthly user quota in bytes and is used for plural. // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
throw new ClientException( throw new ClientException(
sprintf(_m('A file this large would exceed your monthly quota of %d byte.', sprintf(
_m(
'A file this large would exceed your monthly quota of %d byte.',
'A file this large would exceed your monthly quota of %d bytes.', 'A file this large would exceed your monthly quota of %d bytes.',
common_config('attachments', 'monthly_quota')), common_config('attachments', 'monthly_quota')
common_config('attachments', 'monthly_quota'))); ),
common_config('attachments', 'monthly_quota')
)
);
} }
return true; return true;
} }
@ -284,7 +313,7 @@ class File extends Managed_DataObject
// where should the file go? // where should the file go?
static function filename(Profile $profile, $origname, $mimetype) public static function filename(Profile $profile, $origname, $mimetype)
{ {
$ext = self::guessMimeExtension($mimetype, $origname); $ext = self::guessMimeExtension($mimetype, $origname);
@ -313,7 +342,7 @@ class File extends Managed_DataObject
* @return mixed|string * @return mixed|string
* @throws ClientException * @throws ClientException
*/ */
static function guessMimeExtension($mimetype, $filename=null) public static function guessMimeExtension($mimetype, $filename=null)
{ {
try { try {
// first see if we know the extension for our mimetype // first see if we know the extension for our mimetype
@ -364,15 +393,14 @@ class File extends Managed_DataObject
* @param $filename * @param $filename
* @return false|int * @return false|int
*/ */
static function validFilename($filename) public static function validFilename($filename)
{ {
return preg_match('/^[A-Za-z0-9._-]+$/', $filename); return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
} }
static function tryFilename($filename) public static function tryFilename($filename)
{
if (!self::validFilename($filename))
{ {
if (!self::validFilename($filename)) {
throw new InvalidFilenameException($filename); throw new InvalidFilenameException($filename);
} }
// if successful, return the filename for easy if-statementing // if successful, return the filename for easy if-statementing
@ -384,7 +412,7 @@ class File extends Managed_DataObject
* @return string * @return string
* @throws InvalidFilenameException * @throws InvalidFilenameException
*/ */
static function path($filename) public static function path($filename)
{ {
self::tryFilename($filename); self::tryFilename($filename);
@ -397,19 +425,18 @@ class File extends Managed_DataObject
return $dir . $filename; return $dir . $filename;
} }
static function url($filename) public static function url($filename)
{ {
self::tryFilename($filename); self::tryFilename($filename);
if (common_config('site', 'private')) { if (common_config('site', 'private')) {
return common_local_url(
return common_local_url('getfile', 'getfile',
array('filename' => $filename)); array('filename' => $filename)
);
} }
if (GNUsocial::useHTTPS()) { if (GNUsocial::useHTTPS()) {
$sslserver = common_config('attachments', 'sslserver'); $sslserver = common_config('attachments', 'sslserver');
if (empty($sslserver)) { if (empty($sslserver)) {
@ -455,9 +482,10 @@ class File extends Managed_DataObject
return $protocol.'://'.$server.$path.$filename; return $protocol.'://'.$server.$path.$filename;
} }
static $_enclosures = array(); public static $_enclosures = array();
function getEnclosure(){ public function getEnclosure()
{
if (isset(self::$_enclosures[$this->getID()])) { if (isset(self::$_enclosures[$this->getID()])) {
return self::$_enclosures[$this->getID()]; return self::$_enclosures[$this->getID()];
} }
@ -531,8 +559,12 @@ class File extends Managed_DataObject
} }
} }
return $image->getFileThumbnail($width, $height, $crop, return $image->getFileThumbnail(
!is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')); $width,
$height,
$crop,
!is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')
);
} }
public function getPath() public function getPath()
@ -572,7 +604,7 @@ class File extends Managed_DataObject
return $this->url; return $this->url;
} }
static public function getByUrl($url) public static function getByUrl($url)
{ {
$file = new File(); $file = new File();
$file->urlhash = self::hashurl($url); $file->urlhash = self::hashurl($url);
@ -587,7 +619,7 @@ class File extends Managed_DataObject
* @return File * @return File
* @throws NoResultException * @throws NoResultException
*/ */
static public function getByHash($hashstr) public static function getByHash($hashstr)
{ {
$file = new File(); $file = new File();
$file->filehash = strtolower($hashstr); $file->filehash = strtolower($hashstr);
@ -604,10 +636,13 @@ class File extends Managed_DataObject
throw new ServerException('URL already exists in DB'); throw new ServerException('URL already exists in DB');
} }
$sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;'; $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
$result = $this->query(sprintf($sql, $this->tableName(), $result = $this->query(sprintf(
$sql,
$this->tableName(),
$this->_quote((string)self::hashurl($url)), $this->_quote((string)self::hashurl($url)),
$this->_quote((string)$url), $this->_quote((string)$url),
$this->_quote((string)$this->urlhash))); $this->_quote((string)$this->urlhash)
));
if ($result === false) { if ($result === false) {
common_log_db_error($this, 'UPDATE', __FILE__); common_log_db_error($this, 'UPDATE', __FILE__);
throw new ServerException("Could not UPDATE {$this->tableName()}.url"); throw new ServerException("Could not UPDATE {$this->tableName()}.url");
@ -624,7 +659,7 @@ class File extends Managed_DataObject
* @return void * @return void
*/ */
function blowCache($last=false) public function blowCache($last=false)
{ {
self::blow('file:notice-ids:%s', $this->id); self::blow('file:notice-ids:%s', $this->id);
if ($last) { if ($last) {
@ -644,7 +679,7 @@ class File extends Managed_DataObject
* @return array ids of notices that link to this file * @return array ids of notices that link to this file
*/ */
function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0) public function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
{ {
// FIXME: Try to get the Profile::current() here in some other way to avoid mixing // FIXME: Try to get the Profile::current() here in some other way to avoid mixing
// the current session user with possibly background/queue processing. // the current session user with possibly background/queue processing.
@ -652,14 +687,13 @@ class File extends Managed_DataObject
return $stream->getNotices($offset, $limit, $since_id, $max_id); return $stream->getNotices($offset, $limit, $since_id, $max_id);
} }
function noticeCount() public function noticeCount()
{ {
$cacheKey = sprintf('file:notice-count:%d', $this->id); $cacheKey = sprintf('file:notice-count:%d', $this->id);
$count = self::cacheGet($cacheKey); $count = self::cacheGet($cacheKey);
if ($count === false) { if ($count === false) {
$f2p = new File_to_post(); $f2p = new File_to_post();
$f2p->file_id = $this->id; $f2p->file_id = $this->id;
@ -724,7 +758,7 @@ class File extends Managed_DataObject
return $this->update($orig); return $this->update($orig);
} }
static public function hashurl($url) public static function hashurl($url)
{ {
if (empty($url)) { if (empty($url)) {
throw new Exception('No URL provided to hash algorithm.'); throw new Exception('No URL provided to hash algorithm.');
@ -732,7 +766,7 @@ class File extends Managed_DataObject
return hash(self::URLHASH_ALG, $url); return hash(self::URLHASH_ALG, $url);
} }
static public function beforeSchemaUpdate() public static function beforeSchemaUpdate()
{ {
$table = strtolower(get_called_class()); $table = strtolower(get_called_class());
$schema = Schema::get(); $schema = Schema::get();
@ -800,11 +834,13 @@ class File extends Managed_DataObject
// urlhash is hash('sha256', $url) in the File table // urlhash is hash('sha256', $url) in the File table
echo "Updating urlhash fields in $table table..."; echo "Updating urlhash fields in $table table...";
// Maybe very MySQL specific :( // Maybe very MySQL specific :(
$tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;', $tablefix->query(sprintf(
'UPDATE %1$s SET %2$s=%3$s;',
$schema->quoteIdentifier($table), $schema->quoteIdentifier($table),
'urlhash', 'urlhash',
// The line below is "result of sha256 on column `url`" // The line below is "result of sha256 on column `url`"
'SHA2(url, 256)')); 'SHA2(url, 256)'
));
echo "DONE.\n"; echo "DONE.\n";
echo "Resuming core schema upgrade..."; echo "Resuming core schema upgrade...";
} }

View File

@ -153,9 +153,14 @@ class ImageFile extends MediaFile
// doesn't exist anyway, so it's safe to delete $imgPath // doesn't exist anyway, so it's safe to delete $imgPath
@unlink($imgPath); @unlink($imgPath);
} }
common_debug(sprintf('Exception %s caught when creating ImageFile for File id==%s ' . common_debug(sprintf(
'and imgPath==%s: %s', get_class($e), _ve($file->id), 'Exception %s caught when creating ImageFile for File id==%s ' .
_ve($imgPath), _ve($e->getMessage()))); 'and imgPath==%s: %s',
get_class($e),
_ve($file->id),
_ve($imgPath),
_ve($e->getMessage())
));
throw $e; throw $e;
} }
return $image; return $image;
@ -223,7 +228,7 @@ class ImageFile extends MediaFile
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*/ */
function copyTo($outpath) public function copyTo($outpath)
{ {
return new ImageFile(null, $this->resizeTo($outpath)); return new ImageFile(null, $this->resizeTo($outpath));
} }
@ -237,7 +242,7 @@ class ImageFile extends MediaFile
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*/ */
function resizeTo($outpath, array $box=array()) public function resizeTo($outpath, array $box=array())
{ {
$box['width'] = isset($box['width']) ? intval($box['width']) : $this->width; $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
$box['height'] = isset($box['height']) ? intval($box['height']) : $this->height; $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
@ -259,7 +264,6 @@ class ImageFile extends MediaFile
&& $box['w'] === $this->width && $box['w'] === $this->width
&& $box['h'] === $this->height && $box['h'] === $this->height
&& $this->type === $this->preferredType()) { && $this->type === $this->preferredType()) {
if (abs($this->rotate) == 90) { if (abs($this->rotate) == 90) {
// Box is rotated 90 degrees in either direction, // Box is rotated 90 degrees in either direction,
// so we have to redefine x to y and vice versa. // so we have to redefine x to y and vice versa.
@ -337,17 +341,18 @@ class ImageFile extends MediaFile
$image_dest = imagecreatetruecolor($box['width'], $box['height']); $image_dest = imagecreatetruecolor($box['width'], $box['height']);
if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) { if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
$transparent_idx = imagecolortransparent($image_src); $transparent_idx = imagecolortransparent($image_src);
if ($transparent_idx >= 0 && $transparent_idx < 255) { if ($transparent_idx >= 0 && $transparent_idx < 255) {
$transparent_color = imagecolorsforindex($image_src, $transparent_idx); $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
$transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_idx = imagecolorallocate(
$image_dest,
$transparent_color['red'],
$transparent_color['green'], $transparent_color['green'],
$transparent_color['blue']); $transparent_color['blue']
);
imagefill($image_dest, 0, 0, $transparent_idx); imagefill($image_dest, 0, 0, $transparent_idx);
imagecolortransparent($image_dest, $transparent_idx); imagecolortransparent($image_dest, $transparent_idx);
} elseif ($this->type == IMAGETYPE_PNG) { } elseif ($this->type == IMAGETYPE_PNG) {
imagealphablending($image_dest, false); imagealphablending($image_dest, false);
$transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127); $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
@ -356,8 +361,18 @@ class ImageFile extends MediaFile
} }
} }
imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], imagecopyresampled(
$box['width'], $box['height'], $box['w'], $box['h']); $image_dest,
$image_src,
0,
0,
$box['x'],
$box['y'],
$box['width'],
$box['height'],
$box['w'],
$box['h']
);
$type = $this->preferredType(); $type = $this->preferredType();
$ext = image_type_to_extension($type, true); $ext = image_type_to_extension($type, true);
@ -390,8 +405,14 @@ class ImageFile extends MediaFile
public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null) public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
{ {
return self::getScalingValues($this->width, $this->height, return self::getScalingValues(
$maxWidth, $maxHeight, $crop, $this->rotate); $this->width,
$this->height,
$maxWidth,
$maxHeight,
$crop,
$this->rotate
);
} }
/** /**
@ -409,10 +430,14 @@ class ImageFile extends MediaFile
* @return array * @return array
* @throws ServerException * @throws ServerException
*/ */
public static function getScalingValues($width, $height, public static function getScalingValues(
$maxW=null, $maxH=null, $width,
$crop=null, $rotate=0) $height,
{ $maxW=null,
$maxH=null,
$crop=null,
$rotate=0
) {
$maxW = $maxW ?: common_config('thumbnail', 'width'); $maxW = $maxW ?: common_config('thumbnail', 'width');
$maxH = $maxH ?: common_config('thumbnail', 'height'); $maxH = $maxH ?: common_config('thumbnail', 'height');
@ -565,8 +590,12 @@ class ImageFile extends MediaFile
throw new ServerException('Bad thumbnail size parameters.'); throw new ServerException('Bad thumbnail size parameters.');
} }
common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', common_debug(sprintf(
$this->fileRecord->getID(), $width, $height)); 'Generating a thumbnail of File id==%u of size %ux%u',
$this->fileRecord->getID(),
$width,
$height
));
// Perform resize and store into file // Perform resize and store into file
$this->resizeTo($outpath, $box); $this->resizeTo($outpath, $box);
@ -580,10 +609,14 @@ class ImageFile extends MediaFile
// $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it! // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
} }
return File_thumbnail::saveThumbnail($this->fileRecord->getID(), return File_thumbnail::saveThumbnail(
$this->fileRecord->getID(),
// no url since we generated it ourselves and can dynamically // no url since we generated it ourselves and can dynamically
// generate the url // generate the url
null, null,
$width, $height, $outname); $width,
$height,
$outname
);
} }
} }

View File

@ -28,7 +28,9 @@
* @link https://www.gnu.org/software/social/ * @link https://www.gnu.org/software/social/
*/ */
if (!defined('GNUSOCIAL')) { exit(1); } if (!defined('GNUSOCIAL')) {
exit(1);
}
/** /**
@ -100,17 +102,17 @@ class MediaFile
return File::path($this->filename); return File::path($this->filename);
} }
function shortUrl() public function shortUrl()
{ {
return $this->short_fileurl; return $this->short_fileurl;
} }
function getEnclosure() public function getEnclosure()
{ {
return $this->getFile()->getEnclosure(); return $this->getFile()->getEnclosure();
} }
function delete() public function delete()
{ {
@unlink($this->filepath); @unlink($this->filepath);
} }
@ -211,7 +213,7 @@ class MediaFile
return $file; return $file;
} }
function rememberFile($file, $short) public function rememberFile($file, $short)
{ {
$this->maybeAddRedir($file->id, $short); $this->maybeAddRedir($file->id, $short);
} }
@ -249,7 +251,7 @@ class MediaFile
/** /**
* The maximum allowed file size, as a string * The maximum allowed file size, as a string
*/ */
static function maxFileSize() public static function maxFileSize()
{ {
$value = self::maxFileSizeInt(); $value = self::maxFileSizeInt();
if ($value > 1024 * 1024) { if ($value > 1024 * 1024) {
@ -269,11 +271,13 @@ class MediaFile
/** /**
* The maximum allowed file size, as an int * The maximum allowed file size, as an int
*/ */
static function maxFileSizeInt() public static function maxFileSizeInt()
{ {
return min(self::sizeStrToInt(ini_get('post_max_size')), return min(
self::sizeStrToInt(ini_get('post_max_size')),
self::sizeStrToInt(ini_get('upload_max_filesize')), self::sizeStrToInt(ini_get('upload_max_filesize')),
self::sizeStrToInt(ini_get('memory_limit'))); self::sizeStrToInt(ini_get('memory_limit'))
);
} }
/** /**
@ -288,8 +292,10 @@ class MediaFile
switch (strtoupper($unit)) { switch (strtoupper($unit)) {
case 'G': case 'G':
$num *= 1024; $num *= 1024;
// no break
case 'M': case 'M':
$num *= 1024; $num *= 1024;
// no break
case 'K': case 'K':
$num *= 1024; $num *= 1024;
} }
@ -325,8 +331,10 @@ class MediaFile
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
// TRANS: Exception thrown when too large a file is uploaded. // TRANS: Exception thrown when too large a file is uploaded.
// TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB". // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
throw new ClientException(sprintf(_('That file is too big. The maximum file size is %s.'), throw new ClientException(sprintf(
self::maxFileSize())); _('That file is too big. The maximum file size is %s.'),
self::maxFileSize()
));
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
@unlink($_FILES[$param]['tmp_name']); @unlink($_FILES[$param]['tmp_name']);
// TRANS: Client exception. // TRANS: Client exception.
@ -398,7 +406,8 @@ class MediaFile
return new MediaFile($filepath, $mimetype, $filehash); return new MediaFile($filepath, $mimetype, $filehash);
} }
static function fromFilehandle($fh, Profile $scoped=null) { public static function fromFilehandle($fh, Profile $scoped=null)
{
$stream = stream_get_meta_data($fh); $stream = stream_get_meta_data($fh);
// So far we're only handling filehandles originating from tmpfile(), // So far we're only handling filehandles originating from tmpfile(),
// so we can always do hash_file on $stream['uri'] as far as I can tell! // so we can always do hash_file on $stream['uri'] as far as I can tell!
@ -431,7 +440,6 @@ class MediaFile
$filename = basename($file->getPath()); $filename = basename($file->getPath());
$mimetype = $file->mimetype; $mimetype = $file->mimetype;
} catch (NoResultException $e) { } catch (NoResultException $e) {
if ($scoped instanceof Profile) { if ($scoped instanceof Profile) {
File::respectsQuota($scoped, filesize($stream['uri'])); File::respectsQuota($scoped, filesize($stream['uri']));
@ -467,7 +475,8 @@ class MediaFile
* @fixme this seems to tie a front-end error message in, kinda confusing * @fixme this seems to tie a front-end error message in, kinda confusing
* *
*/ */
static function getUploadedMimeType(string $filepath, $originalFilename=false) { public static function getUploadedMimeType(string $filepath, $originalFilename=false)
{
// We only accept filenames to existing files // We only accept filenames to existing files
$mimetype = null; $mimetype = null;
@ -483,21 +492,18 @@ class MediaFile
* ext/fileinfo, which is otherwise enabled by default * ext/fileinfo, which is otherwise enabled by default
* since PHP 5.3 ... * since PHP 5.3 ...
*/ */
if (function_exists('finfo_file')) if (function_exists('finfo_file')) {
{
$finfo = @finfo_open(FILEINFO_MIME); $finfo = @finfo_open(FILEINFO_MIME);
// It is possible that a FALSE value is returned, if there is no magic MIME database // It is possible that a FALSE value is returned, if there is no magic MIME database
// file found on the system // file found on the system
if (is_resource($finfo)) if (is_resource($finfo)) {
{
$mime = @finfo_file($finfo, $filepath); $mime = @finfo_file($finfo, $filepath);
finfo_close($finfo); finfo_close($finfo);
/* According to the comments section of the PHP manual page, /* According to the comments section of the PHP manual page,
* it is possible that this function returns an empty string * it is possible that this function returns an empty string
* for some files (e.g. if they don't exist in the magic MIME database) * for some files (e.g. if they don't exist in the magic MIME database)
*/ */
if (is_string($mime) && preg_match($regexp, $mime, $matches)) if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
{
$mimetype = $matches[1]; $mimetype = $matches[1];
} }
} }
@ -551,12 +557,10 @@ class MediaFile
} }
} }
// Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
if (function_exists('mime_content_type')) if (function_exists('mime_content_type')) {
{
$mimetype = @mime_content_type($filepath); $mimetype = @mime_content_type($filepath);
// It's possible that mime_content_type() returns FALSE or an empty string // It's possible that mime_content_type() returns FALSE or an empty string
if ($mimetype == false && strlen($mimetype) > 0) if ($mimetype == false && strlen($mimetype) > 0) {
{
throw new ServerException(_m('Could not determine file\'s MIME type.')); throw new ServerException(_m('Could not determine file\'s MIME type.'));
} }
} }