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;
30 use Friendica\Model\Photo;
31 use Friendica\Model\User;
32 use Friendica\Module\BaseApi;
33 use Friendica\Module\Response;
34 use Friendica\Navigation\SystemMessages;
35 use Friendica\Network\HTTPException\InternalServerErrorException;
36 use Friendica\Object\Image;
37 use Friendica\Util\Images;
38 use Friendica\Util\Profiler;
39 use Friendica\Util\Strings;
40 use Psr\Log\LoggerInterface;
43 * Asynchronous photo upload module
45 * Only used as the target action of the AjaxUpload Javascript library
47 class Upload extends \Friendica\BaseModule
52 /** @var IHandleUserSessions */
55 /** @var SystemMessages */
56 private $systemMessages;
58 /** @var IManageConfigValues */
62 private $isJson = false;
64 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 = [])
66 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
68 $this->database = $database;
69 $this->userSession = $userSession;
70 $this->systemMessages = $systemMessages;
71 $this->config = $config;
74 protected function post(array $request = [])
76 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
78 $album = trim($request['album'] ?? '');
80 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
83 $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
84 return $this->return(401, $this->t('Invalid request.'));
87 if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
88 $this->logger->warning('Empty "userfile" and "media" field');
89 return $this->return(401, $this->t('Invalid request.'));
97 if (!empty($_FILES['userfile'])) {
98 $src = $_FILES['userfile']['tmp_name'];
99 $filename = basename($_FILES['userfile']['name']);
100 $filesize = intval($_FILES['userfile']['size']);
101 $filetype = $_FILES['userfile']['type'];
102 } elseif (!empty($_FILES['media'])) {
103 if (!empty($_FILES['media']['tmp_name'])) {
104 if (is_array($_FILES['media']['tmp_name'])) {
105 $src = $_FILES['media']['tmp_name'][0];
107 $src = $_FILES['media']['tmp_name'];
111 if (!empty($_FILES['media']['name'])) {
112 if (is_array($_FILES['media']['name'])) {
113 $filename = basename($_FILES['media']['name'][0]);
115 $filename = basename($_FILES['media']['name']);
119 if (!empty($_FILES['media']['size'])) {
120 if (is_array($_FILES['media']['size'])) {
121 $filesize = intval($_FILES['media']['size'][0]);
123 $filesize = intval($_FILES['media']['size']);
127 if (!empty($_FILES['media']['type'])) {
128 if (is_array($_FILES['media']['type'])) {
129 $filetype = $_FILES['media']['type'][0];
131 $filetype = $_FILES['media']['type'];
137 $this->logger->warning('File source (temporary file) cannot be determined', ['$_FILES' => $_FILES]);
138 return $this->return(401, $this->t('Invalid request.'), true);
141 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
143 $this->logger->info('File upload:', [
145 'filename' => $filename,
146 'filesize' => $filesize,
147 'filetype' => $filetype,
150 $imagedata = @file_get_contents($src);
151 $image = new Image($imagedata, $filetype);
153 if (!$image->isValid()) {
155 $this->logger->warning($this->t('Unable to process image.'), ['imagedata[]' => gettype($imagedata), 'filetype' => $filetype]);
156 return $this->return(401, $this->t('Unable to process image.'));
159 $image->orient($src);
162 $max_length = $this->config->get('system', 'max_image_length');
163 if ($max_length > 0) {
164 $image->scaleDown($max_length);
165 $filesize = strlen($image->asString());
166 $this->logger->info('File upload: Scaling picture to new size', ['max_length' => $max_length]);
169 $width = $image->getWidth();
170 $height = $image->getHeight();
172 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
174 if ($maximagesize == 0) {
178 if (!empty($maximagesize) && $filesize > $maximagesize) {
179 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
180 foreach ([5120, 2560, 1280, 640] as $pixels) {
181 if ($filesize > $maximagesize && max($width, $height) > $pixels) {
182 $this->logger->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
183 $image->scaleDown($pixels);
184 $filesize = strlen($image->asString());
185 $width = $image->getWidth();
186 $height = $image->getHeight();
190 if ($filesize > $maximagesize) {
192 $this->logger->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
193 return $this->return(401, $this->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)));
197 $resource_id = Photo::newResource();
201 // If we don't have an album name use the Wall Photos album
202 if (!strlen($album)) {
203 $album = $this->t('Wall Photos');
206 $allow_cid = '<' . $owner['id'] . '>';
208 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid);
210 $this->logger->warning('Photo::store() failed', ['result' => $result]);
211 return $this->return(401, $this->t('Image upload failed.'));
214 if ($width > 640 || $height > 640) {
215 $image->scaleDown(640);
216 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid);
222 if ($width > 320 || $height > 320) {
223 $image->scaleDown(320);
224 $result = Photo::store($image, $owner['uid'], 0, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid);
225 if ($result && ($smallest == 0)) {
230 $this->logger->info('upload done');
231 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");
235 * @param int $httpCode
236 * @param string $message
237 * @param bool $systemMessage
239 * @throws InternalServerErrorException
241 private function return(int $httpCode, string $message, bool $systemMessage = false): void
244 $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true];
245 $this->response->setType(Response::TYPE_JSON, 'application/json');
246 $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
248 if ($systemMessage) {
249 $this->systemMessages->addNotice($message);
252 if ($httpCode >= 400) {
253 $this->response->setStatus($httpCode, $message);
256 $this->response->addContent($message);