]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Photo/Upload.php
Improved asynchronous message procession
[friendica.git] / src / Module / Media / Photo / Upload.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Media\Photo;
23
24 use Friendica\App;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Session\Capability\IHandleUserSessions;
28 use Friendica\Core\System;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Module\Response;
32 use Friendica\Navigation\SystemMessages;
33 use Friendica\Network\HTTPException\InternalServerErrorException;
34 use Friendica\Object\Image;
35 use Friendica\Util\Images;
36 use Friendica\Util\Profiler;
37 use Psr\Log\LoggerInterface;
38
39 /**
40  * Asynchronous photo upload module
41  *
42  * Only used as the target action of the AjaxUpload JavaScript library
43  */
44 class Upload extends \Friendica\BaseModule
45 {
46         /** @var IHandleUserSessions */
47         private $userSession;
48
49         /** @var SystemMessages */
50         private $systemMessages;
51
52         /** @var IManageConfigValues */
53         private $config;
54
55         /** @var bool */
56         private $isJson = false;
57
58         /** @var App\Page */
59         private $page;
60
61         public function __construct(App\Page $page, IManageConfigValues $config, SystemMessages $systemMessages, IHandleUserSessions $userSession, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
62         {
63                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
64
65                 $this->userSession    = $userSession;
66                 $this->systemMessages = $systemMessages;
67                 $this->config         = $config;
68                 $this->page           = $page;
69         }
70
71         protected function post(array $request = [])
72         {
73                 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
74
75                 $album = trim($request['album'] ?? '');
76
77                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
78
79                 if (!$owner) {
80                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
81                         $this->return(401, $this->t('Invalid request.'));
82                 }
83
84                 if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
85                         $this->logger->warning('Empty "userfile" and "media" field');
86                         $this->return(401, $this->t('Invalid request.'));
87                 }
88
89                 $src      = '';
90                 $filename = '';
91                 $filesize = 0;
92                 $filetype = '';
93
94                 if (!empty($_FILES['userfile'])) {
95                         $src      = $_FILES['userfile']['tmp_name'];
96                         $filename = basename($_FILES['userfile']['name']);
97                         $filesize = intval($_FILES['userfile']['size']);
98                         $filetype = $_FILES['userfile']['type'];
99                 } elseif (!empty($_FILES['media'])) {
100                         if (!empty($_FILES['media']['tmp_name'])) {
101                                 if (is_array($_FILES['media']['tmp_name'])) {
102                                         $src = $_FILES['media']['tmp_name'][0];
103                                 } else {
104                                         $src = $_FILES['media']['tmp_name'];
105                                 }
106                         }
107
108                         if (!empty($_FILES['media']['name'])) {
109                                 if (is_array($_FILES['media']['name'])) {
110                                         $filename = basename($_FILES['media']['name'][0]);
111                                 } else {
112                                         $filename = basename($_FILES['media']['name']);
113                                 }
114                         }
115
116                         if (!empty($_FILES['media']['size'])) {
117                                 if (is_array($_FILES['media']['size'])) {
118                                         $filesize = intval($_FILES['media']['size'][0]);
119                                 } else {
120                                         $filesize = intval($_FILES['media']['size']);
121                                 }
122                         }
123
124                         if (!empty($_FILES['media']['type'])) {
125                                 if (is_array($_FILES['media']['type'])) {
126                                         $filetype = $_FILES['media']['type'][0];
127                                 } else {
128                                         $filetype = $_FILES['media']['type'];
129                                 }
130                         }
131                 }
132
133                 if ($src == '') {
134                         $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
135                         $this->return(401, $this->t('Invalid request.'), true);
136                 }
137
138                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
139
140                 $this->logger->info('File upload:', [
141                         'src'      => $src,
142                         'filename' => $filename,
143                         'filesize' => $filesize,
144                         'filetype' => $filetype,
145                 ]);
146
147                 $imagedata = @file_get_contents($src);
148                 $image     = new Image($imagedata, $filetype);
149
150                 if (!$image->isValid()) {
151                         @unlink($src);
152                         $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]);
153                         $this->return(401, $this->t('Unable to process image.'));
154                 }
155
156                 $image->orient($src);
157                 @unlink($src);
158
159                 $max_length = $this->config->get('system', 'max_image_length');
160                 if ($max_length > 0) {
161                         $image->scaleDown($max_length);
162                         $filesize = strlen($image->asString());
163                         $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]);
164                 }
165
166                 $resource_id = Photo::newResource();
167
168                 // If we don't have an album name use the Wall Photos album
169                 if (!strlen($album)) {
170                         $album = $this->t('Wall Photos');
171                 }
172
173                 $allow_cid = '<' . $owner['id'] . '>';
174
175                 $preview = Photo::storeWithPreview($image, $owner['uid'], $resource_id, $filename, $filesize, $album, '', $allow_cid, '', '', '');
176                 if ($preview < 0) {
177                         $this->logger->warning('Photo::store() failed');
178                         $this->return(401, $this->t('Image upload failed.'));
179                 }
180
181                 $this->logger->info('upload done');
182                 $this->return(200, "\n\n" . Images::getBBCodeByResource($resource_id, $owner['nickname'], $preview, $image->getExt()) . "\n\n");
183         }
184
185         /**
186          * @param int    $httpCode
187          * @param string $message
188          * @param bool   $systemMessage
189          * @return void
190          * @throws InternalServerErrorException
191          */
192         private function return(int $httpCode, string $message, bool $systemMessage = false): void
193         {
194                 if ($this->isJson) {
195                         $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true];
196                         $this->response->setType(Response::TYPE_JSON, 'application/json');
197                         $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
198                 } else {
199                         if ($systemMessage) {
200                                 $this->systemMessages->addNotice($message);
201                         }
202
203                         if ($httpCode >= 400) {
204                                 $this->response->setStatus($httpCode, $message);
205                         }
206
207                         $this->response->addContent($message);
208                 }
209
210                 System::echoResponse($this->response->generate());
211                 System::exit();
212         }
213 }