]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
[frio] Fix event time display
[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                         // Please refactor this for the love of everything that's good
101                         if (!empty($parameters['id'])) {
102                                 $uid = $parameters['id'];
103                         }
104
105                         $photo = self::getAvatar($uid, $parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
106                 } else {
107                         $photoid = pathinfo($parameters['name'], PATHINFO_FILENAME);
108                         $scale = 0;
109                         if (substr($photoid, -2, 1) == "-") {
110                                 $scale = intval(substr($photoid, -1, 1));
111                                 $photoid = substr($photoid, 0, -2);
112                         }
113                         $photo = MPhoto::getPhoto($photoid, $scale);
114                         if ($photo === false) {
115                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
116                         }
117                 }
118
119                 $fetch = microtime(true) - $stamp;
120
121                 if ($photo === false) {
122                         throw new HTTPException\NotFoundException();
123                 }
124
125                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
126
127                 $stamp = microtime(true);
128
129                 $imgdata = MPhoto::getImageDataForPhoto($photo);
130                 if (empty($imgdata)) {
131                         throw new HTTPException\NotFoundException();
132                 }
133
134                 // The mimetype for an external or system resource can only be known reliably after it had been fetched
135                 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
136                         $mimetype = Images::getMimeTypeByData($imgdata);
137                         if (!empty($mimetype)) {
138                                 $photo['type'] = $mimetype;
139                         }
140                 }
141
142                 $data = microtime(true) - $stamp;
143
144                 if (empty($imgdata)) {
145                         Logger::warning('Invalid photo', ['id' => $photo['id']]);
146                         if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
147                                 $reference = json_decode($photo['backend-ref'], true);
148                                 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
149                         } else {
150                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
151                         }
152                         throw new HTTPException\InternalServerErrorException($error);
153                 }
154
155                 // if customsize is set and image is not a gif, resize it
156                 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
157                         $img = new Image($imgdata, $photo['type']);
158                         $img->scaleToSquare($customsize);
159                         $imgdata = $img->asString();
160                 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
161                         $img = new Image($imgdata, $photo['type']);
162                         $img->scaleDown($customsize);
163                         $imgdata = $img->asString();
164                 }
165
166                 if (function_exists("header_remove")) {
167                         header_remove("Pragma");
168                         header_remove("pragma");
169                 }
170
171                 header("Content-type: " . $photo['type']);
172
173                 $stamp = microtime(true);
174                 if (!$cacheable) {
175                         // it is a private photo that they have no permission to view.
176                         // tell the browser not to cache it, in case they authenticate
177                         // and subsequently have permission to see it
178                         header("Cache-Control: no-store, no-cache, must-revalidate");
179                 } else {
180                         $md5 = $photo['hash'] ?: md5($imgdata);
181                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
182                         header("Etag: \"{$md5}\"");
183                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
184                         header("Cache-Control: max-age=31536000");
185                 }
186                 $checksum = microtime(true) - $stamp;
187
188                 $stamp = microtime(true);
189                 echo $imgdata;
190                 $output = microtime(true) - $stamp;
191
192                 $total = microtime(true) - $totalstamp;
193                 $rest = $total - ($fetch + $data + $checksum + $output);
194
195                 if (!is_null($scale) && ($scale < 4)) {
196                         Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
197                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
198                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
199                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
200                 }
201
202                 exit();
203         }
204
205         private static function getAvatar(int $uid, $type, $customsize)
206         {
207                 switch($type) {
208                         case "preview":
209                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $uid]);
210                                 if (empty($media)) {
211                                         return false;
212                                 }
213                                 $url = $media['preview'];
214
215                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
216                                         $url = $media['url'];
217                                 }
218
219                                 if (empty($url)) {
220                                         return false;
221                                 }
222
223                                 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
224                                         return MPhoto::getPhoto($matches[1], $matches[2]);
225                                 }
226                 
227                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
228                         case "media":
229                                 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $uid, 'type' => Post\Media::IMAGE]);
230                                 if (empty($media)) {
231                                         return false;
232                                 }
233
234                                 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
235                                         return MPhoto::getPhoto($matches[1], $matches[2]);
236                                 }
237
238                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
239                         case "link":
240                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $uid]);
241                                 if (empty($link)) {
242                                         return false;
243                                 }
244
245                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
246                         case "contact":
247                                 $contact = Contact::getById($uid, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
248                                 if (empty($contact)) {
249                                         return false;
250                                 }
251                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
252                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
253                                 }
254                                 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
255                                         // Fetch photo directly
256                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
257                                         if (!empty($resourceid)) {
258                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
259                                                 if (!empty($photo)) {
260                                                         return $photo;
261                                                 }
262                                         }
263                                         // We continue with the avatar link when the photo link is invalid
264                                         $url = $contact['avatar'];
265                                 } elseif (!empty($contact['avatar'])) {
266                                         $url = $contact['avatar'];
267                                 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
268                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
269                                 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
270                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
271                                 } else {
272                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
273                                 }
274                                 return MPhoto::createPhotoForExternalResource($url);
275                         case "header":
276                                 $contact = Contact::getById($uid, ['uid', 'url', 'header']);
277                                 if (empty($contact)) {
278                                         return false;
279                                 }
280                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
281                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
282                                 }
283                                 if (!empty($contact['header'])) {
284                                         $url = $contact['header'];
285                                 } else {
286                                         $url = DI::baseUrl() . '/images/blank.png';
287                                 }
288                                 return MPhoto::createPhotoForExternalResource($url);
289                         case "profile":
290                         case "custom":
291                                 $scale = 4;
292                                 break;
293                         case "micro":
294                                 $scale = 6;
295                                 break;
296                         case "avatar":
297                         default:
298                                 $scale = 5;
299                 }
300
301                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $uid, "profile" => 1]);
302                 if (empty($photo)) {
303                         $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]) ?: [];
304
305                         switch($type) {
306                                 case "profile":
307                                 case "custom":
308                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
309                                         break;
310                                 case "micro":
311                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
312                                         break;
313                                 case "avatar":
314                                 default:
315                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
316                         }
317
318                         $parts = parse_url($default);
319                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
320                                 $photo = MPhoto::createPhotoForExternalResource($default);
321                         } else {
322                                 $photo = MPhoto::createPhotoForSystemResource($default);
323                         }
324                 }
325                 return $photo;
326         }
327 }