From 39765e601859596a087383bb66898edd9f108ac4 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Sun, 30 Oct 2022 00:17:54 -0400 Subject: [PATCH] Create Profile\Photos\Upload class --- src/Module/Profile/Photos/Upload.php | 279 +++++++++++++++++++ static/routes.config.php | 17 +- view/js/filebrowser.js | 2 +- view/templates/msg-header.tpl | 2 +- view/theme/frio/js/filebrowser.js | 4 +- view/theme/smoothly/templates/jot-header.tpl | 7 +- 6 files changed, 296 insertions(+), 15 deletions(-) create mode 100644 src/Module/Profile/Photos/Upload.php diff --git a/src/Module/Profile/Photos/Upload.php b/src/Module/Profile/Photos/Upload.php new file mode 100644 index 0000000000..e99d7e1083 --- /dev/null +++ b/src/Module/Profile/Photos/Upload.php @@ -0,0 +1,279 @@ +. + * + */ + +namespace Friendica\Module\Profile\Photos; + +use Friendica\App; +use Friendica\Core\Config\Capability\IManageConfigValues; +use Friendica\Core\L10n; +use Friendica\Core\Session\Capability\IHandleUserSessions; +use Friendica\Database\Database; +use Friendica\Model\Photo; +use Friendica\Model\User; +use Friendica\Module\BaseApi; +use Friendica\Module\Response; +use Friendica\Navigation\SystemMessages; +use Friendica\Network\HTTPException\InternalServerErrorException; +use Friendica\Object\Image; +use Friendica\Util\Images; +use Friendica\Util\Profiler; +use Friendica\Util\Strings; +use Psr\Log\LoggerInterface; + +/** + * Asynchronous photo upload module + * + * Only used as the target action of the AjaxUpload Javascript library + */ +class Upload extends \Friendica\BaseModule +{ + /** @var Database */ + private $database; + + /** @var IHandleUserSessions */ + private $userSession; + + /** @var SystemMessages */ + private $systemMessages; + + /** @var IManageConfigValues */ + private $config; + + /** @var bool */ + private $isJson = false; + + public function __construct(IManageConfigValues $config, SystemMessages $systemMessages, IHandleUserSessions $userSession, Database $database, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = []) + { + parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters); + + $this->database = $database; + $this->userSession = $userSession; + $this->systemMessages = $systemMessages; + $this->config = $config; + } + + protected function post(array $request = []) + { + $this->isJson = !empty($request['response']) && $request['response'] == 'json'; + + $album = trim($request['album'] ?? ''); + + if (empty($_FILES['media'])) { + $user = $this->database->selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['nickname' => $this->parameters['nickname'], 'blocked' => false]); + } else { + $user = $this->database->selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['uid' => BaseApi::getCurrentUserID() ?: null, 'blocked' => false]); + } + + if (!$this->database->isResult($user)) { + $this->logger->warning('User is not valid', ['nickname' => $this->parameters['nickname'], 'user' => $user]); + return $this->return(404, $this->t('User not found.')); + } + + /* + * Setup permissions structures + */ + $can_post = false; + $visitor = 0; + $contact_id = 0; + $page_owner_uid = $user['uid']; + + if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $page_owner_uid) { + $can_post = true; + } elseif ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY && !$this->userSession->getRemoteContactID($page_owner_uid)) { + $contact_id = $this->userSession->getRemoteContactID($page_owner_uid); + $can_post = $this->database->exists('contact', ['blocked' => false, 'pending' => false, 'id' => $contact_id, 'uid' => $page_owner_uid]); + $visitor = $contact_id; + } + + if (!$can_post) { + $this->logger->warning('No permission to upload files', ['contact_id' => $contact_id, 'page_owner_uid' => $page_owner_uid]); + return $this->return(403, $this->t('Permission denied.'), true); + } + + if (empty($_FILES['userfile']) && empty($_FILES['media'])) { + $this->logger->warning('Empty "userfile" and "media" field'); + return $this->return(401, $this->t('Invalid request.')); + } + + $src = ''; + $filename = ''; + $filesize = 0; + $filetype = ''; + + if (!empty($_FILES['userfile'])) { + $src = $_FILES['userfile']['tmp_name']; + $filename = basename($_FILES['userfile']['name']); + $filesize = intval($_FILES['userfile']['size']); + $filetype = $_FILES['userfile']['type']; + } elseif (!empty($_FILES['media'])) { + if (!empty($_FILES['media']['tmp_name'])) { + if (is_array($_FILES['media']['tmp_name'])) { + $src = $_FILES['media']['tmp_name'][0]; + } else { + $src = $_FILES['media']['tmp_name']; + } + } + + if (!empty($_FILES['media']['name'])) { + if (is_array($_FILES['media']['name'])) { + $filename = basename($_FILES['media']['name'][0]); + } else { + $filename = basename($_FILES['media']['name']); + } + } + + if (!empty($_FILES['media']['size'])) { + if (is_array($_FILES['media']['size'])) { + $filesize = intval($_FILES['media']['size'][0]); + } else { + $filesize = intval($_FILES['media']['size']); + } + } + + if (!empty($_FILES['media']['type'])) { + if (is_array($_FILES['media']['type'])) { + $filetype = $_FILES['media']['type'][0]; + } else { + $filetype = $_FILES['media']['type']; + } + } + } + + if ($src == '') { + $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]); + return $this->return(401, $this->t('Invalid request.'), true); + } + + $filetype = Images::getMimeTypeBySource($src, $filename, $filetype); + + $this->logger->info('File upload:', [ + 'src' => $src, + 'filename' => $filename, + 'filesize' => $filesize, + 'filetype' => $filetype, + ]); + + $imagedata = @file_get_contents($src); + $image = new Image($imagedata, $filetype); + + if (!$image->isValid()) { + @unlink($src); + $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]); + return $this->return(401, $this->t('Unable to process image.')); + } + + $image->orient($src); + @unlink($src); + + $max_length = $this->config->get('system', 'max_image_length'); + if ($max_length > 0) { + $image->scaleDown($max_length); + $filesize = strlen($image->asString()); + $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]); + } + + $width = $image->getWidth(); + $height = $image->getHeight(); + + $maximagesize = $this->config->get('system', 'maximagesize'); + + if (!empty($maximagesize) && $filesize > $maximagesize) { + // Scale down to multiples of 640 until the maximum size isn't exceeded anymore + foreach ([5120, 2560, 1280, 640] as $pixels) { + if ($filesize > $maximagesize && max($width, $height) > $pixels) { + $this->logger->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]); + $image->scaleDown($pixels); + $filesize = strlen($image->asString()); + $width = $image->getWidth(); + $height = $image->getHeight(); + } + } + + if ($filesize > $maximagesize) { + @unlink($src); + $this->logger->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]); + return $this->return(401, $this->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize))); + } + } + + $resource_id = Photo::newResource(); + + $smallest = 0; + + // If we don't have an album name use the Wall Photos album + if (!strlen($album)) { + $album = $this->t('Wall Photos'); + } + + $allow_cid = '<' . $user['id'] . '>'; + + $result = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid); + if (!$result) { + $this->logger->warning('Photo::store() failed', ['result' => $result]); + return $this->return(401, $this->t('Image upload failed.')); + } + + if ($width > 640 || $height > 640) { + $image->scaleDown(640); + $result = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid); + if ($result) { + $smallest = 1; + } + } + + if ($width > 320 || $height > 320) { + $image->scaleDown(320); + $result = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid); + if ($result && ($smallest == 0)) { + $smallest = 2; + } + } + + $this->logger->info('upload done'); + return $this->return(200, "\n\n" . '[url=' . $this->baseUrl . '/photos/' . $user['nickname'] . '/image/' . $resource_id . '][img]' . $this->baseUrl . "/photo/$resource_id-$smallest." . $image->getExt() . "[/img][/url]\n\n"); + } + + /** + * @param int $httpCode + * @param string $message + * @param bool $systemMessage + * @return void + * @throws InternalServerErrorException + */ + private function return(int $httpCode, string $message, bool $systemMessage = false): void + { + if ($this->isJson) { + $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true]; + $this->response->setType(Response::TYPE_JSON, 'application/json'); + $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); + } else { + if ($systemMessage) { + $this->systemMessages->addNotice($message); + } + + if ($httpCode >= 400) { + $this->response->setStatus($httpCode, $message); + } + + $this->response->addContent($message); + } + } +} diff --git a/static/routes.config.php b/static/routes.config.php index 9afc52e9f5..b27a70c694 100644 --- a/static/routes.config.php +++ b/static/routes.config.php @@ -31,14 +31,15 @@ use Friendica\App\Router as R; use Friendica\Module; $profileRoutes = [ - '' => [Module\Profile\Index::class, [R::GET]], - '/profile' => [Module\Profile\Profile::class, [R::GET]], - '/schedule' => [Module\Profile\Schedule::class, [R::GET, R::POST]], - '/contacts/common' => [Module\Profile\Common::class, [R::GET]], - '/contacts[/{type}]' => [Module\Profile\Contacts::class, [R::GET]], - '/status[/{category}[/{date1}[/{date2}]]]' => [Module\Profile\Status::class, [R::GET]], - '/media' => [Module\Profile\Media::class, [R::GET]], - '/unkmail' => [Module\Profile\UnkMail::class, [R::GET, R::POST]], + '' => [Module\Profile\Index::class, [R::GET]], + '/profile' => [Module\Profile\Profile::class, [R::GET]], + '/schedule' => [Module\Profile\Schedule::class, [R::GET, R::POST]], + '/contacts/common' => [Module\Profile\Common::class, [R::GET]], + '/contacts[/{type}]' => [Module\Profile\Contacts::class, [R::GET]], + '/status[/{category}[/{date1}[/{date2}]]]' => [Module\Profile\Status::class, [R::GET]], + '/media' => [Module\Profile\Media::class, [R::GET]], + '/unkmail' => [Module\Profile\UnkMail::class, [R::GET, R::POST]], + '/photos/upload' => [Module\Profile\Photos\Upload::class, [ R::POST]], ]; $apiRoutes = [ diff --git a/view/js/filebrowser.js b/view/js/filebrowser.js index 24b4d904fd..33d06e708a 100644 --- a/view/js/filebrowser.js +++ b/view/js/filebrowser.js @@ -103,7 +103,7 @@ var FileBrowser = { if ($("#upload-image").length) var image_uploader = new window.AjaxUpload( 'upload-image', - { action: 'wall_upload/'+FileBrowser.nickname+'?response=json', + { action: 'profile/' + FileBrowser.nickname + '/photos/upload?response=json', name: 'userfile', responseType: 'json', onSubmit: function(file,ext) { $('#profile-rotator').show(); $(".error").addClass('hidden'); }, diff --git a/view/templates/msg-header.tpl b/view/templates/msg-header.tpl index d372878002..7b8baf0750 100644 --- a/view/templates/msg-header.tpl +++ b/view/templates/msg-header.tpl @@ -6,7 +6,7 @@ $(document).ready(function() { var uploader = new window.AjaxUpload( 'prvmail-upload', - { action: 'wall_upload/{{$nickname}}', + { action: 'profile/{{$nickname}}/photos/upload', name: 'userfile', onSubmit: function(file,ext) { $('#profile-rotator').show(); }, onComplete: function(file,response) { diff --git a/view/theme/frio/js/filebrowser.js b/view/theme/frio/js/filebrowser.js index 359c6636eb..3cdd03e1af 100644 --- a/view/theme/frio/js/filebrowser.js +++ b/view/theme/frio/js/filebrowser.js @@ -167,9 +167,9 @@ var FileBrowser = { //AjaxUpload for images var image_uploader = new window.AjaxUpload("upload-image", { action: - "wall_upload/" + + "profile/" + FileBrowser.nickname + - "?response=json&album=" + + "/photos/upload?response=json&album=" + encodeURIComponent(FileBrowser.folder), name: "userfile", responseType: "json", diff --git a/view/theme/smoothly/templates/jot-header.tpl b/view/theme/smoothly/templates/jot-header.tpl index 08028be820..71b8771796 100644 --- a/view/theme/smoothly/templates/jot-header.tpl +++ b/view/theme/smoothly/templates/jot-header.tpl @@ -57,12 +57,13 @@ function enableOnUser(){ $(document).ready(function() { /* enable editor on focus and click */ - $("#profile-jot-text").focus(enableOnUser); - $("#profile-jot-text").click(enableOnUser); + $("#profile-jot-text") + .focus(enableOnUser) + .click(enableOnUser); var uploader = new window.AjaxUpload( 'wall-image-upload', - { action: 'wall_upload/{{$nickname}}', + { action: 'profile/{{$nickname}}/photos/upload', name: 'userfile', onSubmit: function(file,ext) { $('#profile-rotator').show(); }, onComplete: function(file,response) {