]> git.mxchange.org Git - friendica.git/commitdiff
Create Profile\Photos\Upload class
authorHypolite Petovan <hypolite@mrpetovan.com>
Sun, 30 Oct 2022 04:17:54 +0000 (00:17 -0400)
committerHypolite Petovan <hypolite@mrpetovan.com>
Sun, 30 Oct 2022 18:20:01 +0000 (14:20 -0400)
src/Module/Profile/Photos/Upload.php [new file with mode: 0644]
static/routes.config.php
view/js/filebrowser.js
view/templates/msg-header.tpl
view/theme/frio/js/filebrowser.js
view/theme/smoothly/templates/jot-header.tpl

diff --git a/src/Module/Profile/Photos/Upload.php b/src/Module/Profile/Photos/Upload.php
new file mode 100644 (file)
index 0000000..e99d7e1
--- /dev/null
@@ -0,0 +1,279 @@
+<?php
+/**
+ * @copyright Copyright (C) 2010-2022, the Friendica project
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program 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.
+ *
+ * This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+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);
+               }
+       }
+}
index 9afc52e9f5e002d72f61ec5ba488485b76fb8884..b27a70c694d5d9f298135f7e410887fd69752f0c 100644 (file)
@@ -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 = [
index 24b4d904fde383a5c2f541ada8bbca514fdfac33..33d06e708ab748653f68102a3e8f52ab17a4a024 100644 (file)
@@ -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'); },
index d3728780029cea104f058a6c52d11df05f246db2..7b8baf0750bf5ed6a9a47fdebe02eb726f02202d 100644 (file)
@@ -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) {
index 359c6636eb243fcda4cc9375fc26d4624c34d0f2..3cdd03e1afa1110a4bf61894085ab700b4b6a156 100644 (file)
@@ -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",
index 08028be8204fbf9f3124fe783a841bc9b59e9382..71b8771796f039f6cdbcc831b3730e1901e6b036 100644 (file)
@@ -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) {