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 = $parameters['guid'];
87 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
88 if (empty($account)) {
89 throw new HTTPException\NotFoundException();
95 // Contact Id Fallback, to remove after version 2021.12
96 if (isset($parameters['contact_id'])) {
97 $id = intval($parameters['contact_id']);
100 if (!empty($parameters['nickname_ext'])) {
101 $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
102 $user = User::getByNickname($nickname, ['uid']);
104 throw new HTTPException\NotFoundException();
110 // User Id Fallback, to remove after version 2021.12
111 if (!empty($parameters['uid_ext'])) {
112 $id = intval(pathinfo($parameters['uid_ext'], PATHINFO_FILENAME));
115 // Please refactor this for the love of everything that's good
116 if (isset($parameters['id'])) {
117 $id = $parameters['id'];
121 Logger::notice('No picture id was detected', ['parameters' => $parameters, 'query' => DI::args()->getQueryString()]);
122 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
125 $photo = self::getPhotoByid($id, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
127 $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
129 if (substr($photoid, -2, 1) == "-") {
130 $scale = intval(substr($photoid, -1, 1));
131 $photoid = substr($photoid, 0, -2);
133 $photo = MPhoto::getPhoto($photoid, $scale);
134 if ($photo === false) {
135 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
139 $fetch = microtime(true) - $stamp;
141 if ($photo === false) {
142 throw new HTTPException\NotFoundException();
145 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
147 $stamp = microtime(true);
149 $imgdata = MPhoto::getImageDataForPhoto($photo);
150 if (empty($imgdata)) {
151 throw new HTTPException\NotFoundException();
154 // The mimetype for an external or system resource can only be known reliably after it had been fetched
155 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
156 $mimetype = Images::getMimeTypeByData($imgdata);
157 if (!empty($mimetype)) {
158 $photo['type'] = $mimetype;
162 $data = microtime(true) - $stamp;
164 if (empty($imgdata)) {
165 Logger::warning('Invalid photo', ['id' => $photo['id']]);
166 if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
167 $reference = json_decode($photo['backend-ref'], true);
168 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
170 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
172 throw new HTTPException\InternalServerErrorException($error);
175 // if customsize is set and image is not a gif, resize it
176 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
177 $img = new Image($imgdata, $photo['type']);
178 $img->scaleToSquare($customsize);
179 $imgdata = $img->asString();
180 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
181 $img = new Image($imgdata, $photo['type']);
182 $img->scaleDown($customsize);
183 $imgdata = $img->asString();
186 if (function_exists("header_remove")) {
187 header_remove("Pragma");
188 header_remove("pragma");
191 header("Content-type: " . $photo['type']);
193 $stamp = microtime(true);
195 // it is a private photo that they have no permission to view.
196 // tell the browser not to cache it, in case they authenticate
197 // and subsequently have permission to see it
198 header("Cache-Control: no-store, no-cache, must-revalidate");
200 $md5 = $photo['hash'] ?: md5($imgdata);
201 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
202 header("Etag: \"{$md5}\"");
203 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
204 header("Cache-Control: max-age=31536000");
206 $checksum = microtime(true) - $stamp;
208 $stamp = microtime(true);
210 $output = microtime(true) - $stamp;
212 $total = microtime(true) - $totalstamp;
213 $rest = $total - ($fetch + $data + $checksum + $output);
215 if (!is_null($scale) && ($scale < 4)) {
216 Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
217 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
218 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
219 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
225 private static function getPhotoByid(int $id, $type, $customsize)
229 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
233 $url = $media['preview'];
235 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
236 $url = $media['url'];
243 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
244 return MPhoto::getPhoto($matches[1], $matches[2]);
247 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
249 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
254 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
255 return MPhoto::getPhoto($matches[1], $matches[2]);
258 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
260 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
265 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
267 $contact = Contact::getById($id, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
268 if (empty($contact)) {
271 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
272 $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
274 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
275 // Fetch photo directly
276 $resourceid = MPhoto::ridFromURI($contact['photo']);
277 if (!empty($resourceid)) {
278 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
279 if (!empty($photo)) {
283 // We continue with the avatar link when the photo link is invalid
284 $url = $contact['avatar'];
285 } elseif (!empty($contact['avatar'])) {
286 $url = $contact['avatar'];
287 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
288 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
289 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
290 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
292 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
294 return MPhoto::createPhotoForExternalResource($url);
296 $contact = Contact::getById($id, ['uid', 'url', 'header']);
297 if (empty($contact)) {
300 If (($contact['uid'] != 0) && empty($contact['header'])) {
301 $contact = Contact::getByURL($contact['url'], false, ['header']);
303 if (!empty($contact['header'])) {
304 $url = $contact['header'];
306 $url = DI::baseUrl() . '/images/blank.png';
308 return MPhoto::createPhotoForExternalResource($url);
321 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
323 $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
328 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
331 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
335 $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
338 $parts = parse_url($default);
339 if (!empty($parts['scheme']) || !empty($parts['host'])) {
340 $photo = MPhoto::createPhotoForExternalResource($default);
342 $photo = MPhoto::createPhotoForSystemResource($default);