]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Merge pull request #10808 from MrPetovan/task/10725-user-avatar
[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                                 $nickname = pathinfo($parameters['nickname_ext'], PATHINFO_FILENAME);
87                                 $user = User::getByNickname($nickname, ['uid']);
88                                 if (empty($user)) {
89                                         throw new HTTPException\NotFoundException();
90                                 }
91
92                                 $uid = $user['uid'];
93                         }
94
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));
98                         }
99
100                         $photo = self::getAvatar($uid, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
101                 } else {
102                         $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
103                         $scale = 0;
104                         if (substr($photoid, -2, 1) == "-") {
105                                 $scale = intval(substr($photoid, -1, 1));
106                                 $photoid = substr($photoid, 0, -2);
107                         }
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));
111                         }
112                 }
113
114                 $fetch = microtime(true) - $stamp;
115
116                 if ($photo === false) {
117                         throw new HTTPException\NotFoundException();
118                 }
119
120                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
121
122                 $stamp = microtime(true);
123
124                 $imgdata = MPhoto::getImageDataForPhoto($photo);
125                 if (empty($imgdata)) {
126                         throw new HTTPException\NotFoundException();
127                 }
128
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;
134                         }
135                 }
136
137                 $data = microtime(true) - $stamp;
138
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']);
144                         } else {
145                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
146                         }
147                         throw new HTTPException\InternalServerErrorException($error);
148                 }
149
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();
159                 }
160
161                 if (function_exists("header_remove")) {
162                         header_remove("Pragma");
163                         header_remove("pragma");
164                 }
165
166                 header("Content-type: " . $photo['type']);
167
168                 $stamp = microtime(true);
169                 if (!$cacheable) {
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");
174                 } else {
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");
180                 }
181                 $checksum = microtime(true) - $stamp;
182
183                 $stamp = microtime(true);
184                 echo $imgdata;
185                 $output = microtime(true) - $stamp;
186
187                 $total = microtime(true) - $totalstamp;
188                 $rest = $total - ($fetch + $data + $checksum + $output);
189
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)]);
195                 }
196
197                 exit();
198         }
199
200         private static function getAvatar(int $uid, $type, $customsize)
201         {
202                 switch($type) {
203                         case "preview":
204                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $uid]);
205                                 if (empty($media)) {
206                                         return false;
207                                 }
208                                 $url = $media['preview'];
209
210                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
211                                         $url = $media['url'];
212                                 }
213
214                                 if (empty($url)) {
215                                         return false;
216                                 }
217
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]);
220                                 }
221                 
222                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
223                         case "media":
224                                 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $uid, 'type' => Post\Media::IMAGE]);
225                                 if (empty($media)) {
226                                         return false;
227                                 }
228
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]);
231                                 }
232
233                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
234                         case "link":
235                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $uid]);
236                                 if (empty($link)) {
237                                         return false;
238                                 }
239
240                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
241                         case "contact":
242                                 $contact = Contact::getById($uid, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
243                                 if (empty($contact)) {
244                                         return false;
245                                 }
246                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
247                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
248                                 }
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)) {
255                                                         return $photo;
256                                                 }
257                                         }
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);
266                                 } else {
267                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
268                                 }
269                                 return MPhoto::createPhotoForExternalResource($url);
270                         case "header":
271                                 $contact = Contact::getById($uid, ['uid', 'url', 'header']);
272                                 if (empty($contact)) {
273                                         return false;
274                                 }
275                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
276                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
277                                 }
278                                 if (!empty($contact['header'])) {
279                                         $url = $contact['header'];
280                                 } else {
281                                         $url = DI::baseUrl() . '/images/blank.png';
282                                 }
283                                 return MPhoto::createPhotoForExternalResource($url);
284                         case "profile":
285                         case "custom":
286                                 $scale = 4;
287                                 break;
288                         case "micro":
289                                 $scale = 6;
290                                 break;
291                         case "avatar":
292                         default:
293                                 $scale = 5;
294                 }
295
296                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $uid, "profile" => 1]);
297                 if (empty($photo)) {
298                         $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]) ?: [];
299
300                         switch($type) {
301                                 case "profile":
302                                 case "custom":
303                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
304                                         break;
305                                 case "micro":
306                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
307                                         break;
308                                 case "avatar":
309                                 default:
310                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
311                         }
312
313                         $parts = parse_url($default);
314                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
315                                 $photo = MPhoto::createPhotoForExternalResource($default);
316                         } else {
317                                 $photo = MPhoto::createPhotoForSystemResource($default);
318                         }
319                 }
320                 return $photo;
321         }
322 }