3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module\Profile\Photos;
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;
42 * Asynchronous photo upload module
44 * Only used as the target action of the AjaxUpload Javascript library
46 class Upload extends \Friendica\BaseModule
51 /** @var IHandleUserSessions */
54 /** @var SystemMessages */
55 private $systemMessages;
57 /** @var IManageConfigValues */
61 private $isJson = false;
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 = [])
65 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
67 $this->database = $database;
68 $this->userSession = $userSession;
69 $this->systemMessages = $systemMessages;
70 $this->config = $config;
73 protected function post(array $request = [])
75 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
77 $album = trim($request['album'] ?? '');
79 if (empty($_FILES['media'])) {
80 $user = $this->database->selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['nickname' => $this->parameters['nickname'], 'blocked' => false]);
82 $user = $this->database->selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['uid' => BaseApi::getCurrentUserID() ?: null, 'blocked' => false]);
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.'));
91 * Setup permissions structures
96 $page_owner_uid = $user['uid'];
98 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $page_owner_uid) {
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;
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);
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.'));
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];
131 $src = $_FILES['media']['tmp_name'];
135 if (!empty($_FILES['media']['name'])) {
136 if (is_array($_FILES['media']['name'])) {
137 $filename = basename($_FILES['media']['name'][0]);
139 $filename = basename($_FILES['media']['name']);
143 if (!empty($_FILES['media']['size'])) {
144 if (is_array($_FILES['media']['size'])) {
145 $filesize = intval($_FILES['media']['size'][0]);
147 $filesize = intval($_FILES['media']['size']);
151 if (!empty($_FILES['media']['type'])) {
152 if (is_array($_FILES['media']['type'])) {
153 $filetype = $_FILES['media']['type'][0];
155 $filetype = $_FILES['media']['type'];
161 $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
162 return $this->return(401, $this->t('Invalid request.'), true);
165 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
167 $this->logger->info('File upload:', [
169 'filename' => $filename,
170 'filesize' => $filesize,
171 'filetype' => $filetype,
174 $imagedata = @file_get_contents($src);
175 $image = new Image($imagedata, $filetype);
177 if (!$image->isValid()) {
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.'));
183 $image->orient($src);
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]);
193 $width = $image->getWidth();
194 $height = $image->getHeight();
196 $maximagesize = $this->config->get('system', 'maximagesize');
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();
210 if ($filesize > $maximagesize) {
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)));
217 $resource_id = Photo::newResource();
221 // If we don't have an album name use the Wall Photos album
222 if (!strlen($album)) {
223 $album = $this->t('Wall Photos');
226 $allow_cid = '<' . $user['id'] . '>';
228 $result = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
230 $this->logger->warning('Photo::store() failed', ['result' => $result]);
231 return $this->return(401, $this->t('Image upload failed.'));
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);
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)) {
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");
255 * @param int $httpCode
256 * @param string $message
257 * @param bool $systemMessage
259 * @throws InternalServerErrorException
261 private function return(int $httpCode, string $message, bool $systemMessage = false): void
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));
268 if ($systemMessage) {
269 $this->systemMessages->addNotice($message);
272 if ($httpCode >= 400) {
273 $this->response->setStatus($httpCode, $message);
276 $this->response->addContent($message);