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\Core\Session;
28 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Photo as MPhoto;
32 use Friendica\Model\Post;
33 use Friendica\Model\Profile;
34 use Friendica\Core\Storage\Type\ExternalResource;
35 use Friendica\Core\Storage\Type\SystemResource;
36 use Friendica\Core\System;
37 use Friendica\Core\Worker;
38 use Friendica\Model\User;
39 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
40 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\HTTPException\NotModifiedException;
43 use Friendica\Object\Image;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\ParseUrl;
47 use Friendica\Util\Proxy;
52 class Photo extends BaseModule
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);
140 $photo = MPhoto::getPhoto($photoid, $scale);
141 if ($photo === false) {
142 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
146 $fetch = microtime(true) - $stamp;
148 if ($photo === false) {
149 throw new HTTPException\NotFoundException();
152 $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
154 $stamp = microtime(true);
156 $imgdata = MPhoto::getImageDataForPhoto($photo);
157 if (empty($imgdata)) {
158 throw new HTTPException\NotFoundException();
161 // The mimetype for an external or system resource can only be known reliably after it had been fetched
162 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
163 $mimetype = Images::getMimeTypeByData($imgdata);
164 if (!empty($mimetype)) {
165 $photo['type'] = $mimetype;
169 $data = microtime(true) - $stamp;
171 if (empty($imgdata)) {
172 Logger::warning('Invalid photo', ['id' => $photo['id']]);
173 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
174 $reference = json_decode($photo['backend-ref'], true);
175 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
177 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
179 throw new HTTPException\InternalServerErrorException($error);
182 // if customsize is set and image is not a gif, resize it
183 if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
184 $img = new Image($imgdata, $photo['type']);
185 $img->scaleToSquare($customsize);
186 $imgdata = $img->asString();
187 } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
188 $img = new Image($imgdata, $photo['type']);
189 $img->scaleDown($customsize);
190 $imgdata = $img->asString();
193 if (function_exists('header_remove')) {
194 header_remove('Pragma');
195 header_remove('pragma');
198 header('Content-type: ' . $photo['type']);
200 $stamp = microtime(true);
202 // it is a private photo that they have no permission to view.
203 // tell the browser not to cache it, in case they authenticate
204 // and subsequently have permission to see it
205 header('Cache-Control: no-store, no-cache, must-revalidate');
207 $md5 = $photo['hash'] ?: md5($imgdata);
208 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
209 header("Etag: \"{$md5}\"");
210 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
211 header('Cache-Control: max-age=31536000');
213 $checksum = microtime(true) - $stamp;
215 $stamp = microtime(true);
217 $output = microtime(true) - $stamp;
219 $total = microtime(true) - $totalstamp;
220 $rest = $total - ($fetch + $data + $checksum + $output);
222 if (!is_null($scale) && ($scale < 4)) {
223 Logger::debug('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
224 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
225 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
226 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
233 * Fetches photo record by given id number, type and custom size
235 * @param int $id Photo id
236 * @param string $type Photo type
237 * @param int $customsize Custom size (?)
238 * @return array|bool Array on success, false on error
240 private static function getPhotoById(int $id, string $type, int $customsize)
244 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
248 $url = $media['preview'];
250 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
251 $url = $media['url'];
258 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
259 return MPhoto::getPhoto($matches[1], $matches[2]);
262 return MPhoto::createPhotoForExternalResource($url, (int)Session::getLocalUser(), $media['mimetype'] ?? '');
264 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
269 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
270 return MPhoto::getPhoto($matches[1], $matches[2]);
273 return MPhoto::createPhotoForExternalResource($media['url'], (int)Session::getLocalUser(), $media['mimetype']);
275 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
280 return MPhoto::createPhotoForExternalResource($link['url'], (int)Session::getLocalUser(), $link['mimetype'] ?? '');
282 $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'xmpp', 'addr', 'network', 'failed', 'updated'];
283 $contact = Contact::getById($id, $fields);
284 if (empty($contact)) {
288 // For local users directly use the photo record that is marked as the profile
289 if (Network::isLocalLink($contact['url'])) {
290 $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
291 if (!empty($contact)) {
292 if ($customsize <= Proxy::PIXEL_MICRO) {
294 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
299 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
300 if (!empty($photo)) {
306 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
307 $contact = Contact::getByURL($contact['url'], false, $fields);
310 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
311 // Fetch photo directly
312 $resourceid = MPhoto::ridFromURI($contact['photo']);
313 if (!empty($resourceid)) {
314 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
315 if (!empty($photo)) {
318 $url = $contact['avatar'];
321 $url = $contact['photo'];
323 } elseif (!empty($contact['avatar'])) {
324 $url = $contact['avatar'];
328 $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
330 $mimetext = $mime[0] . '/' . $mime[1];
332 // Only update federated accounts that hadn't failed before and hadn't been updated recently
333 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
334 && ((time() - strtotime($contact['updated']) > 86400));
336 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
337 $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
338 Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
341 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
342 Worker::add(Worker::PRIORITY_LOW, 'UpdateContact', $id);
344 Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
347 if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
348 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
350 } if (!empty($mimetext)) {
351 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
354 if (empty($mimetext)) {
355 if ($customsize <= Proxy::PIXEL_MICRO) {
356 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_MICRO);
357 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
358 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_THUMB);
360 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_SMALL);
363 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
365 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
366 $contact = Contact::getById($id, $fields);
367 if (empty($contact)) {
370 If (($contact['uid'] != 0) && empty($contact['header'])) {
371 $contact = Contact::getByURL($contact['url'], false, $fields);
373 if (!empty($contact['header'])) {
374 $url = $contact['header'];
376 $url = Contact::getDefaultHeader($contact);
378 return MPhoto::createPhotoForExternalResource($url);
380 $photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
381 if (!empty($photo)) {
384 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
397 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
399 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
404 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
407 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
411 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
414 $parts = parse_url($default);
415 if (!empty($parts['scheme']) || !empty($parts['host'])) {
416 $photo = MPhoto::createPhotoForExternalResource($default);
418 $photo = MPhoto::createPhotoForSystemResource($default);