]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Photo/Upload.php
Merge branch '2023.03-rc' into stable
[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 Friendica\Util\Strings;
38 use Psr\Log\LoggerInterface;
39
40 /**
41  * Asynchronous photo upload module
42  *
43  * Only used as the target action of the AjaxUpload JavaScript library
44  */
45 class Upload extends \Friendica\BaseModule
46 {
47         /** @var IHandleUserSessions */
48         private $userSession;
49
50         /** @var SystemMessages */
51         private $systemMessages;
52
53         /** @var IManageConfigValues */
54         private $config;
55
56         /** @var bool */
57         private $isJson = false;
58
59         /** @var App\Page */
60         private $page;
61
62         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 = [])
63         {
64                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
65
66                 $this->userSession    = $userSession;
67                 $this->systemMessages = $systemMessages;
68                 $this->config         = $config;
69                 $this->page           = $page;
70         }
71
72         protected function post(array $request = [])
73         {
74                 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
75
76                 $album = trim($request['album'] ?? '');
77
78                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
79
80                 if (!$owner) {
81                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
82                         $this->return(401, $this->t('Invalid request.'));
83                 }
84
85                 if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
86                         $this->logger->warning('Empty "userfile" and "media" field');
87                         $this->return(401, $this->t('Invalid request.'));
88                 }
89
90                 $src      = '';
91                 $filename = '';
92                 $filesize = 0;
93                 $filetype = '';
94
95                 if (!empty($_FILES['userfile'])) {
96                         $src      = $_FILES['userfile']['tmp_name'];
97                         $filename = basename($_FILES['userfile']['name']);
98                         $filesize = intval($_FILES['userfile']['size']);
99                         $filetype = $_FILES['userfile']['type'];
100                 } elseif (!empty($_FILES['media'])) {
101                         if (!empty($_FILES['media']['tmp_name'])) {
102                                 if (is_array($_FILES['media']['tmp_name'])) {
103                                         $src = $_FILES['media']['tmp_name'][0];
104                                 } else {
105                                         $src = $_FILES['media']['tmp_name'];
106                                 }
107                         }
108
109                         if (!empty($_FILES['media']['name'])) {
110                                 if (is_array($_FILES['media']['name'])) {
111                                         $filename = basename($_FILES['media']['name'][0]);
112                                 } else {
113                                         $filename = basename($_FILES['media']['name']);
114                                 }
115                         }
116
117                         if (!empty($_FILES['media']['size'])) {
118                                 if (is_array($_FILES['media']['size'])) {
119                                         $filesize = intval($_FILES['media']['size'][0]);
120                                 } else {
121                                         $filesize = intval($_FILES['media']['size']);
122                                 }
123                         }
124
125                         if (!empty($_FILES['media']['type'])) {
126                                 if (is_array($_FILES['media']['type'])) {
127                                         $filetype = $_FILES['media']['type'][0];
128                                 } else {
129                                         $filetype = $_FILES['media']['type'];
130                                 }
131                         }
132                 }
133
134                 if ($src == '') {
135                         $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
136                         $this->return(401, $this->t('Invalid request.'), true);
137                 }
138
139                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
140
141                 $this->logger->info('File upload:', [
142                         'src'      => $src,
143                         'filename' => $filename,
144                         'filesize' => $filesize,
145                         'filetype' => $filetype,
146                 ]);
147
148                 $imagedata = @file_get_contents($src);
149                 $image     = new Image($imagedata, $filetype);
150
151                 if (!$image->isValid()) {
152                         @unlink($src);
153                         $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]);
154                         $this->return(401, $this->t('Unable to process image.'));
155                 }
156
157                 $image->orient($src);
158                 @unlink($src);
159
160                 $max_length = $this->config->get('system', 'max_image_length');
161                 if ($max_length > 0) {
162                         $image->scaleDown($max_length);
163                         $filesize = strlen($image->asString());
164                         $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]);
165                 }
166
167                 $width  = $image->getWidth();
168                 $height = $image->getHeight();
169
170                 $maximagesize = Strings::getBytesFromShorthand($this->config->get('system', 'maximagesize'));
171
172                 if ($maximagesize && $filesize > $maximagesize) {
173                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
174                         foreach ([5120, 2560, 1280, 640] as $pixels) {
175                                 if ($filesize > $maximagesize && max($width, $height) > $pixels) {
176                                         $this->logger->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
177                                         $image->scaleDown($pixels);
178                                         $filesize = strlen($image->asString());
179                                         $width    = $image->getWidth();
180                                         $height   = $image->getHeight();
181                                 }
182                         }
183
184                         if ($filesize > $maximagesize) {
185                                 @unlink($src);
186                                 $this->logger->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
187                                 $this->return(401, $this->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)));
188                         }
189                 }
190
191                 $resource_id = Photo::newResource();
192
193                 $smallest = 0;
194
195                 // If we don't have an album name use the Wall Photos album
196                 if (!strlen($album)) {
197                         $album = $this->t('Wall Photos');
198                 }
199
200                 $allow_cid = '<' . $owner['id'] . '>';
201
202                 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
203                 if (!$result) {
204                         $this->logger->warning('Photo::store() failed', ['result' => $result]);
205                         $this->return(401, $this->t('Image upload failed.'));
206                 }
207
208                 if ($width > 640 || $height > 640) {
209                         $image->scaleDown(640);
210                         $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid);
211                         if ($result) {
212                                 $smallest = 1;
213                         }
214                 }
215
216                 if ($width > 320 || $height > 320) {
217                         $image->scaleDown(320);
218                         $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid);
219                         if ($result && ($smallest == 0)) {
220                                 $smallest = 2;
221                         }
222                 }
223
224                 $this->logger->info('upload done');
225                 $this->return(200, "\n\n" . '[url=' . $this->baseUrl . '/photos/' . $owner['nickname'] . '/image/' . $resource_id . '][img]' . $this->baseUrl . "/photo/$resource_id-$smallest." . $image->getExt() . "[/img][/url]\n\n");
226         }
227
228         /**
229          * @param int    $httpCode
230          * @param string $message
231          * @param bool   $systemMessage
232          * @return void
233          * @throws InternalServerErrorException
234          */
235         private function return(int $httpCode, string $message, bool $systemMessage = false): void
236         {
237                 if ($this->isJson) {
238                         $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true];
239                         $this->response->setType(Response::TYPE_JSON, 'application/json');
240                         $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
241                 } else {
242                         if ($systemMessage) {
243                                 $this->systemMessages->addNotice($message);
244                         }
245
246                         if ($httpCode >= 400) {
247                                 $this->response->setStatus($httpCode, $message);
248                         }
249
250                         $this->response->addContent($message);
251                 }
252
253                 $this->page->exit($this->response->generate());
254                 System::exit();
255         }
256 }