]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Photo/Upload.php
Option to automatically add links as attachment via API
[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\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                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
80
81                 if (!$owner) {
82                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
83                         return $this->return(401, $this->t('Invalid request.'));
84                 }
85
86                 if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
87                         $this->logger->warning('Empty "userfile" and "media" field');
88                         return $this->return(401, $this->t('Invalid request.'));
89                 }
90
91                 $src      = '';
92                 $filename = '';
93                 $filesize = 0;
94                 $filetype = '';
95
96                 if (!empty($_FILES['userfile'])) {
97                         $src      = $_FILES['userfile']['tmp_name'];
98                         $filename = basename($_FILES['userfile']['name']);
99                         $filesize = intval($_FILES['userfile']['size']);
100                         $filetype = $_FILES['userfile']['type'];
101                 } elseif (!empty($_FILES['media'])) {
102                         if (!empty($_FILES['media']['tmp_name'])) {
103                                 if (is_array($_FILES['media']['tmp_name'])) {
104                                         $src = $_FILES['media']['tmp_name'][0];
105                                 } else {
106                                         $src = $_FILES['media']['tmp_name'];
107                                 }
108                         }
109
110                         if (!empty($_FILES['media']['name'])) {
111                                 if (is_array($_FILES['media']['name'])) {
112                                         $filename = basename($_FILES['media']['name'][0]);
113                                 } else {
114                                         $filename = basename($_FILES['media']['name']);
115                                 }
116                         }
117
118                         if (!empty($_FILES['media']['size'])) {
119                                 if (is_array($_FILES['media']['size'])) {
120                                         $filesize = intval($_FILES['media']['size'][0]);
121                                 } else {
122                                         $filesize = intval($_FILES['media']['size']);
123                                 }
124                         }
125
126                         if (!empty($_FILES['media']['type'])) {
127                                 if (is_array($_FILES['media']['type'])) {
128                                         $filetype = $_FILES['media']['type'][0];
129                                 } else {
130                                         $filetype = $_FILES['media']['type'];
131                                 }
132                         }
133                 }
134
135                 if ($src == '') {
136                         $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
137                         return $this->return(401, $this->t('Invalid request.'), true);
138                 }
139
140                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
141
142                 $this->logger->info('File upload:', [
143                         'src'      => $src,
144                         'filename' => $filename,
145                         'filesize' => $filesize,
146                         'filetype' => $filetype,
147                 ]);
148
149                 $imagedata = @file_get_contents($src);
150                 $image     = new Image($imagedata, $filetype);
151
152                 if (!$image->isValid()) {
153                         @unlink($src);
154                         $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]);
155                         return $this->return(401, $this->t('Unable to process image.'));
156                 }
157
158                 $image->orient($src);
159                 @unlink($src);
160
161                 $max_length = $this->config->get('system', 'max_image_length');
162                 if ($max_length > 0) {
163                         $image->scaleDown($max_length);
164                         $filesize = strlen($image->asString());
165                         $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]);
166                 }
167
168                 $width  = $image->getWidth();
169                 $height = $image->getHeight();
170
171                 $maximagesize = Strings::getBytesFromShorthand($this->config->get('system', 'maximagesize'));
172
173                 if ($maximagesize && $filesize > $maximagesize) {
174                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
175                         foreach ([5120, 2560, 1280, 640] as $pixels) {
176                                 if ($filesize > $maximagesize && max($width, $height) > $pixels) {
177                                         $this->logger->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
178                                         $image->scaleDown($pixels);
179                                         $filesize = strlen($image->asString());
180                                         $width    = $image->getWidth();
181                                         $height   = $image->getHeight();
182                                 }
183                         }
184
185                         if ($filesize > $maximagesize) {
186                                 @unlink($src);
187                                 $this->logger->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
188                                 return $this->return(401, $this->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)));
189                         }
190                 }
191
192                 $resource_id = Photo::newResource();
193
194                 $smallest = 0;
195
196                 // If we don't have an album name use the Wall Photos album
197                 if (!strlen($album)) {
198                         $album = $this->t('Wall Photos');
199                 }
200
201                 $allow_cid = '<' . $owner['id'] . '>';
202
203                 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
204                 if (!$result) {
205                         $this->logger->warning('Photo::store() failed', ['result' => $result]);
206                         return $this->return(401, $this->t('Image upload failed.'));
207                 }
208
209                 if ($width > 640 || $height > 640) {
210                         $image->scaleDown(640);
211                         $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid);
212                         if ($result) {
213                                 $smallest = 1;
214                         }
215                 }
216
217                 if ($width > 320 || $height > 320) {
218                         $image->scaleDown(320);
219                         $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid);
220                         if ($result && ($smallest == 0)) {
221                                 $smallest = 2;
222                         }
223                 }
224
225                 $this->logger->info('upload done');
226                 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");
227         }
228
229         /**
230          * @param int    $httpCode
231          * @param string $message
232          * @param bool   $systemMessage
233          * @return void
234          * @throws InternalServerErrorException
235          */
236         private function return(int $httpCode, string $message, bool $systemMessage = false): void
237         {
238                 if ($this->isJson) {
239                         $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true];
240                         $this->response->setType(Response::TYPE_JSON, 'application/json');
241                         $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
242                 } else {
243                         if ($systemMessage) {
244                                 $this->systemMessages->addNotice($message);
245                         }
246
247                         if ($httpCode >= 400) {
248                                 $this->response->setStatus($httpCode, $message);
249                         }
250
251                         $this->response->addContent($message);
252                 }
253         }
254 }