]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Merge remote-tracking branch 'upstream/develop' into photo-guid
[friendica.git] / src / Module / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
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;
40
41 /**
42  * Photo Module
43  */
44 class Photo extends BaseModule
45 {
46         /**
47          * Module initializer
48          *
49          * Fetch a photo or an avatar, in optional size, check for permissions and
50          * return the image
51          */
52         public static function rawContent(array $parameters = [])
53         {
54                 $totalstamp = microtime(true);
55
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"]);
61                         }
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");
68                         }
69                         exit;
70                 }
71
72                 Profile::addVisitorCookieForHTTPSigner();
73
74                 $customsize = 0;
75                 $square_resize = true;
76                 $scale = null;
77                 $stamp = microtime(true);
78                 // User avatar
79                 if (!empty($parameters['type'])) {
80                         if (!empty($parameters['customsize'])) {
81                                 $customsize = intval($parameters['customsize']);
82                                 $square_resize = !in_array($parameters['type'], ['media', 'preview']);
83                         }
84
85                         if (!empty($parameters['nickname_ext'])) {
86                                 if (in_array($parameters['type'], ['contact', 'header'])) {
87                                         $guid = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
88                                         $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
89                                         if (empty($account)) {
90                                                 throw new HTTPException\NotFoundException();
91                                         }
92
93                                         $id = $account['id'];
94                                 } else {
95                                         $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
96                                         $user = User::getByNickname($nickname, ['uid']);
97                                         if (empty($user)) {
98                                                 throw new HTTPException\NotFoundException();
99                                         }
100
101                                         $id = $user['uid'];
102                                 }
103                         }
104
105                         // User Id Fallback, to remove after version 2021.12
106                         if (!empty($parameters['uid_ext'])) {
107                                 $id = intval(pathinfo($parameters['uid_ext'], PATHINFO_FILENAME));
108                         }
109
110                         // Please refactor this for the love of everything that's good
111                         if (isset($parameters['id'])) {
112                                 $id = $parameters['id'];
113                         }
114
115                         if (empty($id)) {
116                                 Logger::notice('No picture id was detected', ['parameters' => $parameters]);
117                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
118                         }
119
120                         $photo = self::getPhotoByid($id, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
121                 } else {
122                         $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
123                         $scale = 0;
124                         if (substr($photoid, -2, 1) == "-") {
125                                 $scale = intval(substr($photoid, -1, 1));
126                                 $photoid = substr($photoid, 0, -2);
127                         }
128                         $photo = MPhoto::getPhoto($photoid, $scale);
129                         if ($photo === false) {
130                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
131                         }
132                 }
133
134                 $fetch = microtime(true) - $stamp;
135
136                 if ($photo === false) {
137                         throw new HTTPException\NotFoundException();
138                 }
139
140                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
141
142                 $stamp = microtime(true);
143
144                 $imgdata = MPhoto::getImageDataForPhoto($photo);
145                 if (empty($imgdata)) {
146                         throw new HTTPException\NotFoundException();
147                 }
148
149                 // The mimetype for an external or system resource can only be known reliably after it had been fetched
150                 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
151                         $mimetype = Images::getMimeTypeByData($imgdata);
152                         if (!empty($mimetype)) {
153                                 $photo['type'] = $mimetype;
154                         }
155                 }
156
157                 $data = microtime(true) - $stamp;
158
159                 if (empty($imgdata)) {
160                         Logger::warning('Invalid photo', ['id' => $photo['id']]);
161                         if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
162                                 $reference = json_decode($photo['backend-ref'], true);
163                                 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
164                         } else {
165                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
166                         }
167                         throw new HTTPException\InternalServerErrorException($error);
168                 }
169
170                 // if customsize is set and image is not a gif, resize it
171                 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
172                         $img = new Image($imgdata, $photo['type']);
173                         $img->scaleToSquare($customsize);
174                         $imgdata = $img->asString();
175                 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
176                         $img = new Image($imgdata, $photo['type']);
177                         $img->scaleDown($customsize);
178                         $imgdata = $img->asString();
179                 }
180
181                 if (function_exists("header_remove")) {
182                         header_remove("Pragma");
183                         header_remove("pragma");
184                 }
185
186                 header("Content-type: " . $photo['type']);
187
188                 $stamp = microtime(true);
189                 if (!$cacheable) {
190                         // it is a private photo that they have no permission to view.
191                         // tell the browser not to cache it, in case they authenticate
192                         // and subsequently have permission to see it
193                         header("Cache-Control: no-store, no-cache, must-revalidate");
194                 } else {
195                         $md5 = $photo['hash'] ?: md5($imgdata);
196                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
197                         header("Etag: \"{$md5}\"");
198                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
199                         header("Cache-Control: max-age=31536000");
200                 }
201                 $checksum = microtime(true) - $stamp;
202
203                 $stamp = microtime(true);
204                 echo $imgdata;
205                 $output = microtime(true) - $stamp;
206
207                 $total = microtime(true) - $totalstamp;
208                 $rest = $total - ($fetch + $data + $checksum + $output);
209
210                 if (!is_null($scale) && ($scale < 4)) {
211                         Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
212                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
213                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
214                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
215                 }
216
217                 exit();
218         }
219
220         private static function getPhotoByid(int $id, $type, $customsize)
221         {
222                 switch($type) {
223                         case "preview":
224                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
225                                 if (empty($media)) {
226                                         return false;
227                                 }
228                                 $url = $media['preview'];
229
230                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
231                                         $url = $media['url'];
232                                 }
233
234                                 if (empty($url)) {
235                                         return false;
236                                 }
237
238                                 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
239                                         return MPhoto::getPhoto($matches[1], $matches[2]);
240                                 }
241
242                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
243                         case "media":
244                                 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
245                                 if (empty($media)) {
246                                         return false;
247                                 }
248
249                                 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
250                                         return MPhoto::getPhoto($matches[1], $matches[2]);
251                                 }
252
253                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
254                         case "link":
255                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
256                                 if (empty($link)) {
257                                         return false;
258                                 }
259
260                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
261                         case "contact":
262                                 $contact = Contact::getById($id, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
263                                 if (empty($contact)) {
264                                         return false;
265                                 }
266                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
267                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
268                                 }
269                                 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
270                                         // Fetch photo directly
271                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
272                                         if (!empty($resourceid)) {
273                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
274                                                 if (!empty($photo)) {
275                                                         return $photo;
276                                                 }
277                                         }
278                                         // We continue with the avatar link when the photo link is invalid
279                                         $url = $contact['avatar'];
280                                 } elseif (!empty($contact['avatar'])) {
281                                         $url = $contact['avatar'];
282                                 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
283                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
284                                 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
285                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
286                                 } else {
287                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
288                                 }
289                                 return MPhoto::createPhotoForExternalResource($url);
290                         case "header":
291                                 $contact = Contact::getById($id, ['uid', 'url', 'header']);
292                                 if (empty($contact)) {
293                                         return false;
294                                 }
295                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
296                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
297                                 }
298                                 if (!empty($contact['header'])) {
299                                         $url = $contact['header'];
300                                 } else {
301                                         $url = DI::baseUrl() . '/images/blank.png';
302                                 }
303                                 return MPhoto::createPhotoForExternalResource($url);
304                         case "profile":
305                         case "custom":
306                                 $scale = 4;
307                                 break;
308                         case "micro":
309                                 $scale = 6;
310                                 break;
311                         case "avatar":
312                         default:
313                                 $scale = 5;
314                 }
315
316                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
317                 if (empty($photo)) {
318                         $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
319
320                         switch($type) {
321                                 case "profile":
322                                 case "custom":
323                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
324                                         break;
325                                 case "micro":
326                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
327                                         break;
328                                 case "avatar":
329                                 default:
330                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
331                         }
332
333                         $parts = parse_url($default);
334                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
335                                 $photo = MPhoto::createPhotoForExternalResource($default);
336                         } else {
337                                 $photo = MPhoto::createPhotoForSystemResource($default);
338                         }
339                 }
340                 return $photo;
341         }
342 }