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