3 * @copyright Copyright (C) 2010-2023, 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\Core\System;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Module\Response;
32 use Friendica\Navigation\SystemMessages;
33 use Friendica\Network\HTTPException\InternalServerErrorException;
34 use Friendica\Object\Image;
35 use Friendica\Util\Images;
36 use Friendica\Util\Profiler;
37 use Friendica\Util\Strings;
38 use Psr\Log\LoggerInterface;
41 * Asynchronous photo upload module
43 * Only used as the target action of the AjaxUpload Javascript library
45 class Upload extends \Friendica\BaseModule
47 /** @var IHandleUserSessions */
50 /** @var SystemMessages */
51 private $systemMessages;
53 /** @var IManageConfigValues */
57 private $isJson = false;
62 public function __construct(App\Page $page, IManageConfigValues $config, SystemMessages $systemMessages, IHandleUserSessions $userSession, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
64 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
66 $this->userSession = $userSession;
67 $this->systemMessages = $systemMessages;
68 $this->config = $config;
72 protected function post(array $request = [])
74 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
76 $album = trim($request['album'] ?? '');
78 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
81 $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
82 $this->return(401, $this->t('Invalid request.'));
85 if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
86 $this->logger->warning('Empty "userfile" and "media" field');
87 $this->return(401, $this->t('Invalid request.'));
95 if (!empty($_FILES['userfile'])) {
96 $src = $_FILES['userfile']['tmp_name'];
97 $filename = basename($_FILES['userfile']['name']);
98 $filesize = intval($_FILES['userfile']['size']);
99 $filetype = $_FILES['userfile']['type'];
100 } elseif (!empty($_FILES['media'])) {
101 if (!empty($_FILES['media']['tmp_name'])) {
102 if (is_array($_FILES['media']['tmp_name'])) {
103 $src = $_FILES['media']['tmp_name'][0];
105 $src = $_FILES['media']['tmp_name'];
109 if (!empty($_FILES['media']['name'])) {
110 if (is_array($_FILES['media']['name'])) {
111 $filename = basename($_FILES['media']['name'][0]);
113 $filename = basename($_FILES['media']['name']);
117 if (!empty($_FILES['media']['size'])) {
118 if (is_array($_FILES['media']['size'])) {
119 $filesize = intval($_FILES['media']['size'][0]);
121 $filesize = intval($_FILES['media']['size']);
125 if (!empty($_FILES['media']['type'])) {
126 if (is_array($_FILES['media']['type'])) {
127 $filetype = $_FILES['media']['type'][0];
129 $filetype = $_FILES['media']['type'];
135 $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
136 $this->return(401, $this->t('Invalid request.'), true);
139 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
141 $this->logger->info('File upload:', [
143 'filename' => $filename,
144 'filesize' => $filesize,
145 'filetype' => $filetype,
148 $imagedata = @file_get_contents($src);
149 $image = new Image($imagedata, $filetype);
151 if (!$image->isValid()) {
153 $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]);
154 $this->return(401, $this->t('Unable to process image.'));
157 $image->orient($src);
160 $max_length = $this->config->get('system', 'max_image_length');
161 if ($max_length > 0) {
162 $image->scaleDown($max_length);
163 $filesize = strlen($image->asString());
164 $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]);
167 $width = $image->getWidth();
168 $height = $image->getHeight();
170 $maximagesize = Strings::getBytesFromShorthand($this->config->get('system', 'maximagesize'));
172 if ($maximagesize && $filesize > $maximagesize) {
173 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
174 foreach ([5120, 2560, 1280, 640] as $pixels) {
175 if ($filesize > $maximagesize && max($width, $height) > $pixels) {
176 $this->logger->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
177 $image->scaleDown($pixels);
178 $filesize = strlen($image->asString());
179 $width = $image->getWidth();
180 $height = $image->getHeight();
184 if ($filesize > $maximagesize) {
186 $this->logger->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
187 $this->return(401, $this->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)));
191 $resource_id = Photo::newResource();
195 // If we don't have an album name use the Wall Photos album
196 if (!strlen($album)) {
197 $album = $this->t('Wall Photos');
200 $allow_cid = '<' . $owner['id'] . '>';
202 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
204 $this->logger->warning('Photo::store() failed', ['result' => $result]);
205 $this->return(401, $this->t('Image upload failed.'));
208 if ($width > 640 || $height > 640) {
209 $image->scaleDown(640);
210 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid);
216 if ($width > 320 || $height > 320) {
217 $image->scaleDown(320);
218 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid);
219 if ($result && ($smallest == 0)) {
224 $this->logger->info('upload done');
225 $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");
229 * @param int $httpCode
230 * @param string $message
231 * @param bool $systemMessage
233 * @throws InternalServerErrorException
235 private function return(int $httpCode, string $message, bool $systemMessage = false): void
238 $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true];
239 $this->response->setType(Response::TYPE_JSON, 'application/json');
240 $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
242 if ($systemMessage) {
243 $this->systemMessages->addNotice($message);
246 if ($httpCode >= 400) {
247 $this->response->setStatus($httpCode, $message);
250 $this->response->addContent($message);
253 $this->page->exit($this->response->generate());