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);
78 if (!empty($parameters['customsize'])) {
79 $customsize = intval($parameters['customsize']);
80 $uid = pathinfo($parameters['name'], PATHINFO_FILENAME);
81 $photo = self::getAvatar($uid, $parameters['type'], $customsize);
82 $square_resize = !in_array($parameters['type'], ['media', 'preview']);
83 } elseif (!empty($parameters['type'])) {
84 $uid = pathinfo($parameters['name'], PATHINFO_FILENAME);
85 $photo = self::getAvatar($uid, $parameters['type'], Proxy::PIXEL_SMALL);
86 } elseif (!empty($parameters['name'])) {
87 $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
89 if (substr($photoid, -2, 1) == "-") {
90 $scale = intval(substr($photoid, -1, 1));
91 $photoid = substr($photoid, 0, -2);
93 $photo = MPhoto::getPhoto($photoid, $scale);
94 if ($photo === false) {
95 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
99 $fetch = microtime(true) - $stamp;
101 if ($photo === false) {
102 throw new HTTPException\NotFoundException();
105 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
107 $stamp = microtime(true);
109 $imgdata = MPhoto::getImageDataForPhoto($photo);
110 if (empty($imgdata)) {
111 throw new HTTPException\NotFoundException();
114 // The mimetype for an external or system resource can only be known reliably after it had been fetched
115 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
116 $mimetype = Images::getMimeTypeByData($imgdata);
117 if (!empty($mimetype)) {
118 $photo['type'] = $mimetype;
122 $data = microtime(true) - $stamp;
124 if (empty($imgdata)) {
125 Logger::warning('Invalid photo', ['id' => $photo['id']]);
126 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
127 $reference = json_decode($photo['backend-ref'], true);
128 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
130 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
132 throw new HTTPException\InternalServerErrorException($error);
135 // if customsize is set and image is not a gif, resize it
136 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
137 $img = new Image($imgdata, $photo['type']);
138 $img->scaleToSquare($customsize);
139 $imgdata = $img->asString();
140 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
141 $img = new Image($imgdata, $photo['type']);
142 $img->scaleDown($customsize);
143 $imgdata = $img->asString();
146 if (function_exists("header_remove")) {
147 header_remove("Pragma");
148 header_remove("pragma");
151 header("Content-type: " . $photo['type']);
153 $stamp = microtime(true);
155 // it is a private photo that they have no permission to view.
156 // tell the browser not to cache it, in case they authenticate
157 // and subsequently have permission to see it
158 header("Cache-Control: no-store, no-cache, must-revalidate");
160 $md5 = $photo['hash'] ?: md5($imgdata);
161 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
162 header("Etag: \"{$md5}\"");
163 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
164 header("Cache-Control: max-age=31536000");
166 $checksum = microtime(true) - $stamp;
168 $stamp = microtime(true);
170 $output = microtime(true) - $stamp;
172 $total = microtime(true) - $totalstamp;
173 $rest = $total - ($fetch + $data + $checksum + $output);
175 if (!is_null($scale) && ($scale < 4)) {
176 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
177 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
178 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
179 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
185 private static function getAvatar(int $uid, $type, $customsize)
189 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $uid]);
193 $url = $media['preview'];
195 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
196 $url = $media['url'];
203 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
204 return MPhoto::getPhoto($matches[1], $matches[2]);
207 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
209 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $uid, 'type' => Post\Media::IMAGE]);
214 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
215 return MPhoto::getPhoto($matches[1], $matches[2]);
218 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
220 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $uid]);
225 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
227 $contact = Contact::getById($uid, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
228 if (empty($contact)) {
231 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
232 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
234 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
235 // Fetch photo directly
236 $resourceid = MPhoto::ridFromURI($contact['photo']);
237 if (!empty($resourceid)) {
238 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
239 if (!empty($photo)) {
243 // We continue with the avatar link when the photo link is invalid
244 $url = $contact['avatar'];
245 } elseif (!empty($contact['avatar'])) {
246 $url = $contact['avatar'];
247 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
248 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
249 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
250 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
252 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
254 return MPhoto::createPhotoForExternalResource($url);
256 $contact = Contact::getById($uid, ['uid', 'url', 'header']);
257 if (empty($contact)) {
260 If (($contact['uid'] != 0) && empty($contact['header'])) {
261 $contact = Contact::getByURL($contact['url'], false, ['header']);
263 if (!empty($contact['header'])) {
264 $url = $contact['header'];
266 $url = DI::baseUrl() . '/images/blank.png';
268 return MPhoto::createPhotoForExternalResource($url);
281 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $uid, "profile" => 1]);
283 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]) ?: [];
288 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
291 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
295 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
298 $parts = parse_url($default);
299 if (!empty($parts['scheme']) || !empty($parts['host'])) {
300 $photo = MPhoto::createPhotoForExternalResource($default);
302 $photo = MPhoto::createPhotoForSystemResource($default);