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\Media\Photo;
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 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
82 $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
83 return $this->return(401, $this->t('Invalid request.'));
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.'));
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];
106 $src = $_FILES['media']['tmp_name'];
110 if (!empty($_FILES['media']['name'])) {
111 if (is_array($_FILES['media']['name'])) {
112 $filename = basename($_FILES['media']['name'][0]);
114 $filename = basename($_FILES['media']['name']);
118 if (!empty($_FILES['media']['size'])) {
119 if (is_array($_FILES['media']['size'])) {
120 $filesize = intval($_FILES['media']['size'][0]);
122 $filesize = intval($_FILES['media']['size']);
126 if (!empty($_FILES['media']['type'])) {
127 if (is_array($_FILES['media']['type'])) {
128 $filetype = $_FILES['media']['type'][0];
130 $filetype = $_FILES['media']['type'];
136 $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
137 return $this->return(401, $this->t('Invalid request.'), true);
140 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
142 $this->logger->info('File upload:', [
144 'filename' => $filename,
145 'filesize' => $filesize,
146 'filetype' => $filetype,
149 $imagedata = @file_get_contents($src);
150 $image = new Image($imagedata, $filetype);
152 if (!$image->isValid()) {
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.'));
158 $image->orient($src);
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]);
168 $width = $image->getWidth();
169 $height = $image->getHeight();
171 $maximagesize = $this->config->get('system', 'maximagesize');
173 if (!empty($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();
185 if ($filesize > $maximagesize) {
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)));
192 $resource_id = Photo::newResource();
196 // If we don't have an album name use the Wall Photos album
197 if (!strlen($album)) {
198 $album = $this->t('Wall Photos');
201 $allow_cid = '<' . $owner['id'] . '>';
203 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
205 $this->logger->warning('Photo::store() failed', ['result' => $result]);
206 return $this->return(401, $this->t('Image upload failed.'));
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);
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)) {
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");
230 * @param int $httpCode
231 * @param string $message
232 * @param bool $systemMessage
234 * @throws InternalServerErrorException
236 private function return(int $httpCode, string $message, bool $systemMessage = false): void
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));
243 if ($systemMessage) {
244 $this->systemMessages->addNotice($message);
247 if ($httpCode >= 400) {
248 $this->response->setStatus($httpCode, $message);
251 $this->response->addContent($message);