]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Merge pull request #10890 from xundeenergie/improve-links
[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['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();
90                                 }
91
92                                 $id = $account['id'];
93                         }
94
95                         // Contact Id Fallback, to remove after version 2021.12
96                         if (isset($parameters['contact_id'])) {
97                                 $id = intval($parameters['contact_id']);
98                         }
99
100                         if (!empty($parameters['nickname_ext'])) {
101                                 $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
102                                 $user = User::getByNickname($nickname, ['uid']);
103                                 if (empty($user)) {
104                                         throw new HTTPException\NotFoundException();
105                                 }
106
107                                 $id = $user['uid'];
108                         }
109
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));
113                         }
114
115                         // Please refactor this for the love of everything that's good
116                         if (isset($parameters['id'])) {
117                                 $id = $parameters['id'];
118                         }
119
120                         if (empty($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.'));
123                         }
124
125                         $photo = self::getPhotoByid($id, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
126                 } else {
127                         $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
128                         $scale = 0;
129                         if (substr($photoid, -2, 1) == "-") {
130                                 $scale = intval(substr($photoid, -1, 1));
131                                 $photoid = substr($photoid, 0, -2);
132                         }
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));
136                         }
137                 }
138
139                 $fetch = microtime(true) - $stamp;
140
141                 if ($photo === false) {
142                         throw new HTTPException\NotFoundException();
143                 }
144
145                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
146
147                 $stamp = microtime(true);
148
149                 $imgdata = MPhoto::getImageDataForPhoto($photo);
150                 if (empty($imgdata)) {
151                         throw new HTTPException\NotFoundException();
152                 }
153
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;
159                         }
160                 }
161
162                 $data = microtime(true) - $stamp;
163
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']);
169                         } else {
170                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
171                         }
172                         throw new HTTPException\InternalServerErrorException($error);
173                 }
174
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();
184                 }
185
186                 if (function_exists("header_remove")) {
187                         header_remove("Pragma");
188                         header_remove("pragma");
189                 }
190
191                 header("Content-type: " . $photo['type']);
192
193                 $stamp = microtime(true);
194                 if (!$cacheable) {
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");
199                 } else {
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");
205                 }
206                 $checksum = microtime(true) - $stamp;
207
208                 $stamp = microtime(true);
209                 echo $imgdata;
210                 $output = microtime(true) - $stamp;
211
212                 $total = microtime(true) - $totalstamp;
213                 $rest = $total - ($fetch + $data + $checksum + $output);
214
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)]);
220                 }
221
222                 exit();
223         }
224
225         private static function getPhotoByid(int $id, $type, $customsize)
226         {
227                 switch($type) {
228                         case "preview":
229                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
230                                 if (empty($media)) {
231                                         return false;
232                                 }
233                                 $url = $media['preview'];
234
235                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
236                                         $url = $media['url'];
237                                 }
238
239                                 if (empty($url)) {
240                                         return false;
241                                 }
242
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]);
245                                 }
246
247                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
248                         case "media":
249                                 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
250                                 if (empty($media)) {
251                                         return false;
252                                 }
253
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]);
256                                 }
257
258                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
259                         case "link":
260                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
261                                 if (empty($link)) {
262                                         return false;
263                                 }
264
265                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
266                         case "contact":
267                                 $contact = Contact::getById($id, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
268                                 if (empty($contact)) {
269                                         return false;
270                                 }
271                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
272                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
273                                 }
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)) {
280                                                         return $photo;
281                                                 }
282                                         }
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);
291                                 } else {
292                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
293                                 }
294                                 return MPhoto::createPhotoForExternalResource($url);
295                         case "header":
296                                 $contact = Contact::getById($id, ['uid', 'url', 'header']);
297                                 if (empty($contact)) {
298                                         return false;
299                                 }
300                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
301                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
302                                 }
303                                 if (!empty($contact['header'])) {
304                                         $url = $contact['header'];
305                                 } else {
306                                         $url = DI::baseUrl() . '/images/blank.png';
307                                 }
308                                 return MPhoto::createPhotoForExternalResource($url);
309                         case "profile":
310                         case "custom":
311                                 $scale = 4;
312                                 break;
313                         case "micro":
314                                 $scale = 6;
315                                 break;
316                         case "avatar":
317                         default:
318                                 $scale = 5;
319                 }
320
321                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
322                 if (empty($photo)) {
323                         $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
324
325                         switch($type) {
326                                 case "profile":
327                                 case "custom":
328                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
329                                         break;
330                                 case "micro":
331                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
332                                         break;
333                                 case "avatar":
334                                 default:
335                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
336                         }
337
338                         $parts = parse_url($default);
339                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
340                                 $photo = MPhoto::createPhotoForExternalResource($default);
341                         } else {
342                                 $photo = MPhoto::createPhotoForSystemResource($default);
343                         }
344                 }
345                 return $photo;
346         }
347 }