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;
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Database\DBA;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Photo as MPhoto;
31 use Friendica\Model\Post;
32 use Friendica\Model\Profile;
33 use Friendica\Core\Storage\Type\ExternalResource;
34 use Friendica\Core\Storage\Type\SystemResource;
35 use Friendica\Core\System;
36 use Friendica\Core\Worker;
37 use Friendica\Model\User;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Network\HTTPException\NotModifiedException;
42 use Friendica\Object\Image;
43 use Friendica\Util\Images;
44 use Friendica\Util\Network;
45 use Friendica\Util\ParseUrl;
46 use Friendica\Util\Proxy;
47 use Friendica\Worker\UpdateContact;
52 class Photo extends BaseApi
57 * Fetch a photo or an avatar, in optional size, check for permissions and
60 protected function rawContent(array $request = [])
62 $totalstamp = microtime(true);
64 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
65 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
66 if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
67 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
69 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
70 header('Cache-Control: max-age=31536000');
71 if (function_exists('header_remove')) {
72 header_remove('Last-Modified');
73 header_remove('Expires');
74 header_remove('Cache-Control');
76 throw new NotModifiedException();
79 Profile::addVisitorCookieForHTTPSigner();
82 $square_resize = true;
84 $stamp = microtime(true);
86 if (!empty($this->parameters['type'])) {
87 if (!empty($this->parameters['customsize'])) {
88 $customsize = intval($this->parameters['customsize']);
89 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
92 if (!empty($this->parameters['guid'])) {
93 $guid = $this->parameters['guid'];
94 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
95 if (empty($account)) {
96 throw new HTTPException\NotFoundException();
102 // Contact Id Fallback, to remove after version 2021.12
103 if (isset($this->parameters['contact_id'])) {
104 $id = intval($this->parameters['contact_id']);
107 if (!empty($this->parameters['nickname_ext'])) {
108 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
109 $user = User::getByNickname($nickname, ['uid']);
111 throw new HTTPException\NotFoundException();
117 // User Id Fallback, to remove after version 2021.12
118 if (!empty($this->parameters['uid_ext'])) {
119 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
122 // Please refactor this for the love of everything that's good
123 if (isset($this->parameters['id'])) {
124 $id = $this->parameters['id'];
128 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
129 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
132 $photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
134 $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
136 if (substr($photoid, -2, 1) == '-') {
137 $scale = intval(substr($photoid, -1, 1));
138 $photoid = substr($photoid, 0, -2);
141 if (!empty($this->parameters['size'])) {
142 switch ($this->parameters['size']) {
152 $photo = MPhoto::getPhoto($photoid, $scale, self::getCurrentUserID());
153 if ($photo === false) {
154 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
158 $fetch = microtime(true) - $stamp;
160 if ($photo === false) {
161 throw new HTTPException\NotFoundException();
164 $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
166 $stamp = microtime(true);
168 $imgdata = MPhoto::getImageDataForPhoto($photo);
169 if (empty($imgdata) && empty($photo['blurhash'])) {
170 throw new HTTPException\NotFoundException();
171 } elseif (empty($imgdata) && !empty($photo['blurhash'])) {
172 $image = New Image('', 'image/png');
173 $image->getFromBlurHash($photo['blurhash'], $photo['width'], $photo['height']);
174 $imgdata = $image->asString();
177 // The mimetype for an external or system resource can only be known reliably after it had been fetched
178 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
179 $mimetype = Images::getMimeTypeByData($imgdata);
180 if (!empty($mimetype)) {
181 $photo['type'] = $mimetype;
185 $data = microtime(true) - $stamp;
187 if (empty($imgdata)) {
188 Logger::warning('Invalid photo', ['id' => $photo['id']]);
189 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
190 $reference = json_decode($photo['backend-ref'], true);
191 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
193 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
195 throw new HTTPException\InternalServerErrorException($error);
198 if (!empty($request['static'])) {
199 $img = new Image($imgdata, $photo['type']);
201 $imgdata = $img->asString();
204 // if customsize is set and image is not a gif, resize it
205 if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
206 $img = new Image($imgdata, $photo['type']);
207 $img->scaleToSquare($customsize);
208 $imgdata = $img->asString();
209 } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
210 $img = new Image($imgdata, $photo['type']);
211 $img->scaleDown($customsize);
212 $imgdata = $img->asString();
215 if (function_exists('header_remove')) {
216 header_remove('Pragma');
217 header_remove('pragma');
220 header('Content-type: ' . $photo['type']);
222 $stamp = microtime(true);
224 // it is a private photo that they have no permission to view.
225 // tell the browser not to cache it, in case they authenticate
226 // and subsequently have permission to see it
227 header('Cache-Control: no-store, no-cache, must-revalidate');
229 $md5 = $photo['hash'] ?: md5($imgdata);
230 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
231 header("Etag: \"{$md5}\"");
232 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
233 header('Cache-Control: max-age=31536000');
235 $checksum = microtime(true) - $stamp;
237 $stamp = microtime(true);
239 $output = microtime(true) - $stamp;
241 $total = microtime(true) - $totalstamp;
242 $rest = $total - ($fetch + $data + $checksum + $output);
244 if (!is_null($scale) && ($scale < 4)) {
245 Logger::debug('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
246 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
247 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
248 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
255 * Fetches photo record by given id number, type and custom size
257 * @param int $id Photo id
258 * @param string $type Photo type
259 * @param int $customsize Custom size (?)
260 * @return array|bool Array on success, false on error
262 private static function getPhotoById(int $id, string $type, int $customsize)
266 $media = DBA::selectFirst('post-media', ['preview', 'url', 'preview-height', 'preview-width', 'height', 'width', 'mimetype', 'type', 'uri-id', 'blurhash'], ['id' => $id]);
270 $url = $media['preview'];
271 $width = $media['preview-width'];
272 $height = $media['preview-height'];
274 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
275 $url = $media['url'];
276 $width = $media['width'];
277 $height = $media['height'];
284 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
285 return MPhoto::getPhoto($matches[1], $matches[2], self::getCurrentUserID());
288 return MPhoto::createPhotoForExternalResource($url, (int)DI::userSession()->getLocalUserId(), $media['mimetype'] ?? '', $media['blurhash'], $width, $height);
290 $media = DBA::selectFirst('post-media', ['url', 'height', 'width', 'mimetype', 'uri-id', 'blurhash'], ['id' => $id, 'type' => Post\Media::IMAGE]);
295 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
296 return MPhoto::getPhoto($matches[1], $matches[2], self::getCurrentUserID());
299 return MPhoto::createPhotoForExternalResource($media['url'], (int)DI::userSession()->getLocalUserId(), $media['mimetype'], $media['blurhash'], $media['width'], $media['height']);
301 $link = DBA::selectFirst('post-link', ['url', 'mimetype', 'blurhash', 'width', 'height'], ['id' => $id]);
306 return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0);
308 $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated'];
309 $contact = Contact::getById($id, $fields);
310 if (empty($contact)) {
314 // For local users directly use the photo record that is marked as the profile
315 if (Network::isLocalLink($contact['url'])) {
316 $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
317 if (!empty($contact)) {
318 if ($customsize <= Proxy::PIXEL_MICRO) {
320 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
325 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
326 if (!empty($photo)) {
332 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
333 $contact = Contact::getByURL($contact['url'], false, $fields);
336 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
337 // Fetch photo directly
338 $resourceid = MPhoto::ridFromURI($contact['photo']);
339 if (!empty($resourceid)) {
340 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
341 if (!empty($photo)) {
344 $url = $contact['avatar'];
347 $url = $contact['photo'];
349 } elseif (!empty($contact['avatar'])) {
350 $url = $contact['avatar'];
353 // If it is a local link, we save resources by just redirecting to it.
354 if (!empty($url) && Network::isLocalLink($url)) {
355 System::externalRedirect($url);
360 $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
362 $mimetext = $mime[0] . '/' . $mime[1];
364 // Only update federated accounts that hadn't failed before and hadn't been updated recently
365 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
366 && ((time() - strtotime($contact['updated']) > 86400));
368 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
369 $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
370 Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
374 UpdateContact::add(Worker::PRIORITY_LOW, $id);
375 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
376 } catch (\InvalidArgumentException $e) {
377 Logger::notice($e->getMessage(), ['id' => $id, 'contact' => $contact]);
380 Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
383 if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
384 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
386 } if (!empty($mimetext)) {
387 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
390 if (empty($mimetext) && !empty($contact['blurhash'])) {
391 $image = New Image('', 'image/png');
392 $image->getFromBlurHash($contact['blurhash'], $customsize, $customsize);
393 return MPhoto::createPhotoForImageData($image->asString());
394 } elseif (empty($mimetext)) {
395 if ($customsize <= Proxy::PIXEL_MICRO) {
396 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_MICRO);
397 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
398 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_THUMB);
400 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_SMALL);
402 if (Network::isLocalLink($url)) {
403 System::externalRedirect($url);
406 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext, $contact['blurhash'] ?? null, $customsize, $customsize);
408 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
409 $contact = Contact::getById($id, $fields);
410 if (empty($contact)) {
414 if (Network::isLocalLink($contact['url'])) {
415 $header_uid = User::getIdForURL($contact['url']);
416 if (empty($header_uid)) {
417 throw new HTTPException\NotFoundException();
419 return self::getBannerForUser($header_uid);
422 If (($contact['uid'] != 0) && empty($contact['header'])) {
423 $contact = Contact::getByURL($contact['url'], false, $fields);
425 if (!empty($contact['header'])) {
426 $url = $contact['header'];
428 $url = Contact::getDefaultHeader($contact);
429 if (Network::isLocalLink($url)) {
430 System::externalRedirect($url);
433 return MPhoto::createPhotoForExternalResource($url);
435 return self::getBannerForUser($id);
448 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
450 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
455 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
458 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
462 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
465 if (Network::isLocalLink($default)) {
466 System::externalRedirect($default);
469 $parts = parse_url($default);
470 if (!empty($parts['scheme']) || !empty($parts['host'])) {
471 $photo = MPhoto::createPhotoForExternalResource($default);
473 $photo = MPhoto::createPhotoForSystemResource($default);
479 private static function getBannerForUser(int $uid): array
481 $photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $uid, 'photo-type' => MPhoto::USER_BANNER]);
482 if (!empty($photo)) {
485 return MPhoto::createPhotoForImageData(file_get_contents(DI::basePath() . '/images/friendica-banner.jpg'));