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\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Photo as MPhoto;
30 use Friendica\Model\Post;
31 use Friendica\Model\Profile;
32 use Friendica\Core\Storage\Type\ExternalResource;
33 use Friendica\Core\Storage\Type\SystemResource;
34 use Friendica\Model\User;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\HTTPException\NotModifiedException;
37 use Friendica\Object\Image;
38 use Friendica\Util\Images;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Proxy;
46 class Photo extends BaseModule
51 * Fetch a photo or an avatar, in optional size, check for permissions and
54 protected function rawContent(array $request = [])
56 $totalstamp = microtime(true);
58 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
59 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
60 if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
61 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
63 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
64 header("Cache-Control: max-age=31536000");
65 if (function_exists("header_remove")) {
66 header_remove("Last-Modified");
67 header_remove("Expires");
68 header_remove("Cache-Control");
70 throw new NotModifiedException();
73 Profile::addVisitorCookieForHTTPSigner();
76 $square_resize = true;
78 $stamp = microtime(true);
80 if (!empty($this->parameters['type'])) {
81 if (!empty($this->parameters['customsize'])) {
82 $customsize = intval($this->parameters['customsize']);
83 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
86 if (!empty($this->parameters['guid'])) {
87 $guid = $this->parameters['guid'];
88 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
89 if (empty($account)) {
90 throw new HTTPException\NotFoundException();
96 // Contact Id Fallback, to remove after version 2021.12
97 if (isset($this->parameters['contact_id'])) {
98 $id = intval($this->parameters['contact_id']);
101 if (!empty($this->parameters['nickname_ext'])) {
102 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
103 $user = User::getByNickname($nickname, ['uid']);
105 throw new HTTPException\NotFoundException();
111 // User Id Fallback, to remove after version 2021.12
112 if (!empty($this->parameters['uid_ext'])) {
113 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
116 // Please refactor this for the love of everything that's good
117 if (isset($this->parameters['id'])) {
118 $id = $this->parameters['id'];
122 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
123 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
126 $photo = self::getPhotoByid($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
128 $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
130 if (substr($photoid, -2, 1) == "-") {
131 $scale = intval(substr($photoid, -1, 1));
132 $photoid = substr($photoid, 0, -2);
134 $photo = MPhoto::getPhoto($photoid, $scale);
135 if ($photo === false) {
136 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
140 $fetch = microtime(true) - $stamp;
142 if ($photo === false) {
143 throw new HTTPException\NotFoundException();
146 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
148 $stamp = microtime(true);
150 $imgdata = MPhoto::getImageDataForPhoto($photo);
151 if (empty($imgdata)) {
152 throw new HTTPException\NotFoundException();
155 // The mimetype for an external or system resource can only be known reliably after it had been fetched
156 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
157 $mimetype = Images::getMimeTypeByData($imgdata);
158 if (!empty($mimetype)) {
159 $photo['type'] = $mimetype;
163 $data = microtime(true) - $stamp;
165 if (empty($imgdata)) {
166 Logger::warning('Invalid photo', ['id' => $photo['id']]);
167 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
168 $reference = json_decode($photo['backend-ref'], true);
169 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
171 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
173 throw new HTTPException\InternalServerErrorException($error);
176 // if customsize is set and image is not a gif, resize it
177 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
178 $img = new Image($imgdata, $photo['type']);
179 $img->scaleToSquare($customsize);
180 $imgdata = $img->asString();
181 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
182 $img = new Image($imgdata, $photo['type']);
183 $img->scaleDown($customsize);
184 $imgdata = $img->asString();
187 if (function_exists("header_remove")) {
188 header_remove("Pragma");
189 header_remove("pragma");
192 header("Content-type: " . $photo['type']);
194 $stamp = microtime(true);
196 // it is a private photo that they have no permission to view.
197 // tell the browser not to cache it, in case they authenticate
198 // and subsequently have permission to see it
199 header("Cache-Control: no-store, no-cache, must-revalidate");
201 $md5 = $photo['hash'] ?: md5($imgdata);
202 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
203 header("Etag: \"{$md5}\"");
204 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
205 header("Cache-Control: max-age=31536000");
207 $checksum = microtime(true) - $stamp;
209 $stamp = microtime(true);
211 $output = microtime(true) - $stamp;
213 $total = microtime(true) - $totalstamp;
214 $rest = $total - ($fetch + $data + $checksum + $output);
216 if (!is_null($scale) && ($scale < 4)) {
217 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
218 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
219 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
220 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
226 private static function getPhotoByid(int $id, $type, $customsize)
230 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
234 $url = $media['preview'];
236 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
237 $url = $media['url'];
244 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
245 return MPhoto::getPhoto($matches[1], $matches[2]);
248 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
250 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
255 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
256 return MPhoto::getPhoto($matches[1], $matches[2]);
259 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
261 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
266 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
268 $contact = Contact::getById($id, ['uid', 'url', 'nurl', 'avatar', 'photo', 'xmpp', 'addr']);
269 if (empty($contact)) {
273 // For local users directly use the photo record that is marked as the profile
274 if (Network::isLocalLink($contact['url'])) {
275 $contact = Contact::selectFirst(['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr'], ['nurl' => $contact['nurl'], 'self' => true]);
276 if (!empty($contact)) {
277 if ($customsize <= Proxy::PIXEL_MICRO) {
279 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
284 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $contact['uid'], "profile" => 1]);
285 if (!empty($photo)) {
291 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
292 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
295 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
296 // Fetch photo directly
297 $resourceid = MPhoto::ridFromURI($contact['photo']);
298 if (!empty($resourceid)) {
299 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
300 if (!empty($photo)) {
304 // We continue with the avatar link when the photo link is invalid
305 $url = $contact['avatar'];
306 } elseif (!empty($contact['avatar'])) {
307 $url = $contact['avatar'];
311 $mime = ParseUrl::getContentType($url);
313 $mimetext = $mime[0] . '/' . $mime[1];
315 Logger::info('Invalid file', ['url' => $url]);
317 if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
318 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
322 if (empty($mimetext)) {
323 if ($customsize <= Proxy::PIXEL_MICRO) {
324 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
325 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
326 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
328 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
331 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
333 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
334 $contact = Contact::getById($id, $fields);
335 if (empty($contact)) {
338 If (($contact['uid'] != 0) && empty($contact['header'])) {
339 $contact = Contact::getByURL($contact['url'], false, $fields);
341 if (!empty($contact['header'])) {
342 $url = $contact['header'];
344 $url = Contact::getDefaultHeader($contact);
346 return MPhoto::createPhotoForExternalResource($url);
348 $photo = MPhoto::selectFirst([], ["scale" => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
349 if (!empty($photo)) {
352 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
365 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
367 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
372 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
375 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
379 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
382 $parts = parse_url($default);
383 if (!empty($parts['scheme']) || !empty($parts['host'])) {
384 $photo = MPhoto::createPhotoForExternalResource($default);
386 $photo = MPhoto::createPhotoForSystemResource($default);