[Media] Copy media subsystem from v2 and roughly structure it for v3

This commit is contained in:
Hugo Sales 2021-04-11 20:53:23 +00:00
parent a38ee03f18
commit fe478c6104
Signed by: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0
14 changed files with 422 additions and 295 deletions

View File

@ -28,11 +28,7 @@ use App\Core\Router\RouteLoader;
class Directory extends Module class Directory extends Module
{ {
/** /**
* Map URLs to actions * Map URLs to Controllers
*
* @param RouteLoader $r
*
* @return bool hook value; true means continue processing, false means stop.
*/ */
public function onAddRoute(RouteLoader $r) public function onAddRoute(RouteLoader $r)
{ {

View File

@ -1,4 +1,6 @@
<?php <?php
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@ -13,30 +15,41 @@
// //
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
defined('GNUSOCIAL') || die(); namespace Plugin\Media\Controller;
use App\Core\Controller;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Show notice attachments * Show note attachments
* *
* @category Personal * @author Evan Prodromou <evan@status.net>
* @package GNUsocial * @author Hugo Sales <hugo@hsal.es>
* @author Evan Prodromou <evan@status.net> * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @copyright 2008-2009 StatusNet, Inc. *
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @see http://status.net/
*/ */
class AttachmentAction extends ManagedAction class Attachment extends Controller
{ {
public function handle(Request $request)
{
return [
'_template' => 'doc/tos.html.twig',
];
}
/** /**
* Attachment File object to show * Attachment File object to show
*/ */
public $attachment = null; public $attachment;
public $filehash = null; public $filehash;
public $filepath = null; public $filepath;
public $filesize = null; public $filesize;
public $mimetype = null; public $mimetype;
public $filename = null; public $filename;
/** /**
* Load attributes based on database arguments * Load attributes based on database arguments
@ -45,16 +58,17 @@ class AttachmentAction extends ManagedAction
* *
* @param array $args $_REQUEST array * @param array $args $_REQUEST array
* *
* @return bool flag
* @throws ClientException * @throws ClientException
* @throws FileNotFoundException * @throws FileNotFoundException
* @throws FileNotStoredLocallyException * @throws FileNotStoredLocallyException
* @throws InvalidFilenameException * @throws InvalidFilenameException
* @throws ServerException * @throws ServerException
*
* @return bool flag
*/ */
protected function prepare(array $args = []) protected function prepare(array $args = [])
{ {
parent::prepare($args); // parent::prepare($args);
try { try {
if (!empty($id = $this->trimmed('attachment'))) { if (!empty($id = $this->trimmed('attachment'))) {
@ -88,6 +102,8 @@ class AttachmentAction extends ManagedAction
/** /**
* Is this action read-only? * Is this action read-only?
* *
* @param mixed $args
*
* @return bool true * @return bool true
*/ */
public function isReadOnly($args): bool public function isReadOnly($args): bool
@ -102,13 +118,18 @@ class AttachmentAction extends ManagedAction
*/ */
public function title(): string public function title(): string
{ {
$a = new Attachment($this->attachment); $a = new self($this->attachment);
return $a->title(); return $a->title();
} }
public function showPage(): void public function showPage(): void
{ {
parent::showPage(); if (empty($this->filepath)) {
// if it's not a local file, gtfo
common_redirect($this->attachment->getUrl(), 303);
}
// parent::showPage();
} }
/** /**
@ -120,7 +141,7 @@ class AttachmentAction extends ManagedAction
*/ */
public function showContent(): void public function showContent(): void
{ {
$ali = new Attachment($this->attachment, $this); $ali = new self($this->attachment, $this);
$ali->show(); $ali->show();
} }
@ -147,8 +168,9 @@ class AttachmentAction extends ManagedAction
/** /**
* Last-modified date for file * Last-modified date for file
* *
* @return int last-modified date as unix timestamp
* @throws ServerException * @throws ServerException
*
* @return int last-modified date as unix timestamp
*/ */
public function lastModified(): ?int public function lastModified(): ?int
{ {
@ -169,8 +191,9 @@ class AttachmentAction extends ManagedAction
* This returns the same data (inode, size, mtime) as Apache would, * This returns the same data (inode, size, mtime) as Apache would,
* but in decimal instead of hex. * but in decimal instead of hex.
* *
* @return string etag http header
* @throws ServerException * @throws ServerException
*
* @return string etag http header
*/ */
public function etag(): ?string public function etag(): ?string
{ {
@ -185,7 +208,7 @@ class AttachmentAction extends ManagedAction
if (empty($path)) { if (empty($path)) {
return null; return null;
} }
$key = Cache::key('attachments:etag:' . $path); $key = Cache::key('attachments:etag:' . $path);
$etag = $cache->get($key); $etag = $cache->get($key);
if ($etag === false) { if ($etag === false) {
$etag = crc32(file_get_contents($path)); $etag = crc32(file_get_contents($path));

View File

@ -14,18 +14,20 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
defined('GNUSOCIAL') || die(); namespace Plugin\Media\Controller;
/** /**
* Download notice attachment * Download notice attachment
* *
* @category Personal * @category Personal
* @package GNUsocial * @package GNUsocial
* @author Mikael Nordfeldth <mmn@hethane.se> *
* @copyright 2016 Free Software Foundation, Inc http://www.fsf.org * @author Mikael Nordfeldth <mmn@hethane.se>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or late * @license https://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
*
* @see https:/gnu.io/social
*/ */
class Attachment_downloadAction extends AttachmentAction class AttachmentDownload extends Attachment
{ {
public function showPage(): void public function showPage(): void
{ {

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
defined('GNUSOCIAL') || die(); namespace Plugin\Media\Controller;
/** /**
* Show notice attachments * Show notice attachments
@ -27,9 +27,9 @@ defined('GNUSOCIAL') || die();
*/ */
class Attachment_thumbnailAction extends Attachment_viewAction class Attachment_thumbnailAction extends Attachment_viewAction
{ {
protected $thumb_w = null; // max width protected $thumb_w; // max width
protected $thumb_h = null; // max height protected $thumb_h; // max height
protected $thumb_c = null; // crop? protected $thumb_c; // crop?
protected function doPreparation() protected function doPreparation()
{ {
@ -45,6 +45,7 @@ class Attachment_thumbnailAction extends Attachment_viewAction
* requested in the GET variables (read in the constructor). Tries * requested in the GET variables (read in the constructor). Tries
* to send the most appropriate file with the correct size and * to send the most appropriate file with the correct size and
* headers or displays an error if it's not possible. * headers or displays an error if it's not possible.
*
* @throws ClientException * @throws ClientException
* @throws ReflectionException * @throws ReflectionException
* @throws ServerException * @throws ServerException
@ -56,8 +57,7 @@ class Attachment_thumbnailAction extends Attachment_viewAction
$filepath = $this->filepath; $filepath = $this->filepath;
try { try {
$thumbnail = $this->attachment->getThumbnail($this->thumb_w, $this->thumb_h, $this->thumb_c); $thumbnail = $this->attachment->getThumbnail($this->thumb_w, $this->thumb_h, $this->thumb_c);
$filename = $thumbnail->getFilename(); $file = $thumbnail->getFile();
$filepath = $thumbnail->getPath();
} catch (UseFileAsThumbnailException $e) { } catch (UseFileAsThumbnailException $e) {
// With this exception, the file exists locally $e->file; // With this exception, the file exists locally $e->file;
} catch (FileNotFoundException $e) { } catch (FileNotFoundException $e) {

View File

@ -14,17 +14,17 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
defined('GNUSOCIAL') || die(); namespace Plugin\Media\Controller;
/** /**
* View notice attachment * View notice attachment
* *
* @package GNUsocial * @package GNUsocial
* @author Mikael Nordfeldth <mmn@hethane.se> *
* @copyright 2016 Free Software Foundation, Inc http://www.fsf.org * @author Miguel Dantas <biodantasgs@gmail.com>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
*/ */
class Attachment_viewAction extends AttachmentAction class AttachmentView extends Attachment
{ {
public function showPage(): void public function showPage(): void
{ {

48
plugins/Media/Media.php Normal file
View File

@ -0,0 +1,48 @@
<?php
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Plugin\Media;
use App\Core\Event;
use App\Core\Module;
use App\Core\Router\RouteLoader;
class Media extends Module
{
/**
* Map URLs to Controllers
*/
public function onAddRoute(RouteLoader $r)
{
// foreach (['' => 'attachment',
// '/view' => 'attachment_view',
// '/download' => 'attachment_download',
// '/thumbnail' => 'attachment_thumbnail'] as $postfix => $action) {
// foreach (['filehash' => '[A-Za-z0-9._-]{64}',
// 'attachment' => '[0-9]+'] as $type => $match) {
// $r->connect($action, "attachment/:{$type}{$postfix}",
// ['action' => $action],
// [$type => $match]);
// }
// }
$r->connect('attachment', '/attachment/{filehash<[A-Za-z0-9._-]{64}>}', Controller\Attachment::class);
return Event::next;
}
}

View File

@ -28,7 +28,8 @@
* @copyright 2008, 2019-2020 Free Software Foundation http://fsf.org * @copyright 2008, 2019-2020 Free Software Foundation http://fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
*/ */
defined('GNUSOCIAL') || die();
namespace Plugin\Media\Util;
use Intervention\Image\ImageManagerStatic as Image; use Intervention\Image\ImageManagerStatic as Image;
@ -55,93 +56,92 @@ class ImageFile extends MediaFile
public $animated; // Animated image? (has more than 1 frame). null means untested public $animated; // Animated image? (has more than 1 frame). null means untested
public $mimetype; // The _ImageFile_ mimetype, _not_ the originating File object public $mimetype; // The _ImageFile_ mimetype, _not_ the originating File object
/** // /**
* ImageFile constructor. // * ImageFile constructor.
* // *
* @param int|null $id The DB id of the file. Int if known, null if not. // * @param int|null $id The DB id of the file. Int if known, null if not.
* If null, it searches for it. If -1, it skips all DB // * If null, it searches for it. If -1, it skips all DB
* interactions (useful for temporary objects) // * interactions (useful for temporary objects)
* @param string $filepath The path of the file this media refers to. Required // * @param string $filepath The path of the file this media refers to. Required
* @param string|null $filehash The hash of the file, if known. Optional // * @param string|null $filehash The hash of the file, if known. Optional
* @param string|null $fileurl // *
* @throws ClientException // * @throws ClientException
* @throws NoResultException // * @throws NoResultException
* @throws ServerException // * @throws ServerException
* @throws UnsupportedMediaException // * @throws UnsupportedMediaException
*/ // */
public function __construct(?int $id = null, string $filepath, ?string $filehash = null, ?string $fileurl = null) // public function __construct(?int $id = null, string $filepath, ?string $filehash = null)
{ // {
$old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit')); // $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
// These do not have to be the same as fileRecord->filename for example, // // These do not have to be the same as fileRecord->filename for example,
// since we may have generated an image source file from something else! // // since we may have generated an image source file from something else!
$this->filepath = $filepath; // $this->filepath = $filepath;
$this->filename = basename($filepath); // $this->filename = basename($filepath);
$img = Image::make($this->filepath); // $img = Image::make($this->filepath);
$this->mimetype = $img->mime(); // $this->mimetype = $img->mime();
$cmp = function ($obj, $type) { // $cmp = function ($obj, $type) {
if ($obj->mimetype == image_type_to_mime_type($type)) { // if ($obj->mimetype == image_type_to_mime_type($type)) {
$obj->type = $type; // $obj->type = $type;
return true; // return true;
} // }
return false; // return false;
}; // };
if (!(($cmp($this, IMAGETYPE_GIF) && function_exists('imagecreatefromgif')) || // if (!(($cmp($this, IMAGETYPE_GIF) && function_exists('imagecreatefromgif')) ||
($cmp($this, IMAGETYPE_JPEG) && function_exists('imagecreatefromjpeg')) || // ($cmp($this, IMAGETYPE_JPEG) && function_exists('imagecreatefromjpeg')) ||
($cmp($this, IMAGETYPE_BMP) && function_exists('imagecreatefrombmp')) || // ($cmp($this, IMAGETYPE_BMP) && function_exists('imagecreatefrombmp')) ||
($cmp($this, IMAGETYPE_WBMP) && function_exists('imagecreatefromwbmp')) || // ($cmp($this, IMAGETYPE_WBMP) && function_exists('imagecreatefromwbmp')) ||
($cmp($this, IMAGETYPE_XBM) && function_exists('imagecreatefromxbm')) || // ($cmp($this, IMAGETYPE_XBM) && function_exists('imagecreatefromxbm')) ||
($cmp($this, IMAGETYPE_PNG) && function_exists('imagecreatefrompng')) || // ($cmp($this, IMAGETYPE_PNG) && function_exists('imagecreatefrompng')) ||
($cmp($this, IMAGETYPE_WEBP) && function_exists('imagecreatefromwebp')) // ($cmp($this, IMAGETYPE_WEBP) && function_exists('imagecreatefromwebp'))
) // )
) { // ) {
common_debug("Mimetype '{$this->mimetype}' was not recognized as a supported format"); // common_debug("Mimetype '{$this->mimetype}' was not recognized as a supported format");
// TRANS: Exception thrown when trying to upload an unsupported image file format. // // TRANS: Exception thrown when trying to upload an unsupported image file format.
throw new UnsupportedMediaException(_m('Unsupported image format.'), $this->filepath); // throw new UnsupportedMediaException(_m('Unsupported image format.'), $this->filepath);
} // }
$this->width = $img->width(); // $this->width = $img->width();
$this->height = $img->height(); // $this->height = $img->height();
parent::__construct( // parent::__construct(
$filepath, // $filepath,
$this->mimetype, // $this->mimetype,
$filehash, // $filehash,
$id, // $id
$fileurl // );
);
if ($this->type === IMAGETYPE_JPEG) { // if ($this->type === IMAGETYPE_JPEG) {
// Orientation value to rotate thumbnails properly // // Orientation value to rotate thumbnails properly
$exif = @$img->exif(); // $exif = @$img->exif();
if (is_array($exif) && isset($exif['Orientation'])) { // if (is_array($exif) && isset($exif['Orientation'])) {
switch ((int)($exif['Orientation'])) { // switch ((int)($exif['Orientation'])) {
case 1: // top is top // case 1: // top is top
$this->rotate = 0; // $this->rotate = 0;
break; // break;
case 3: // top is bottom // case 3: // top is bottom
$this->rotate = 180; // $this->rotate = 180;
break; // break;
case 6: // top is right // case 6: // top is right
$this->rotate = -90; // $this->rotate = -90;
break; // break;
case 8: // top is left // case 8: // top is left
$this->rotate = 90; // $this->rotate = 90;
break; // break;
} // }
// If we ever write this back, Orientation should be set to '1' // // If we ever write this back, Orientation should be set to '1'
} // }
} elseif ($this->type === IMAGETYPE_GIF) { // } elseif ($this->type === IMAGETYPE_GIF) {
$this->animated = $this->isAnimatedGif(); // $this->animated = $this->isAnimatedGif();
} // }
Event::handle('FillImageFileMetadata', [$this]); // Event::handle('FillImageFileMetadata', [$this]);
$img->destroy(); // $img->destroy();
ini_set('memory_limit', $old_limit); // Restore the old memory limit // ini_set('memory_limit', $old_limit); // Restore the old memory limit
} // }
/** /**
* Shortcut method to get an ImageFile from a File * Shortcut method to get an ImageFile from a File
@ -153,10 +153,24 @@ class ImageFile extends MediaFile
* @throws NoResultException * @throws NoResultException
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException
*
* @return ImageFile
*/ */
public static function fromFileObject(File $file) public static function fromFileObject(File $file)
{ {
$media = common_get_mime_media($file->mimetype); $imgPath = null;
$media = common_get_mime_media($file->mimetype);
if (Event::handle('CreateFileImageThumbnailSource', [$file, &$imgPath, $media])) {
if (empty($file->filename) && !file_exists($imgPath)) {
throw new FileNotFoundException($imgPath);
}
// First some mimetype specific exceptions
switch ($file->mimetype) {
case 'image/svg+xml':
throw new UseFileAsThumbnailException($file);
}
// And we'll only consider it an image if it has such a media type // And we'll only consider it an image if it has such a media type
if ($media !== 'image') { if ($media !== 'image') {
@ -183,17 +197,18 @@ class ImageFile extends MediaFile
* Uses MediaFile's `fromUpload` to do the majority of the work * Uses MediaFile's `fromUpload` to do the majority of the work
* and ensures the uploaded file is in fact an image. * and ensures the uploaded file is in fact an image.
* *
* @param string $param * @param string $param
* @param null|Profile $scoped * @param null|Profile $scoped
* *
* @return ImageFile
* @throws NoResultException * @throws NoResultException
* @throws NoUploadedMediaException * @throws NoUploadedMediaException
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*
* @throws ClientException * @throws ClientException
*
* @return ImageFile
*
*/ */
public static function fromUpload(string $param = 'upload', ?Profile $scoped = null): self public static function fromUpload(string $param = 'upload', ?Profile $scoped = null): self
{ {
@ -229,6 +244,8 @@ class ImageFile extends MediaFile
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*
* @return ImageFile
*/ */
public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null): self public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null): self
{ {
@ -270,13 +287,14 @@ class ImageFile extends MediaFile
* *
* @param string $outpath * @param string $outpath
* *
* @return ImageFile the image stored at target path
* @throws NoResultException * @throws NoResultException
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*
* @throws ClientException * @throws ClientException
*
* @return ImageFile the image stored at target path
*
*/ */
public function copyTo($outpath) public function copyTo($outpath)
{ {
@ -287,22 +305,23 @@ class ImageFile extends MediaFile
* Create and save a thumbnail image. * Create and save a thumbnail image.
* *
* @param string $outpath * @param string $outpath
* @param array $box width, height, boundary box (x,y,w,h) defaults to full image * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
*
* @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException
* *
* @return string full local filesystem filename * @return string full local filesystem filename
* @return string full local filesystem filename * @return string full local filesystem filename
* @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException
* *
*/ */
public function resizeTo($outpath, array $box = []) public function resizeTo($outpath, array $box = [])
{ {
$box['width'] = isset($box['width']) ? (int)($box['width']) : $this->width; $box['width'] = isset($box['width']) ? (int) ($box['width']) : $this->width;
$box['height'] = isset($box['height']) ? (int)($box['height']) : $this->height; $box['height'] = isset($box['height']) ? (int) ($box['height']) : $this->height;
$box['x'] = isset($box['x']) ? (int)($box['x']) : 0; $box['x'] = isset($box['x']) ? (int) ($box['x']) : 0;
$box['y'] = isset($box['y']) ? (int)($box['y']) : 0; $box['y'] = isset($box['y']) ? (int) ($box['y']) : 0;
$box['w'] = isset($box['w']) ? (int)($box['w']) : $this->width; $box['w'] = isset($box['w']) ? (int) ($box['w']) : $this->width;
$box['h'] = isset($box['h']) ? (int)($box['h']) : $this->height; $box['h'] = isset($box['h']) ? (int) ($box['h']) : $this->height;
if (!file_exists($this->filepath)) { if (!file_exists($this->filepath)) {
// TRANS: Exception thrown during resize when image has been registered as present, // TRANS: Exception thrown during resize when image has been registered as present,
@ -321,20 +340,20 @@ class ImageFile extends MediaFile
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.
$tmp = $box['width']; $tmp = $box['width'];
$box['width'] = $box['height']; $box['width'] = $box['height'];
$box['height'] = $tmp; $box['height'] = $tmp;
$tmp = $box['x']; $tmp = $box['x'];
$box['x'] = $box['y']; $box['x'] = $box['y'];
$box['y'] = $tmp; $box['y'] = $tmp;
$tmp = $box['w']; $tmp = $box['w'];
$box['w'] = $box['h']; $box['w'] = $box['h'];
$box['h'] = $tmp; $box['h'] = $tmp;
} }
} }
$this->height = $box['h']; $this->height = $box['h'];
$this->width = $box['w']; $this->width = $box['w'];
if (Event::handle('StartResizeImageFile', [$this, $outpath, $box])) { if (Event::handle('StartResizeImageFile', [$this, $outpath, $box])) {
$outpath = $this->resizeToFile($outpath, $box); $outpath = $this->resizeToFile($outpath, $box);
@ -441,9 +460,10 @@ class ImageFile extends MediaFile
* @param $crop int Crop to the size (not preserving aspect ratio) * @param $crop int Crop to the size (not preserving aspect ratio)
* @param int $rotate * @param int $rotate
* *
* @return array
* @throws ServerException * @throws ServerException
* *
* @return array
*
*/ */
public static function getScalingValues( public static function getScalingValues(
$width, $width,
@ -467,8 +487,8 @@ class ImageFile extends MediaFile
// Because GD doesn't understand EXIF orientation etc. // Because GD doesn't understand EXIF orientation etc.
if (abs($rotate) == 90) { if (abs($rotate) == 90) {
$tmp = $width; $tmp = $width;
$width = $height; $width = $height;
$height = $tmp; $height = $tmp;
} }
@ -481,7 +501,7 @@ class ImageFile extends MediaFile
if ($crop) { if ($crop) {
$s_ar = $width / $height; $s_ar = $width / $height;
$t_ar = $maxW / $maxH; $t_ar = $maxW / $maxH;
$rw = $maxW; $rw = $maxW;
$rh = $maxH; $rh = $maxH;
@ -567,12 +587,12 @@ class ImageFile extends MediaFile
// Throws FileNotFoundException or FileNotStoredLocallyException // Throws FileNotFoundException or FileNotStoredLocallyException
$this->filepath = $this->fileRecord->getFileOrThumbnailPath(); $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
$filename = basename($this->filepath); $filename = basename($this->filepath);
if ($width === null) { if ($width === null) {
$width = common_config('thumbnail', 'width'); $width = common_config('thumbnail', 'width');
$height = common_config('thumbnail', 'height'); $height = common_config('thumbnail', 'height');
$crop = common_config('thumbnail', 'crop'); $crop = common_config('thumbnail', 'crop');
} }
if (!$upscale) { if (!$upscale) {
@ -586,7 +606,7 @@ class ImageFile extends MediaFile
if ($height === null) { if ($height === null) {
$height = $width; $height = $width;
$crop = true; $crop = true;
} }
// Get proper aspect ratio width and height before lookup // Get proper aspect ratio width and height before lookup
@ -597,18 +617,18 @@ class ImageFile extends MediaFile
$thumb = File_thumbnail::pkeyGet([ $thumb = File_thumbnail::pkeyGet([
'file_id' => $this->fileRecord->getID(), 'file_id' => $this->fileRecord->getID(),
'width' => $width, 'width' => $width,
'height' => $height, 'height' => $height,
]); ]);
if ($thumb instanceof File_thumbnail) { if ($thumb instanceof File_thumbnail) {
$this->height = $height; $this->height = $height;
$this->width = $width; $this->width = $width;
return $thumb; return $thumb;
} }
$type = $this->preferredType(); $type = $this->preferredType();
$ext = image_type_to_extension($type, true); $ext = image_type_to_extension($type, true);
// Decoding returns null if the file is in the old format // Decoding returns null if the file is in the old format
$filename = MediaFile::decodeFilename(basename($this->filepath)); $filename = MediaFile::decodeFilename(basename($this->filepath));
// Encoding null makes the file use 'untitled', and also replaces the extension // Encoding null makes the file use 'untitled', and also replaces the extension
@ -617,8 +637,8 @@ class ImageFile extends MediaFile
// The boundary box for our resizing // The boundary box for our resizing
$box = [ $box = [
'width' => $width, 'height' => $height, 'width' => $width, 'height' => $height,
'x' => $x, 'y' => $y, 'x' => $x, 'y' => $y,
'w' => $w, 'h' => $h, 'w' => $w, 'h' => $h,
]; ];
$outpath = File_thumbnail::path( $outpath = File_thumbnail::path(
@ -643,7 +663,7 @@ class ImageFile extends MediaFile
)); ));
$this->height = $box['height']; $this->height = $box['height'];
$this->width = $box['width']; $this->width = $box['width'];
// Perform resize and store into file // Perform resize and store into file
$outpath = $this->resizeTo($outpath, $box); $outpath = $this->resizeTo($outpath, $box);

View File

@ -28,9 +28,8 @@
* @copyright 2008-2009, 2019-2021 Free Software Foundation http://fsf.org * @copyright 2008-2009, 2019-2021 Free Software Foundation http://fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
*/ */
defined('GNUSOCIAL') || die();
require_once INSTALLDIR . '/lib/util/tempfile.php'; namespace Plugin\Media\Util;
/** /**
* Class responsible for abstracting media files * Class responsible for abstracting media files
@ -45,46 +44,52 @@ class MediaFile
public $short_fileurl; public $short_fileurl;
public $mimetype; public $mimetype;
/** // /**
* MediaFile constructor. // * MediaFile constructor.
* // *
* @param string|null $filepath The path of the file this media refers to. Required // * @param string $filepath The path of the file this media refers to. Required
* @param string $mimetype The mimetype of the file. Required // * @param string $mimetype The mimetype of the file. Required
* @param string|null $filehash The hash of the file, if known. Optional // * @param string|null $filehash The hash of the file, if known. Optional
* @param int|null $id The DB id of the file. Int if known, null if not. // * @param int|null $id The DB id of the file. Int if known, null if not.
* If null, it searches for it. If -1, it skips all DB // * If null, it searches for it. If -1, it skips all DB
* interactions (useful for temporary objects) // * interactions (useful for temporary objects)
* @param string|null $fileurl Provide if remote // *
* @throws ClientException // * @throws ClientException
* @throws NoResultException // * @throws NoResultException
* @throws ServerException // * @throws ServerException
*/ // */
public function __construct(?string $filepath = null, string $mimetype, ?string $filehash = null, ?int $id = null, ?string $fileurl = null) // public function __construct(string $filepath, string $mimetype, ?string $filehash = null, ?int $id = null)
{ // {
$this->filepath = $filepath; // $this->filepath = $filepath;
$this->filename = basename($this->filepath); // $this->filename = basename($this->filepath);
$this->mimetype = $mimetype; // $this->mimetype = $mimetype;
$this->filehash = is_null($filepath) ? null : self::getHashOfFile($this->filepath, $filehash); // $this->filehash = self::getHashOfFile($this->filepath, $filehash);
$this->id = $id; // $this->id = $id;
$this->fileurl = $fileurl;
// If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB, // // If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB,
// or add redirects // // or add redirects
if ($this->id !== -1) { // if ($this->id !== -1) {
if (!empty($this->id)) { // if (!empty($this->id)) {
// If we have an id, load it // // If we have an id, load it
$this->fileRecord = new File(); // $this->fileRecord = new File();
$this->fileRecord->id = $this->id; // $this->fileRecord->id = $this->id;
if (!$this->fileRecord->find(true)) { // if (!$this->fileRecord->find(true)) {
// If we have set an ID, we need that ID to exist! // // If we have set an ID, we need that ID to exist!
throw new NoResultException($this->fileRecord); // throw new NoResultException($this->fileRecord);
} // }
} else { // } else {
// Otherwise, store it // // Otherwise, store it
$this->fileRecord = $this->storeFile(); // $this->fileRecord = $this->storeFile();
} // }
}
} // $this->fileurl = common_local_url(
// 'attachment',
// ['attachment' => $this->fileRecord->id]
// );
// $this->short_fileurl = common_shorten_url($this->fileurl);
// }
// }
/** /**
* Shortcut method to get a MediaFile from a File * Shortcut method to get a MediaFile from a File
@ -177,12 +182,13 @@ class MediaFile
* *
* This won't work for files >2GiB because PHP uses only 32bit. * This won't work for files >2GiB because PHP uses only 32bit.
* *
* @param string $filepath * @param string $filepath
* @param null|string $filehash * @param null|string $filehash
* *
* @return string
* @throws ServerException * @throws ServerException
* *
* @return string
*
*/ */
public static function getHashOfFile(string $filepath, $filehash = null) public static function getHashOfFile(string $filepath, $filehash = null)
{ {
@ -201,10 +207,11 @@ class MediaFile
/** /**
* Retrieve or insert as a file in the DB * Retrieve or insert as a file in the DB
* *
* @return object File
* @throws ServerException * @throws ServerException
*
* @throws ClientException * @throws ClientException
*
* @return object File
*
*/ */
protected function storeFile() protected function storeFile()
{ {
@ -224,11 +231,11 @@ class MediaFile
$file->url = $this->fileurl; $file->url = $this->fileurl;
$file->urlhash = is_null($file->url) ? null : File::hashurl($file->url); $file->urlhash = is_null($file->url) ? null : File::hashurl($file->url);
$file->filehash = $this->filehash; $file->filehash = $this->filehash;
$file->size = filesize($this->filepath); $file->size = filesize($this->filepath);
if ($file->size === false) { if ($file->size === false) {
throw new ServerException('Could not read file to get its size'); throw new ServerException('Could not read file to get its size');
} }
$file->date = time(); $file->date = time();
$file->mimetype = $this->mimetype; $file->mimetype = $this->mimetype;
$file_id = $file->insert(); $file_id = $file->insert();
@ -297,13 +304,14 @@ class MediaFile
* Encodes a file name and a file hash in the new file format, which is used to avoid * Encodes a file name and a file hash in the new file format, which is used to avoid
* having an extension in the file, removing trust in extensions, while keeping the original name * having an extension in the file, removing trust in extensions, while keeping the original name
* *
* @param null|string $original_name * @param null|string $original_name
* @param string $filehash * @param string $filehash
* @param null|string|bool $ext from File::getSafeExtension * @param null|bool|string $ext from File::getSafeExtension
* *
* @return string
* @throws ClientException * @throws ClientException
* @throws ServerException * @throws ServerException
*
* @return string
*/ */
public static function encodeFilename($original_name, string $filehash, $ext = null): string public static function encodeFilename($original_name, string $filehash, $ext = null): string
{ {
@ -322,7 +330,7 @@ class MediaFile
if (!empty($ext)) { if (!empty($ext)) {
// Remove dots if we have them (make sure they're not repeated) // Remove dots if we have them (make sure they're not repeated)
$ext = preg_replace('/^\.+/', '', $ext); $ext = preg_replace('/^\.+/', '', $ext);
$original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name); $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
} }
@ -386,9 +394,9 @@ class MediaFile
* This format should be respected. Notice the dash, which is important to distinguish it from the previous * This format should be respected. Notice the dash, which is important to distinguish it from the previous
* format ("{$hash}.{$ext}") * format ("{$hash}.{$ext}")
* *
* @param string $param Form name * @param string $param Form name
* @param Profile|null $scoped * @param null|Profile $scoped
* @return ImageFile|MediaFile *
* @throws ClientException * @throws ClientException
* @throws InvalidFilenameException * @throws InvalidFilenameException
* @throws NoResultException * @throws NoResultException
@ -396,6 +404,8 @@ class MediaFile
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*
* @return ImageFile|MediaFile
*/ */
public static function fromUpload(string $param = 'media', ?Profile $scoped = null) public static function fromUpload(string $param = 'media', ?Profile $scoped = null)
{ {
@ -478,7 +488,7 @@ class MediaFile
} }
$mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']); $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
$media = common_get_mime_media($mimetype); $media = common_get_mime_media($mimetype);
$basename = basename($_FILES[$param]['name']); $basename = basename($_FILES[$param]['name']);
@ -488,7 +498,7 @@ class MediaFile
// Validate the image by re-encoding it. Additionally normalizes old formats to WebP, // Validate the image by re-encoding it. Additionally normalizes old formats to WebP,
// keeping GIF untouched if animated // keeping GIF untouched if animated
$outpath = $img->resizeTo($img->filepath); $outpath = $img->resizeTo($img->filepath);
$ext = image_type_to_extension($img->preferredType(), false); $ext = image_type_to_extension($img->preferredType(), false);
} }
$filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename)); $filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename));
@ -532,6 +542,8 @@ class MediaFile
* @throws ServerException * @throws ServerException
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
*
* @return ImageFile|MediaFile
*/ */
public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null) public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null)
{ {
@ -622,7 +634,7 @@ class MediaFile
// Additionally normalises old formats to PNG, // Additionally normalises old formats to PNG,
// keeping JPEG and GIF untouched. // keeping JPEG and GIF untouched.
$outpath = $img->resizeTo($img->filepath); $outpath = $img->resizeTo($img->filepath);
$ext = image_type_to_extension($img->preferredType(), false); $ext = image_type_to_extension($img->preferredType(), false);
} }
$filename = self::encodeFilename( $filename = self::encodeFilename(
$basename, $basename,
@ -655,6 +667,9 @@ class MediaFile
return new self($filepath, $mimetype, $filehash, $file_id, $url); return new self($filepath, $mimetype, $filehash, $file_id, $url);
} }
/**
* Construct media fiile from an upload
*/
public static function fromFileInfo(SplFileInfo $finfo, Profile $scoped = null) public static function fromFileInfo(SplFileInfo $finfo, Profile $scoped = null)
{ {
$filehash = hash_file(File::FILEHASH_ALG, $finfo->getRealPath()); $filehash = hash_file(File::FILEHASH_ALG, $finfo->getRealPath());
@ -712,16 +727,17 @@ class MediaFile
/** /**
* Attempt to identify the content type of a given file. * Attempt to identify the content type of a given file.
* *
* @param string $filepath filesystem path as string (file must exist) * @param string $filepath filesystem path as string (file must exist)
* @param bool $originalFilename (optional) for extension-based detection * @param bool $originalFilename (optional) for extension-based detection
*
* @throws ServerException
* @throws ClientException if type is known, but not supported for local uploads
* *
* @return string * @return string
* *
* @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
* *
* @throws ServerException
* *
* @throws ClientException if type is known, but not supported for local uploads
*/ */
public static function getUploadedMimeType(string $filepath, $originalFilename = false) public static function getUploadedMimeType(string $filepath, $originalFilename = false)
{ {
@ -821,7 +837,7 @@ class MediaFile
'text/plain', 'text/plain',
'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
// TODO: for XML we could do better content-based sniffing too // TODO: for XML we could do better content-based sniffing too
'text/xml',]; 'text/xml', ];
$supported = common_config('attachments', 'supported'); $supported = common_config('attachments', 'supported');

View File

@ -21,16 +21,16 @@
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @author Sarven Capadisli <csarven@status.net> * @author Sarven Capadisli <csarven@status.net>
* @copyright 2008 StatusNet, Inc. * @copyright 2008 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
*/ */
if (!defined('GNUSOCIAL')) { namespace Plugin\Media\media;
exit(1);
}
/** /**
* used for one-off attachment action * used for one-off attachment action
@ -41,7 +41,7 @@ class Attachment extends AttachmentListItem
{ {
if (Event::handle('StartShowAttachmentLink', [$this->out, $this->attachment])) { if (Event::handle('StartShowAttachmentLink', [$this->out, $this->attachment])) {
$this->out->elementStart('div', ['id' => 'attachment_view', $this->out->elementStart('div', ['id' => 'attachment_view',
'class' => 'h-entry']); 'class' => 'h-entry', ]);
$this->out->elementStart('div', 'entry-title'); $this->out->elementStart('div', 'entry-title');
$this->out->element('a', $this->linkAttr(), _m('Download link')); $this->out->element('a', $this->linkAttr(), _m('Download link'));
$this->out->elementEnd('div'); $this->out->elementEnd('div');
@ -61,6 +61,6 @@ class Attachment extends AttachmentListItem
public function linkAttr() public function linkAttr()
{ {
return ['rel' => 'external', 'href' => $this->attachment->getUrl(null)]; return ['rel' => 'external', 'href' => $this->attachment->getAttachmentDownloadUrl()];
} }
} }

View File

@ -21,14 +21,16 @@
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @author Sarven Capadisli <csarven@status.net> * @author Sarven Capadisli <csarven@status.net>
* @copyright 2008 StatusNet, Inc. * @copyright 2008 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
*/ */
if (!defined('GNUSOCIAL')) { exit(1); } namespace Plugin\Media\media;
/** /**
* widget for displaying a list of notice attachments * widget for displaying a list of notice attachments
@ -40,29 +42,30 @@ if (!defined('GNUSOCIAL')) { exit(1); }
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
* @see Notice * @see Notice
* @see NoticeListItem * @see NoticeListItem
* @see ProfileNoticeList * @see ProfileNoticeList
*/ */
class AttachmentList extends Widget class AttachmentList
{ {
/** the current stream of notices being displayed. */ /** the current stream of notices being displayed. */
public $notice;
var $notice = null; // /**
// * constructor
/** // *
* constructor // * @param Notice $notice stream of notices from DB_DataObject
* // */
* @param Notice $notice stream of notices from DB_DataObject // function __construct(Notice $notice, $out=null)
*/ // {
function __construct(Notice $notice, $out=null) // // parent::__construct($out);
{ // $this->notice = $notice;
parent::__construct($out); // }
$this->notice = $notice;
}
/** /**
* show the list of attachments * show the list of attachments
@ -72,16 +75,22 @@ class AttachmentList extends Widget
* *
* @return int count of items listed. * @return int count of items listed.
*/ */
function show() public function show()
{ {
$attachments = $this->notice->attachments(); $attachments = $this->notice->attachments();
foreach ($attachments as $key => $att) {
// Remove attachments which are not representable with neither a title nor thumbnail
if ($att->getTitle() === _('Untitled attachment') && !$att->hasThumbnail()) {
unset($attachments[$key]);
}
}
if (!count($attachments)) { if (!count($attachments)) {
return 0; return 0;
} }
if ($this->notice->getProfile()->isSilenced()) { if ($this->notice->getProfile()->isSilenced()) {
// TRANS: Message for inline attachments list in notices when the author has been silenced. // TRANS: Message for inline attachments list in notices when the author has been silenced.
$this->element('div', ['class'=>'error'], $this->element('div', ['class' => 'error'],
_('Attachments are hidden because this profile has been silenced.')); _('Attachments are hidden because this profile has been silenced.'));
return 0; return 0;
} }
@ -98,12 +107,12 @@ class AttachmentList extends Widget
return count($attachments); return count($attachments);
} }
function showListStart() public function showListStart()
{ {
$this->out->elementStart('ol', array('class' => 'attachments')); $this->out->elementStart('ol', ['class' => 'attachments']);
} }
function showListEnd() public function showListEnd()
{ {
$this->out->elementEnd('ol'); $this->out->elementEnd('ol');
} }
@ -115,7 +124,7 @@ class AttachmentList extends Widget
* *
* @return AttachmentListItem a list item for displaying the attachment * @return AttachmentListItem a list item for displaying the attachment
*/ */
function newListItem(File $attachment) public function newListItem(File $attachment)
{ {
return new AttachmentListItem($attachment, $this->out); return new AttachmentListItem($attachment, $this->out);
} }

View File

@ -21,14 +21,16 @@
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @author Sarven Capadisli <csarven@status.net> * @author Sarven Capadisli <csarven@status.net>
* @copyright 2008 StatusNet, Inc. * @copyright 2008 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
*/ */
if (!defined('GNUSOCIAL')) { exit(1); } namespace Plugin\Media\media;
/** /**
* widget for displaying a single notice * widget for displaying a single notice
@ -41,32 +43,35 @@ if (!defined('GNUSOCIAL')) { exit(1); }
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
* @see NoticeList * @see NoticeList
* @see ProfileNoticeListItem * @see ProfileNoticeListItem
*/ */
class AttachmentListItem extends Widget class AttachmentListItem
{ {
/** The attachment this item will show. */ /** The attachment this item will show. */
public $attachment;
var $attachment = null;
/** /**
* @param File $attachment the attachment we will display * @param File $attachment the attachment we will display
*/ */
function __construct(File $attachment, $out=null) // function __construct(File $attachment, $out=null)
{ // {
parent::__construct($out); // // parent::__construct($out);
$this->attachment = $attachment; // $this->attachment = $attachment;
} // }
function title() { public function title()
{
return $this->attachment->getTitle() ?: MediaFile::getDisplayName($this->attachment); return $this->attachment->getTitle() ?: MediaFile::getDisplayName($this->attachment);
} }
function linkTitle() { public function linkTitle()
{
return $this->title(); return $this->title();
} }
@ -78,13 +83,13 @@ class AttachmentListItem extends Widget
* *
* @return void * @return void
*/ */
function show() public function show()
{ {
$this->showStart(); $this->showStart();
try { try {
$this->showNoticeAttachment(); $this->showNoticeAttachment();
} catch (Exception $e) { } catch (Exception $e) {
$this->element('div', ['class'=>'error'], $e->getMessage()); $this->element('div', ['class' => 'error'], $e->getMessage());
common_debug($e->getMessage()); common_debug($e->getMessage());
} }
$this->showEnd(); $this->showEnd();
@ -98,17 +103,19 @@ class AttachmentListItem extends Widget
]; ];
} }
function showNoticeAttachment() public function showNoticeAttachment()
{ {
$this->showRepresentation(); $this->showRepresentation();
} }
function showRepresentation() /**
* Show in HTML
*/
public function showRepresentation()
{ {
$enclosure = $this->attachment->getEnclosure(); $enclosure = $this->attachment->getEnclosure();
if (Event::handle('StartShowAttachmentRepresentation', [$this->out, $this->attachment])) { if (Event::handle('StartShowAttachmentRepresentation', [$this->out, $this->attachment])) {
$this->out->elementStart('label'); $this->out->elementStart('label');
$this->out->element('a', ['rel' => 'external', 'href' => $this->attachment->getAttachmentUrl()], $this->title()); $this->out->element('a', ['rel' => 'external', 'href' => $this->attachment->getAttachmentUrl()], $this->title());
$this->out->elementEnd('label'); $this->out->elementEnd('label');
@ -208,7 +215,7 @@ class AttachmentListItem extends Widget
} }
} }
} }
Event::handle('EndShowAttachmentRepresentation', array($this->out, $this->attachment)); Event::handle('EndShowAttachmentRepresentation', [$this->out, $this->attachment]);
} }
protected function showHtmlFile(File $attachment) protected function showHtmlFile(File $attachment)
@ -225,19 +232,19 @@ class AttachmentListItem extends Widget
protected function scrubHtmlFile(File $attachment) protected function scrubHtmlFile(File $attachment)
{ {
$path = $attachment->getPath(); $path = $attachment->getPath();
$raw = file_get_contents($path); $raw = file_get_contents($path);
// Normalize... // Normalize...
$dom = new DOMDocument(); $dom = new DOMDocument();
if(!$dom->loadHTML($raw)) { if (!$dom->loadHTML($raw)) {
common_log(LOG_ERR, "Bad HTML in local HTML attachment $path"); common_log(LOG_ERR, "Bad HTML in local HTML attachment {$path}");
return false; return false;
} }
// Remove <script>s or htmlawed will dump their contents into output! // Remove <script>s or htmlawed will dump their contents into output!
// Note: removing child nodes while iterating seems to mess things up, // Note: removing child nodes while iterating seems to mess things up,
// hence the double loop. // hence the double loop.
$scripts = array(); $scripts = [];
foreach ($dom->getElementsByTagName('script') as $script) { foreach ($dom->getElementsByTagName('script') as $script) {
$scripts[] = $script; $scripts[] = $script;
} }
@ -251,7 +258,7 @@ class AttachmentListItem extends Widget
$body = preg_replace('/^.*<body[^>]*>/is', '', $body); $body = preg_replace('/^.*<body[^>]*>/is', '', $body);
$body = preg_replace('/<\/body[^>]*>.*$/is', '', $body); $body = preg_replace('/<\/body[^>]*>.*$/is', '', $body);
require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php'; require_once INSTALLDIR . '/extlib/HTMLPurifier/HTMLPurifier.auto.php';
$purifier = new HTMLPurifier(); $purifier = new HTMLPurifier();
return $purifier->purify($body); return $purifier->purify($body);
} }
@ -261,7 +268,7 @@ class AttachmentListItem extends Widget
* *
* @return void * @return void
*/ */
function showStart() public function showStart()
{ {
// XXX: RDFa // XXX: RDFa
// TODO: add notice_type class e.g., notice_video, notice_image // TODO: add notice_type class e.g., notice_video, notice_image
@ -275,7 +282,7 @@ class AttachmentListItem extends Widget
* *
* @return void * @return void
*/ */
function showEnd() public function showEnd()
{ {
$this->out->elementEnd('li'); $this->out->elementEnd('li');
} }

View File

@ -19,12 +19,13 @@
* *
* @category Widget * @category Widget
* @package GNUsocial * @package GNUsocial
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc. * @copyright 2009 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
defined('GNUSOCIAL') || die(); namespace Plugin\Media\media;
/** /**
* FIXME * FIXME
@ -33,15 +34,16 @@ defined('GNUSOCIAL') || die();
* *
* @category Widget * @category Widget
* @package GNUsocial * @package GNUsocial
*
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc. * @copyright 2009 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
class AttachmentNoticeSection extends NoticeSection class AttachmentNoticeSection // extends NoticeSection
{ {
public function showContent() public function showContent()
{ {
parent::showContent(); // parent::showContent();
return false; return false;
} }
@ -49,7 +51,7 @@ class AttachmentNoticeSection extends NoticeSection
{ {
$notice = new Notice; $notice = new Notice;
$notice->joinAdd(array('id', 'file_to_post:post_id')); $notice->joinAdd(['id', 'file_to_post:post_id']);
$notice->whereAdd(sprintf('file_to_post.file_id = %d', $this->out->attachment->id)); $notice->whereAdd(sprintf('file_to_post.file_id = %d', $this->out->attachment->id));
$notice->selectAdd('notice.id'); $notice->selectAdd('notice.id');

View File

@ -21,17 +21,19 @@
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Brion Vibber <brion@status.net> * @author Brion Vibber <brion@status.net>
* @copyright 2010 StatusNet, Inc. * @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
*/ */
if (!defined('GNUSOCIAL')) { exit(1); } namespace Plugin\Media\media;
class InlineAttachmentList extends AttachmentList class InlineAttachmentList extends AttachmentList
{ {
function showListStart() public function showListStart()
{ {
$this->out->element('h4', 'attachments-title', _('Attachments')); $this->out->element('h4', 'attachments-title', _('Attachments'));
parent::showListStart(); parent::showListStart();
@ -44,7 +46,7 @@ class InlineAttachmentList extends AttachmentList
* *
* @return ListItem a list item for displaying the attachment * @return ListItem a list item for displaying the attachment
*/ */
function newListItem(File $attachment) public function newListItem(File $attachment)
{ {
return new InlineAttachmentListItem($attachment, $this->out); return new InlineAttachmentListItem($attachment, $this->out);
} }

View File

@ -21,13 +21,15 @@
* *
* @category UI * @category UI
* @package StatusNet * @package StatusNet
*
* @author Brion Vibber <brion@status.net> * @author Brion Vibber <brion@status.net>
* @copyright 2010 StatusNet, Inc. * @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/ *
* @see http://status.net/
*/ */
if (!defined('GNUSOCIAL')) { exit(1); } namespace Plugin\Media\media;
class InlineAttachmentListItem extends AttachmentListItem class InlineAttachmentListItem extends AttachmentListItem
{ {
@ -36,7 +38,7 @@ class InlineAttachmentListItem extends AttachmentListItem
* *
* @return void * @return void
*/ */
function showStart() public function showStart()
{ {
// XXX: RDFa // XXX: RDFa
// TODO: add notice_type class e.g., notice_video, notice_image // TODO: add notice_type class e.g., notice_video, notice_image
@ -55,7 +57,7 @@ class InlineAttachmentListItem extends AttachmentListItem
* *
* @return void * @return void
*/ */
function showEnd() public function showEnd()
{ {
$this->out->elementEnd('li'); $this->out->elementEnd('li');
} }