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;
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;
51 class Photo extends BaseModule
56 * Fetch a photo or an avatar, in optional size, check for permissions and
59 protected function rawContent(array $request = [])
61 $totalstamp = microtime(true);
63 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
64 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
65 if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
66 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
68 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
69 header('Cache-Control: max-age=31536000');
70 if (function_exists('header_remove')) {
71 header_remove('Last-Modified');
72 header_remove('Expires');
73 header_remove('Cache-Control');
75 throw new NotModifiedException();
78 Profile::addVisitorCookieForHTTPSigner();
81 $square_resize = true;
83 $stamp = microtime(true);
85 if (!empty($this->parameters['type'])) {
86 if (!empty($this->parameters['customsize'])) {
87 $customsize = intval($this->parameters['customsize']);
88 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
91 if (!empty($this->parameters['guid'])) {
92 $guid = $this->parameters['guid'];
93 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
94 if (empty($account)) {
95 throw new HTTPException\NotFoundException();
101 // Contact Id Fallback, to remove after version 2021.12
102 if (isset($this->parameters['contact_id'])) {
103 $id = intval($this->parameters['contact_id']);
106 if (!empty($this->parameters['nickname_ext'])) {
107 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
108 $user = User::getByNickname($nickname, ['uid']);
110 throw new HTTPException\NotFoundException();
116 // User Id Fallback, to remove after version 2021.12
117 if (!empty($this->parameters['uid_ext'])) {
118 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
121 // Please refactor this for the love of everything that's good
122 if (isset($this->parameters['id'])) {
123 $id = $this->parameters['id'];
127 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
128 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
131 $photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
133 $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
135 if (substr($photoid, -2, 1) == '-') {
136 $scale = intval(substr($photoid, -1, 1));
137 $photoid = substr($photoid, 0, -2);
139 $photo = MPhoto::getPhoto($photoid, $scale);
140 if ($photo === false) {
141 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
145 $fetch = microtime(true) - $stamp;
147 if ($photo === false) {
148 throw new HTTPException\NotFoundException();
151 $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
153 $stamp = microtime(true);
155 $imgdata = MPhoto::getImageDataForPhoto($photo);
156 if (empty($imgdata)) {
157 throw new HTTPException\NotFoundException();
160 // The mimetype for an external or system resource can only be known reliably after it had been fetched
161 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
162 $mimetype = Images::getMimeTypeByData($imgdata);
163 if (!empty($mimetype)) {
164 $photo['type'] = $mimetype;
168 $data = microtime(true) - $stamp;
170 if (empty($imgdata)) {
171 Logger::warning('Invalid photo', ['id' => $photo['id']]);
172 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
173 $reference = json_decode($photo['backend-ref'], true);
174 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
176 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
178 throw new HTTPException\InternalServerErrorException($error);
181 // if customsize is set and image is not a gif, resize it
182 if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
183 $img = new Image($imgdata, $photo['type']);
184 $img->scaleToSquare($customsize);
185 $imgdata = $img->asString();
186 } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
187 $img = new Image($imgdata, $photo['type']);
188 $img->scaleDown($customsize);
189 $imgdata = $img->asString();
192 if (function_exists('header_remove')) {
193 header_remove('Pragma');
194 header_remove('pragma');
197 header('Content-type: ' . $photo['type']);
199 $stamp = microtime(true);
201 // it is a private photo that they have no permission to view.
202 // tell the browser not to cache it, in case they authenticate
203 // and subsequently have permission to see it
204 header('Cache-Control: no-store, no-cache, must-revalidate');
206 $md5 = $photo['hash'] ?: md5($imgdata);
207 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
208 header("Etag: \"{$md5}\"");
209 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
210 header('Cache-Control: max-age=31536000');
212 $checksum = microtime(true) - $stamp;
214 $stamp = microtime(true);
216 $output = microtime(true) - $stamp;
218 $total = microtime(true) - $totalstamp;
219 $rest = $total - ($fetch + $data + $checksum + $output);
221 if (!is_null($scale) && ($scale < 4)) {
222 Logger::debug('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
223 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
224 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
225 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
232 * Fetches photo record by given id number, type and custom size
234 * @param int $id Photo id
235 * @param string $type Photo type
236 * @param int $customsize Custom size (?)
237 * @return array|bool Array on success, false on error
239 private static function getPhotoById(int $id, string $type, int $customsize)
243 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
247 $url = $media['preview'];
249 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
250 $url = $media['url'];
257 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
258 return MPhoto::getPhoto($matches[1], $matches[2]);
261 return MPhoto::createPhotoForExternalResource($url, (int)DI::userSession()->getLocalUserId(), $media['mimetype'] ?? '');
263 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
268 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
269 return MPhoto::getPhoto($matches[1], $matches[2]);
272 return MPhoto::createPhotoForExternalResource($media['url'], (int)DI::userSession()->getLocalUserId(), $media['mimetype']);
274 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
279 return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '');
281 $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'xmpp', 'addr', 'network', 'failed', 'updated'];
282 $contact = Contact::getById($id, $fields);
283 if (empty($contact)) {
287 // For local users directly use the photo record that is marked as the profile
288 if (Network::isLocalLink($contact['url'])) {
289 $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
290 if (!empty($contact)) {
291 if ($customsize <= Proxy::PIXEL_MICRO) {
293 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
298 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
299 if (!empty($photo)) {
305 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
306 $contact = Contact::getByURL($contact['url'], false, $fields);
309 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
310 // Fetch photo directly
311 $resourceid = MPhoto::ridFromURI($contact['photo']);
312 if (!empty($resourceid)) {
313 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
314 if (!empty($photo)) {
317 $url = $contact['avatar'];
320 $url = $contact['photo'];
322 } elseif (!empty($contact['avatar'])) {
323 $url = $contact['avatar'];
327 $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
329 $mimetext = $mime[0] . '/' . $mime[1];
331 // Only update federated accounts that hadn't failed before and hadn't been updated recently
332 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
333 && ((time() - strtotime($contact['updated']) > 86400));
335 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
336 $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
337 Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
340 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
341 Worker::add(Worker::PRIORITY_LOW, 'UpdateContact', $id);
343 Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
346 if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
347 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
349 } if (!empty($mimetext)) {
350 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
353 if (empty($mimetext)) {
354 if ($customsize <= Proxy::PIXEL_MICRO) {
355 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_MICRO);
356 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
357 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_THUMB);
359 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_SMALL);
362 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
364 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
365 $contact = Contact::getById($id, $fields);
366 if (empty($contact)) {
369 If (($contact['uid'] != 0) && empty($contact['header'])) {
370 $contact = Contact::getByURL($contact['url'], false, $fields);
372 if (!empty($contact['header'])) {
373 $url = $contact['header'];
375 $url = Contact::getDefaultHeader($contact);
377 return MPhoto::createPhotoForExternalResource($url);
379 $photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
380 if (!empty($photo)) {
383 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
396 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
398 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
403 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
406 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
410 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
413 $parts = parse_url($default);
414 if (!empty($parts['scheme']) || !empty($parts['host'])) {
415 $photo = MPhoto::createPhotoForExternalResource($default);
417 $photo = MPhoto::createPhotoForSystemResource($default);