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\Worker;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Network\HTTPException;
40 use Friendica\Network\HTTPException\NotModifiedException;
41 use Friendica\Object\Image;
42 use Friendica\Util\Images;
43 use Friendica\Util\Network;
44 use Friendica\Util\ParseUrl;
45 use Friendica\Util\Proxy;
50 class Photo extends BaseModule
55 * Fetch a photo or an avatar, in optional size, check for permissions and
58 protected function rawContent(array $request = [])
60 $totalstamp = microtime(true);
62 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
63 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
64 if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
65 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
67 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
68 header("Cache-Control: max-age=31536000");
69 if (function_exists("header_remove")) {
70 header_remove("Last-Modified");
71 header_remove("Expires");
72 header_remove("Cache-Control");
74 throw new NotModifiedException();
77 Profile::addVisitorCookieForHTTPSigner();
80 $square_resize = true;
82 $stamp = microtime(true);
84 if (!empty($this->parameters['type'])) {
85 if (!empty($this->parameters['customsize'])) {
86 $customsize = intval($this->parameters['customsize']);
87 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
90 if (!empty($this->parameters['guid'])) {
91 $guid = $this->parameters['guid'];
92 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
93 if (empty($account)) {
94 throw new HTTPException\NotFoundException();
100 // Contact Id Fallback, to remove after version 2021.12
101 if (isset($this->parameters['contact_id'])) {
102 $id = intval($this->parameters['contact_id']);
105 if (!empty($this->parameters['nickname_ext'])) {
106 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
107 $user = User::getByNickname($nickname, ['uid']);
109 throw new HTTPException\NotFoundException();
115 // User Id Fallback, to remove after version 2021.12
116 if (!empty($this->parameters['uid_ext'])) {
117 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
120 // Please refactor this for the love of everything that's good
121 if (isset($this->parameters['id'])) {
122 $id = $this->parameters['id'];
126 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
127 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
130 $photo = self::getPhotoByid($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
132 $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
134 if (substr($photoid, -2, 1) == "-") {
135 $scale = intval(substr($photoid, -1, 1));
136 $photoid = substr($photoid, 0, -2);
138 $photo = MPhoto::getPhoto($photoid, $scale);
139 if ($photo === false) {
140 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
144 $fetch = microtime(true) - $stamp;
146 if ($photo === false) {
147 throw new HTTPException\NotFoundException();
150 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
152 $stamp = microtime(true);
154 $imgdata = MPhoto::getImageDataForPhoto($photo);
155 if (empty($imgdata)) {
156 throw new HTTPException\NotFoundException();
159 // The mimetype for an external or system resource can only be known reliably after it had been fetched
160 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
161 $mimetype = Images::getMimeTypeByData($imgdata);
162 if (!empty($mimetype)) {
163 $photo['type'] = $mimetype;
167 $data = microtime(true) - $stamp;
169 if (empty($imgdata)) {
170 Logger::warning('Invalid photo', ['id' => $photo['id']]);
171 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
172 $reference = json_decode($photo['backend-ref'], true);
173 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
175 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
177 throw new HTTPException\InternalServerErrorException($error);
180 // if customsize is set and image is not a gif, resize it
181 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
182 $img = new Image($imgdata, $photo['type']);
183 $img->scaleToSquare($customsize);
184 $imgdata = $img->asString();
185 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
186 $img = new Image($imgdata, $photo['type']);
187 $img->scaleDown($customsize);
188 $imgdata = $img->asString();
191 if (function_exists("header_remove")) {
192 header_remove("Pragma");
193 header_remove("pragma");
196 header("Content-type: " . $photo['type']);
198 $stamp = microtime(true);
200 // it is a private photo that they have no permission to view.
201 // tell the browser not to cache it, in case they authenticate
202 // and subsequently have permission to see it
203 header("Cache-Control: no-store, no-cache, must-revalidate");
205 $md5 = $photo['hash'] ?: md5($imgdata);
206 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
207 header("Etag: \"{$md5}\"");
208 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
209 header("Cache-Control: max-age=31536000");
211 $checksum = microtime(true) - $stamp;
213 $stamp = microtime(true);
215 $output = microtime(true) - $stamp;
217 $total = microtime(true) - $totalstamp;
218 $rest = $total - ($fetch + $data + $checksum + $output);
220 if (!is_null($scale) && ($scale < 4)) {
221 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
222 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
223 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
224 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
227 DI::page()->logRuntime();
231 private static function getPhotoByid(int $id, $type, $customsize)
235 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
239 $url = $media['preview'];
241 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
242 $url = $media['url'];
249 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
250 return MPhoto::getPhoto($matches[1], $matches[2]);
253 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
255 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
260 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
261 return MPhoto::getPhoto($matches[1], $matches[2]);
264 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
266 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
271 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
273 $fields = ['uid', 'url', 'nurl', 'avatar', 'photo', 'xmpp', 'addr', 'network', 'failed', 'updated'];
274 $contact = Contact::getById($id, $fields);
275 if (empty($contact)) {
279 // For local users directly use the photo record that is marked as the profile
280 if (Network::isLocalLink($contact['url'])) {
281 $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
282 if (!empty($contact)) {
283 if ($customsize <= Proxy::PIXEL_MICRO) {
285 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
290 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $contact['uid'], "profile" => 1]);
291 if (!empty($photo)) {
297 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
298 $contact = Contact::getByURL($contact['url'], false, $fields);
301 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
302 // Fetch photo directly
303 $resourceid = MPhoto::ridFromURI($contact['photo']);
304 if (!empty($resourceid)) {
305 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
306 if (!empty($photo)) {
309 $url = $contact['avatar'];
312 $url = $contact['photo'];
314 } elseif (!empty($contact['avatar'])) {
315 $url = $contact['avatar'];
319 $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
321 $mimetext = $mime[0] . '/' . $mime[1];
323 // Only update federated accounts that hadn't failed before and hadn't been updated recently
324 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
325 && ((time() - strtotime($contact['updated']) > 86400));
327 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
328 $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
329 Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
332 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
333 Worker::add(PRIORITY_LOW, "UpdateContact", $id);
335 Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
338 if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
339 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
341 } if (!empty($mimetext)) {
342 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
345 if (empty($mimetext)) {
346 if ($customsize <= Proxy::PIXEL_MICRO) {
347 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
348 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
349 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
351 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
354 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
356 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
357 $contact = Contact::getById($id, $fields);
358 if (empty($contact)) {
361 If (($contact['uid'] != 0) && empty($contact['header'])) {
362 $contact = Contact::getByURL($contact['url'], false, $fields);
364 if (!empty($contact['header'])) {
365 $url = $contact['header'];
367 $url = Contact::getDefaultHeader($contact);
369 return MPhoto::createPhotoForExternalResource($url);
371 $photo = MPhoto::selectFirst([], ["scale" => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
372 if (!empty($photo)) {
375 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
388 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
390 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
395 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
398 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
402 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
405 $parts = parse_url($default);
406 if (!empty($parts['scheme']) || !empty($parts['host'])) {
407 $photo = MPhoto::createPhotoForExternalResource($default);
409 $photo = MPhoto::createPhotoForSystemResource($default);