);
}
- public static function isProtected($url) {
-
- $protected_urls_exps = array(
- 'https://www.facebook.com/login.php',
- common_path('main/login')
- );
-
- foreach ($protected_urls_exps as $protected_url_exp) {
- if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
- return true;
- }
- }
+ public static function isProtected($url)
+ {
+ $protected_urls_exps = array(
+ 'https://www.facebook.com/login.php',
+ common_path('main/login')
+ );
+
+ foreach ($protected_urls_exps as $protected_url_exp) {
+ if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
+ return true;
+ }
+ }
- return false;
+ return false;
}
/**
$file = new File;
$file->url = $given_url;
- if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
- if (!empty($redir_data['title'])) $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']);
+ if (!empty($redir_data['protected'])) {
+ $file->protected = $redir_data['protected'];
+ }
+ if (!empty($redir_data['title'])) {
+ $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();
return $file;
}
- public function saveFile() {
+ public function saveFile()
+ {
$this->urlhash = self::hashurl($this->url);
if (!Event::handle('StartFileSaveNew', array(&$this))) {
*
* @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)) {
throw new ServerException('No given URL to process');
}
return $file;
}
- public static function respectsQuota(Profile $scoped, $fileSize) {
+ public static function respectsQuota(Profile $scoped, $fileSize)
+ {
if ($fileSize > common_config('attachments', 'file_quota')) {
// 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: %1$d is the number of bytes of an uploaded file.
- $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
+ $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
$fileQuota = common_config('attachments', 'file_quota');
// TRANS: Message given if an upload is larger than the configured maximum.
// 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...
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));
+ 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
+ )
+ );
}
$file = new File;
// TRANS: Message given if an upload would exceed user quota.
// TRANS: %d (number) is the user quota in bytes and is used for plural.
throw new ClientException(
- 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.',
- common_config('attachments', 'user_quota')),
- common_config('attachments', 'user_quota')));
+ 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.',
+ 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())';
$file->query($query);
// 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.
throw new ClientException(
- 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.',
- common_config('attachments', 'monthly_quota')),
- common_config('attachments', 'monthly_quota')));
+ 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.',
+ common_config('attachments', 'monthly_quota')
+ ),
+ common_config('attachments', 'monthly_quota')
+ )
+ );
}
return true;
}
// 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);
* @return mixed|string
* @throws ClientException
*/
- static function guessMimeExtension($mimetype, $filename=null)
+ public static function guessMimeExtension($mimetype, $filename=null)
{
try {
// first see if we know the extension for our mimetype
* @param $filename
* @return false|int
*/
- static function validFilename($filename)
+ public static function validFilename($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);
}
// if successful, return the filename for easy if-statementing
* @return string
* @throws InvalidFilenameException
*/
- static function path($filename)
+ public static function path($filename)
{
self::tryFilename($filename);
return $dir . $filename;
}
- static function url($filename)
+ public static function url($filename)
{
self::tryFilename($filename);
- if (common_config('site','private')) {
-
- return common_local_url('getfile',
- array('filename' => $filename));
-
+ if (common_config('site', 'private')) {
+ return common_local_url(
+ 'getfile',
+ array('filename' => $filename)
+ );
}
if (GNUsocial::useHTTPS()) {
-
$sslserver = common_config('attachments', 'sslserver');
if (empty($sslserver)) {
if (is_string(common_config('site', 'sslserver')) &&
mb_strlen(common_config('site', 'sslserver')) > 0) {
$server = common_config('site', 'sslserver');
- } else if (common_config('site', 'server')) {
+ } elseif (common_config('site', 'server')) {
$server = common_config('site', 'server');
}
$path = common_config('site', 'path') . '/file/';
return $protocol.'://'.$server.$path.$filename;
}
- static $_enclosures = array();
+ public static $_enclosures = array();
- function getEnclosure(){
+ public function getEnclosure()
+ {
if (isset(self::$_enclosures[$this->getID()])) {
return self::$_enclosures[$this->getID()];
}
}
}
- return $image->getFileThumbnail($width, $height, $crop,
- !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale'));
+ return $image->getFileThumbnail(
+ $width,
+ $height,
+ $crop,
+ !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')
+ );
}
public function getPath()
return $this->url;
}
- static public function getByUrl($url)
+ public static function getByUrl($url)
{
$file = new File();
$file->urlhash = self::hashurl($url);
* @return File
* @throws NoResultException
*/
- static public function getByHash($hashstr)
+ public static function getByHash($hashstr)
{
$file = new File();
$file->filehash = strtolower($hashstr);
throw new ServerException('URL already exists in DB');
}
$sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
- $result = $this->query(sprintf($sql, $this->tableName(),
- $this->_quote((string)self::hashurl($url)),
- $this->_quote((string)$url),
- $this->_quote((string)$this->urlhash)));
+ $result = $this->query(sprintf(
+ $sql,
+ $this->tableName(),
+ $this->_quote((string)self::hashurl($url)),
+ $this->_quote((string)$url),
+ $this->_quote((string)$this->urlhash)
+ ));
if ($result === false) {
common_log_db_error($this, 'UPDATE', __FILE__);
throw new ServerException("Could not UPDATE {$this->tableName()}.url");
* @return void
*/
- function blowCache($last=false)
+ public function blowCache($last=false)
{
self::blow('file:notice-ids:%s', $this->id);
if ($last) {
* @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
// the current session user with possibly background/queue processing.
return $stream->getNotices($offset, $limit, $since_id, $max_id);
}
- function noticeCount()
+ public function noticeCount()
{
$cacheKey = sprintf('file:notice-count:%d', $this->id);
$count = self::cacheGet($cacheKey);
if ($count === false) {
-
$f2p = new File_to_post();
$f2p->file_id = $this->id;
$count = $f2p->count();
self::cacheSet($cacheKey, $count);
- }
+ }
return $count;
}
return $this->update($orig);
}
- static public function hashurl($url)
+ public static function hashurl($url)
{
if (empty($url)) {
throw new Exception('No URL provided to hash algorithm.');
return hash(self::URLHASH_ALG, $url);
}
- static public function beforeSchemaUpdate()
+ public static function beforeSchemaUpdate()
{
$table = strtolower(get_called_class());
$schema = Schema::get();
$dupfile->update($orig);
print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
// only start deleting with this fetch.
- while($dupfile->fetch()) {
+ while ($dupfile->fetch()) {
common_log(LOG_INFO, sprintf('Deleting duplicate File entry of %1$d: %2$d (original URL: %3$s collides with these first 191 characters: %4$s', $dupfile->id, $file->id, $origurl, $file->shortenedurl));
print ".";
$dupfile->delete();
echo "\n...now running hacky pre-schemaupdate change for $table:";
// We have to create a urlhash that is _not_ the primary key,
// transfer data and THEN run checkSchema
- $schemadef['fields']['urlhash'] = array (
+ $schemadef['fields']['urlhash'] = array(
'type' => 'varchar',
'length' => 64,
'not null' => false, // this is because when adding column, all entries will _be_ NULL!
'description' => 'sha256 of destination URL (url field)',
);
- $schemadef['fields']['url'] = array (
+ $schemadef['fields']['url'] = array(
'type' => 'text',
'description' => 'destination URL after following possible redirections',
);
// urlhash is hash('sha256', $url) in the File table
echo "Updating urlhash fields in $table table...";
// Maybe very MySQL specific :(
- $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
- $schema->quoteIdentifier($table),
- 'urlhash',
+ $tablefix->query(sprintf(
+ 'UPDATE %1$s SET %2$s=%3$s;',
+ $schema->quoteIdentifier($table),
+ 'urlhash',
// The line below is "result of sha256 on column `url`"
- 'SHA2(url, 256)'));
+ 'SHA2(url, 256)'
+ ));
echo "DONE.\n";
echo "Resuming core schema upgrade...";
}
// doesn't exist anyway, so it's safe to delete $imgPath
@unlink($imgPath);
}
- common_debug(sprintf('Exception %s caught when creating ImageFile for File id==%s ' .
- 'and imgPath==%s: %s', get_class($e), _ve($file->id),
- _ve($imgPath), _ve($e->getMessage())));
+ common_debug(sprintf(
+ 'Exception %s caught when creating ImageFile for File id==%s ' .
+ 'and imgPath==%s: %s',
+ get_class($e),
+ _ve($file->id),
+ _ve($imgPath),
+ _ve($e->getMessage())
+ ));
throw $e;
}
return $image;
* @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException
*/
- function copyTo($outpath)
+ public function copyTo($outpath)
{
return new ImageFile(null, $this->resizeTo($outpath));
}
* @throws UnsupportedMediaException
* @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['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
&& $box['w'] === $this->width
&& $box['h'] === $this->height
&& $this->type === $this->preferredType()) {
-
if (abs($this->rotate) == 90) {
// Box is rotated 90 degrees in either direction,
// so we have to redefine x to y and vice versa.
$image_dest = imagecreatetruecolor($box['width'], $box['height']);
if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
-
$transparent_idx = imagecolortransparent($image_src);
if ($transparent_idx >= 0 && $transparent_idx < 255) {
$transparent_color = imagecolorsforindex($image_src, $transparent_idx);
- $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'],
- $transparent_color['green'],
- $transparent_color['blue']);
+ $transparent_idx = imagecolorallocate(
+ $image_dest,
+ $transparent_color['red'],
+ $transparent_color['green'],
+ $transparent_color['blue']
+ );
imagefill($image_dest, 0, 0, $transparent_idx);
imagecolortransparent($image_dest, $transparent_idx);
-
} elseif ($this->type == IMAGETYPE_PNG) {
imagealphablending($image_dest, false);
$transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
}
}
- imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'],
- $box['width'], $box['height'], $box['w'], $box['h']);
+ imagecopyresampled(
+ $image_dest,
+ $image_src,
+ 0,
+ 0,
+ $box['x'],
+ $box['y'],
+ $box['width'],
+ $box['height'],
+ $box['w'],
+ $box['h']
+ );
$type = $this->preferredType();
$ext = image_type_to_extension($type, true);
public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
{
- return self::getScalingValues($this->width, $this->height,
- $maxWidth, $maxHeight, $crop, $this->rotate);
+ return self::getScalingValues(
+ $this->width,
+ $this->height,
+ $maxWidth,
+ $maxHeight,
+ $crop,
+ $this->rotate
+ );
}
/**
* @return array
* @throws ServerException
*/
- public static function getScalingValues($width, $height,
- $maxW=null, $maxH=null,
- $crop=null, $rotate=0)
- {
+ public static function getScalingValues(
+ $width,
+ $height,
+ $maxW=null,
+ $maxH=null,
+ $crop=null,
+ $rotate=0
+ ) {
$maxW = $maxW ?: common_config('thumbnail', 'width');
$maxH = $maxH ?: common_config('thumbnail', 'height');
// We read through the file til we reach the end of the file, or we've found
// at least 2 frame headers
- while(!feof($fh) && $count < 2) {
+ while (!feof($fh) && $count < 2) {
$chunk = fread($fh, 1024 * 100); //read 100kb at a time
$count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
// rewind in case we ended up in the middle of the header, but avoid
|| $box['w'] < 1 || $box['x'] >= $this->width
|| $box['h'] < 1 || $box['y'] >= $this->height) {
// Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
- common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box,true));
+ common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box, true));
throw new ServerException('Bad thumbnail size parameters.');
}
- common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u',
- $this->fileRecord->getID(), $width, $height));
+ common_debug(sprintf(
+ 'Generating a thumbnail of File id==%u of size %ux%u',
+ $this->fileRecord->getID(),
+ $width,
+ $height
+ ));
// Perform resize and store into file
$this->resizeTo($outpath, $box);
// $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
// generate the url
null,
- $width, $height, $outname);
+ $width,
+ $height,
+ $outname
+ );
}
}
* @link https://www.gnu.org/software/social/
*/
-if (!defined('GNUSOCIAL')) { exit(1); }
+if (!defined('GNUSOCIAL')) {
+ exit(1);
+}
/**
return File::path($this->filename);
}
- function shortUrl()
+ public function shortUrl()
{
return $this->short_fileurl;
}
- function getEnclosure()
+ public function getEnclosure()
{
return $this->getFile()->getEnclosure();
}
- function delete()
+ public function delete()
{
@unlink($this->filepath);
}
return $file;
}
- function rememberFile($file, $short)
+ public function rememberFile($file, $short)
{
$this->maybeAddRedir($file->id, $short);
}
/**
* The maximum allowed file size, as a string
*/
- static function maxFileSize()
+ public static function maxFileSize()
{
$value = self::maxFileSizeInt();
if ($value > 1024 * 1024) {
$value = $value/(1024*1024);
// TRANS: Number of megabytes. %d is the number.
- return sprintf(_m('%dMB','%dMB',$value),$value);
- } else if ($value > 1024) {
+ return sprintf(_m('%dMB', '%dMB', $value), $value);
+ } elseif ($value > 1024) {
$value = $value/1024;
// TRANS: Number of kilobytes. %d is the number.
- return sprintf(_m('%dkB','%dkB',$value),$value);
+ return sprintf(_m('%dkB', '%dkB', $value), $value);
} else {
// TRANS: Number of bytes. %d is the number.
- return sprintf(_m('%dB','%dB',$value),$value);
+ return sprintf(_m('%dB', '%dB', $value), $value);
}
}
/**
* The maximum allowed file size, as an int
*/
- static function maxFileSizeInt()
+ public static function maxFileSizeInt()
{
- return min(self::sizeStrToInt(ini_get('post_max_size')),
- self::sizeStrToInt(ini_get('upload_max_filesize')),
- self::sizeStrToInt(ini_get('memory_limit')));
+ return min(
+ self::sizeStrToInt(ini_get('post_max_size')),
+ self::sizeStrToInt(ini_get('upload_max_filesize')),
+ self::sizeStrToInt(ini_get('memory_limit'))
+ );
}
/**
{
$unit = substr($str, -1);
$num = substr($str, 0, -1);
- switch(strtoupper($unit)){
+ switch (strtoupper($unit)) {
case 'G':
$num *= 1024;
+ // no break
case 'M':
$num *= 1024;
+ // no break
case 'K':
$num *= 1024;
}
case UPLOAD_ERR_FORM_SIZE:
// TRANS: Exception thrown when too large a file is uploaded.
// 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.'),
- self::maxFileSize()));
+ throw new ClientException(sprintf(
+ _('That file is too big. The maximum file size is %s.'),
+ self::maxFileSize()
+ ));
case UPLOAD_ERR_PARTIAL:
@unlink($_FILES[$param]['tmp_name']);
// TRANS: Client exception.
// but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
$filepath = $file->getPath();
$mimetype = $file->mimetype;
- // XXX PHP: Upgrade to PHP 7.1
+ // XXX PHP: Upgrade to PHP 7.1
// catch (FileNotFoundException | NoResultException $e)
} catch (Exception $e) {
// We have to save the upload as a new local file. This is the normal course of action.
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);
// 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!
$filename = basename($file->getPath());
$mimetype = $file->mimetype;
-
} catch (NoResultException $e) {
if ($scoped instanceof Profile) {
File::respectsQuota($scoped, filesize($stream['uri']));
common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
// TRANS: Client exception thrown when a file upload operation fails because the file could
// TRANS: not be moved from the temporary folder to the permanent file location.
- throw new ClientException(_('File could not be moved to destination directory.' ));
+ throw new ClientException(_('File could not be moved to destination directory.'));
}
}
* @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
$mimetype = null;
* ext/fileinfo, which is otherwise enabled by default
* since PHP 5.3 ...
*/
- if (function_exists('finfo_file'))
- {
+ if (function_exists('finfo_file')) {
$finfo = @finfo_open(FILEINFO_MIME);
// It is possible that a FALSE value is returned, if there is no magic MIME database
// file found on the system
- if (is_resource($finfo))
- {
+ if (is_resource($finfo)) {
$mime = @finfo_file($finfo, $filepath);
finfo_close($finfo);
/* According to the comments section of the PHP manual page,
* 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)
*/
- if (is_string($mime) && preg_match($regexp, $mime, $matches))
- {
+ if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
$mimetype = $matches[1];
}
}
}
}
// 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);
// 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.'));
}
}