3 * @copyright Copyright (C) 2010-2021, 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\Model\Storage\ExternalResource;
33 use Friendica\Model\Storage\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 public static function rawContent(array $parameters = [])
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($parameters['type'])) {
81 if (!empty($parameters['customsize'])) {
82 $customsize = intval($parameters['customsize']);
83 $square_resize = !in_array($parameters['type'], ['media', 'preview']);
86 if (!empty($parameters['guid'])) {
87 $guid = $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($parameters['contact_id'])) {
98 $id = intval($parameters['contact_id']);
101 if (!empty($parameters['nickname_ext'])) {
102 $nickname = pathinfo($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($parameters['uid_ext'])) {
113 $id = intval(pathinfo($parameters['uid_ext'], PATHINFO_FILENAME));
116 // Please refactor this for the love of everything that's good
117 if (isset($parameters['id'])) {
118 $id = $parameters['id'];
122 Logger::notice('No picture id was detected', ['parameters' => $parameters, 'query' => DI::args()->getQueryString()]);
123 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
126 $photo = self::getPhotoByid($id, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
128 $photoid = pathinfo($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', 'avatar', 'photo', 'xmpp', 'addr']);
269 if (empty($contact)) {
272 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
273 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
275 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
276 // Fetch photo directly
277 $resourceid = MPhoto::ridFromURI($contact['photo']);
278 if (!empty($resourceid)) {
279 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
280 if (!empty($photo)) {
284 // We continue with the avatar link when the photo link is invalid
285 $url = $contact['avatar'];
286 } elseif (!empty($contact['avatar'])) {
287 $url = $contact['avatar'];
291 $mime = ParseUrl::getContentType($url);
292 if (empty($mime) || ($mime[0] != 'image')) {
295 $mimetext = $mime[0] . '/' . $mime[1];
299 if ($customsize <= Proxy::PIXEL_MICRO) {
300 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
301 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
302 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
304 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
307 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
309 $contact = Contact::getById($id, ['uid', 'url', 'header']);
310 if (empty($contact)) {
313 If (($contact['uid'] != 0) && empty($contact['header'])) {
314 $contact = Contact::getByURL($contact['url'], false, ['header']);
316 if (!empty($contact['header'])) {
317 $url = $contact['header'];
319 $url = DI::baseUrl() . '/images/blank.png';
321 return MPhoto::createPhotoForExternalResource($url);
334 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
336 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
341 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
344 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
348 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
351 $parts = parse_url($default);
352 if (!empty($parts['scheme']) || !empty($parts['host'])) {
353 $photo = MPhoto::createPhotoForExternalResource($default);
355 $photo = MPhoto::createPhotoForSystemResource($default);