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['nickname_ext'])) {
86 $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
87 $user = User::getByNickname($nickname, ['uid']);
89 throw new HTTPException\NotFoundException();
95 // User Id Fallback, to remove after version 2021.12
96 if (!empty($parameters['uid_ext'])) {
97 $uid = intval(pathinfo($parameters['uid_ext'], PATHINFO_FILENAME));
100 $photo = self::getAvatar($uid, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
102 $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
104 if (substr($photoid, -2, 1) == "-") {
105 $scale = intval(substr($photoid, -1, 1));
106 $photoid = substr($photoid, 0, -2);
108 $photo = MPhoto::getPhoto($photoid, $scale);
109 if ($photo === false) {
110 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
114 $fetch = microtime(true) - $stamp;
116 if ($photo === false) {
117 throw new HTTPException\NotFoundException();
120 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
122 $stamp = microtime(true);
124 $imgdata = MPhoto::getImageDataForPhoto($photo);
125 if (empty($imgdata)) {
126 throw new HTTPException\NotFoundException();
129 // The mimetype for an external or system resource can only be known reliably after it had been fetched
130 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
131 $mimetype = Images::getMimeTypeByData($imgdata);
132 if (!empty($mimetype)) {
133 $photo['type'] = $mimetype;
137 $data = microtime(true) - $stamp;
139 if (empty($imgdata)) {
140 Logger::warning('Invalid photo', ['id' => $photo['id']]);
141 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
142 $reference = json_decode($photo['backend-ref'], true);
143 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
145 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
147 throw new HTTPException\InternalServerErrorException($error);
150 // if customsize is set and image is not a gif, resize it
151 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
152 $img = new Image($imgdata, $photo['type']);
153 $img->scaleToSquare($customsize);
154 $imgdata = $img->asString();
155 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
156 $img = new Image($imgdata, $photo['type']);
157 $img->scaleDown($customsize);
158 $imgdata = $img->asString();
161 if (function_exists("header_remove")) {
162 header_remove("Pragma");
163 header_remove("pragma");
166 header("Content-type: " . $photo['type']);
168 $stamp = microtime(true);
170 // it is a private photo that they have no permission to view.
171 // tell the browser not to cache it, in case they authenticate
172 // and subsequently have permission to see it
173 header("Cache-Control: no-store, no-cache, must-revalidate");
175 $md5 = $photo['hash'] ?: md5($imgdata);
176 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
177 header("Etag: \"{$md5}\"");
178 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
179 header("Cache-Control: max-age=31536000");
181 $checksum = microtime(true) - $stamp;
183 $stamp = microtime(true);
185 $output = microtime(true) - $stamp;
187 $total = microtime(true) - $totalstamp;
188 $rest = $total - ($fetch + $data + $checksum + $output);
190 if (!is_null($scale) && ($scale < 4)) {
191 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
192 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
193 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
194 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
200 private static function getAvatar(int $uid, $type, $customsize)
204 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $uid]);
208 $url = $media['preview'];
210 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
211 $url = $media['url'];
218 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
219 return MPhoto::getPhoto($matches[1], $matches[2]);
222 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
224 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $uid, 'type' => Post\Media::IMAGE]);
229 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
230 return MPhoto::getPhoto($matches[1], $matches[2]);
233 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
235 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $uid]);
240 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
242 $contact = Contact::getById($uid, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
243 if (empty($contact)) {
246 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
247 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
249 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
250 // Fetch photo directly
251 $resourceid = MPhoto::ridFromURI($contact['photo']);
252 if (!empty($resourceid)) {
253 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
254 if (!empty($photo)) {
258 // We continue with the avatar link when the photo link is invalid
259 $url = $contact['avatar'];
260 } elseif (!empty($contact['avatar'])) {
261 $url = $contact['avatar'];
262 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
263 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
264 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
265 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
267 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
269 return MPhoto::createPhotoForExternalResource($url);
271 $contact = Contact::getById($uid, ['uid', 'url', 'header']);
272 if (empty($contact)) {
275 If (($contact['uid'] != 0) && empty($contact['header'])) {
276 $contact = Contact::getByURL($contact['url'], false, ['header']);
278 if (!empty($contact['header'])) {
279 $url = $contact['header'];
281 $url = DI::baseUrl() . '/images/blank.png';
283 return MPhoto::createPhotoForExternalResource($url);
296 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $uid, "profile" => 1]);
298 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]) ?: [];
303 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
306 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
310 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
313 $parts = parse_url($default);
314 if (!empty($parts['scheme']) || !empty($parts['host'])) {
315 $photo = MPhoto::createPhotoForExternalResource($default);
317 $photo = MPhoto::createPhotoForSystemResource($default);