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