[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
* @package GNUsocial
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @copyright 2008-2009 StatusNet, Inc. * @author Hugo Sales <hugo@hsal.es>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
*
* @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
{ {

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> * @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2016 Free Software Foundation, Inc http://www.fsf.org * @license https://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or late *
* @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)
{ {
$imgPath = null;
$media = common_get_mime_media($file->mimetype); $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') {
@ -186,14 +200,15 @@ class ImageFile extends MediaFile
* @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)
{ {
@ -289,11 +307,12 @@ class ImageFile extends MediaFile
* @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
* *
* @return string full local filesystem filename
* @return string full local filesystem filename
* @throws UnsupportedMediaException * @throws UnsupportedMediaException
* @throws UseFileAsThumbnailException * @throws UseFileAsThumbnailException
* *
* @return string full local filesystem filename
* @return string full local filesystem filename
*
*/ */
public function resizeTo($outpath, array $box = []) public function resizeTo($outpath, array $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,

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
@ -180,9 +185,10 @@ class MediaFile
* @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()
{ {
@ -299,11 +306,12 @@ class MediaFile
* *
* @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
{ {
@ -387,8 +395,8 @@ class MediaFile
* 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)
{ {
@ -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)
{ {
@ -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());
@ -715,13 +730,14 @@ class MediaFile
* @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)
{ {

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,9 +75,15 @@ 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;
} }
@ -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,7 +83,7 @@ class AttachmentListItem extends Widget
* *
* @return void * @return void
*/ */
function show() public function show()
{ {
$this->showStart(); $this->showStart();
try { try {
@ -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)
@ -230,14 +237,14 @@ class AttachmentListItem extends Widget
// 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;
} }
@ -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');
} }