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