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\Object\Image;
37 use Friendica\Util\Images;
38 use Friendica\Util\Network;
39 use Friendica\Util\Proxy;
44 class Photo extends BaseModule
49 * Fetch a photo or an avatar, in optional size, check for permissions and
52 public static function rawContent(array $parameters = [])
54 $totalstamp = microtime(true);
56 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
57 header("HTTP/1.1 304 Not Modified");
58 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
59 if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
60 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
62 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
63 header("Cache-Control: max-age=31536000");
64 if (function_exists("header_remove")) {
65 header_remove("Last-Modified");
66 header_remove("Expires");
67 header_remove("Cache-Control");
72 Profile::addVisitorCookieForHTTPSigner();
75 $square_resize = true;
77 $stamp = microtime(true);
79 if (!empty($parameters['type'])) {
80 if (!empty($parameters['customsize'])) {
81 $customsize = intval($parameters['customsize']);
82 $square_resize = !in_array($parameters['type'], ['media', 'preview']);
85 if (!empty($parameters['guid'])) {
86 $guid = pathinfo($parameters['guid'], PATHINFO_FILENAME);
87 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
88 if (empty($account)) {
89 throw new HTTPException\NotFoundException();
95 if (!empty($parameters['contact_id'])) {
96 $id = intval(pathinfo($parameters['contact_id'], PATHINFO_FILENAME));
99 if (!empty($parameters['nickname_ext'])) {
100 $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
101 $user = User::getByNickname($nickname, ['uid']);
103 throw new HTTPException\NotFoundException();
109 // User Id Fallback, to remove after version 2021.12
110 if (!empty($parameters['uid_ext'])) {
111 $id = intval(pathinfo($parameters['uid_ext'], PATHINFO_FILENAME));
114 // Please refactor this for the love of everything that's good
115 if (isset($parameters['id'])) {
116 $id = $parameters['id'];
120 Logger::notice('No picture id was detected', ['parameters' => $parameters, 'query' => DI::args()->getQueryString()]);
121 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
124 $photo = self::getPhotoByid($id, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
126 $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
128 if (substr($photoid, -2, 1) == "-") {
129 $scale = intval(substr($photoid, -1, 1));
130 $photoid = substr($photoid, 0, -2);
132 $photo = MPhoto::getPhoto($photoid, $scale);
133 if ($photo === false) {
134 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
138 $fetch = microtime(true) - $stamp;
140 if ($photo === false) {
141 throw new HTTPException\NotFoundException();
144 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
146 $stamp = microtime(true);
148 $imgdata = MPhoto::getImageDataForPhoto($photo);
149 if (empty($imgdata)) {
150 throw new HTTPException\NotFoundException();
153 // The mimetype for an external or system resource can only be known reliably after it had been fetched
154 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
155 $mimetype = Images::getMimeTypeByData($imgdata);
156 if (!empty($mimetype)) {
157 $photo['type'] = $mimetype;
161 $data = microtime(true) - $stamp;
163 if (empty($imgdata)) {
164 Logger::warning('Invalid photo', ['id' => $photo['id']]);
165 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
166 $reference = json_decode($photo['backend-ref'], true);
167 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
169 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
171 throw new HTTPException\InternalServerErrorException($error);
174 // if customsize is set and image is not a gif, resize it
175 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
176 $img = new Image($imgdata, $photo['type']);
177 $img->scaleToSquare($customsize);
178 $imgdata = $img->asString();
179 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
180 $img = new Image($imgdata, $photo['type']);
181 $img->scaleDown($customsize);
182 $imgdata = $img->asString();
185 if (function_exists("header_remove")) {
186 header_remove("Pragma");
187 header_remove("pragma");
190 header("Content-type: " . $photo['type']);
192 $stamp = microtime(true);
194 // it is a private photo that they have no permission to view.
195 // tell the browser not to cache it, in case they authenticate
196 // and subsequently have permission to see it
197 header("Cache-Control: no-store, no-cache, must-revalidate");
199 $md5 = $photo['hash'] ?: md5($imgdata);
200 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
201 header("Etag: \"{$md5}\"");
202 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
203 header("Cache-Control: max-age=31536000");
205 $checksum = microtime(true) - $stamp;
207 $stamp = microtime(true);
209 $output = microtime(true) - $stamp;
211 $total = microtime(true) - $totalstamp;
212 $rest = $total - ($fetch + $data + $checksum + $output);
214 if (!is_null($scale) && ($scale < 4)) {
215 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
216 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
217 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
218 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
224 private static function getPhotoByid(int $id, $type, $customsize)
228 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
232 $url = $media['preview'];
234 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
235 $url = $media['url'];
242 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
243 return MPhoto::getPhoto($matches[1], $matches[2]);
246 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
248 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
253 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
254 return MPhoto::getPhoto($matches[1], $matches[2]);
257 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
259 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
264 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
266 $contact = Contact::getById($id, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
267 if (empty($contact)) {
270 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
271 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
273 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
274 // Fetch photo directly
275 $resourceid = MPhoto::ridFromURI($contact['photo']);
276 if (!empty($resourceid)) {
277 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
278 if (!empty($photo)) {
282 // We continue with the avatar link when the photo link is invalid
283 $url = $contact['avatar'];
284 } elseif (!empty($contact['avatar'])) {
285 $url = $contact['avatar'];
286 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
287 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
288 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
289 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
291 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
293 return MPhoto::createPhotoForExternalResource($url);
295 $contact = Contact::getById($id, ['uid', 'url', 'header']);
296 if (empty($contact)) {
299 If (($contact['uid'] != 0) && empty($contact['header'])) {
300 $contact = Contact::getByURL($contact['url'], false, ['header']);
302 if (!empty($contact['header'])) {
303 $url = $contact['header'];
305 $url = DI::baseUrl() . '/images/blank.png';
307 return MPhoto::createPhotoForExternalResource($url);
320 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
322 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
327 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
330 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
334 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
337 $parts = parse_url($default);
338 if (!empty($parts['scheme']) || !empty($parts['host'])) {
339 $photo = MPhoto::createPhotoForExternalResource($default);
341 $photo = MPhoto::createPhotoForSystemResource($default);