]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Merge pull request #12630 from annando/diaspora-item
[friendica.git] / src / Module / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Core\Protocol;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Photo as MPhoto;
31 use Friendica\Model\Post;
32 use Friendica\Model\Profile;
33 use Friendica\Core\Storage\Type\ExternalResource;
34 use Friendica\Core\Storage\Type\SystemResource;
35 use Friendica\Core\System;
36 use Friendica\Core\Worker;
37 use Friendica\Model\User;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Network\HTTPException\NotModifiedException;
42 use Friendica\Object\Image;
43 use Friendica\Util\Images;
44 use Friendica\Util\Network;
45 use Friendica\Util\ParseUrl;
46 use Friendica\Util\Proxy;
47 use Friendica\Worker\UpdateContact;
48
49 /**
50  * Photo Module
51  */
52 class Photo extends BaseModule
53 {
54         /**
55          * Module initializer
56          *
57          * Fetch a photo or an avatar, in optional size, check for permissions and
58          * return the image
59          */
60         protected function rawContent(array $request = [])
61         {
62                 $totalstamp = microtime(true);
63
64                 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
65                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
66                         if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
67                                 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
68                         }
69                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
70                         header('Cache-Control: max-age=31536000');
71                         if (function_exists('header_remove')) {
72                                 header_remove('Last-Modified');
73                                 header_remove('Expires');
74                                 header_remove('Cache-Control');
75                         }
76                         throw new NotModifiedException();
77                 }
78
79                 Profile::addVisitorCookieForHTTPSigner();
80
81                 $customsize = 0;
82                 $square_resize = true;
83                 $scale = null;
84                 $stamp = microtime(true);
85                 // User avatar
86                 if (!empty($this->parameters['type'])) {
87                         if (!empty($this->parameters['customsize'])) {
88                                 $customsize = intval($this->parameters['customsize']);
89                                 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
90                         }
91
92                         if (!empty($this->parameters['guid'])) {
93                                 $guid = $this->parameters['guid'];
94                                 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
95                                 if (empty($account)) {
96                                         throw new HTTPException\NotFoundException();
97                                 }
98
99                                 $id = $account['id'];
100                         }
101
102                         // Contact Id Fallback, to remove after version 2021.12
103                         if (isset($this->parameters['contact_id'])) {
104                                 $id = intval($this->parameters['contact_id']);
105                         }
106
107                         if (!empty($this->parameters['nickname_ext'])) {
108                                 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
109                                 $user = User::getByNickname($nickname, ['uid']);
110                                 if (empty($user)) {
111                                         throw new HTTPException\NotFoundException();
112                                 }
113
114                                 $id = $user['uid'];
115                         }
116
117                         // User Id Fallback, to remove after version 2021.12
118                         if (!empty($this->parameters['uid_ext'])) {
119                                 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
120                         }
121
122                         // Please refactor this for the love of everything that's good
123                         if (isset($this->parameters['id'])) {
124                                 $id = $this->parameters['id'];
125                         }
126
127                         if (empty($id)) {
128                                 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
129                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
130                         }
131
132                         $photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
133                 } else {
134                         $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
135                         $scale = 0;
136                         if (substr($photoid, -2, 1) == '-') {
137                                 $scale = intval(substr($photoid, -1, 1));
138                                 $photoid = substr($photoid, 0, -2);
139                         }
140
141                         if (!empty($this->parameters['size'])) {
142                                 switch ($this->parameters['size']) {
143                                         case 'thumb_small':
144                                                 $scale = 2;
145                                                 break;
146                                         case 'scaled_full':
147                                                 $scale = 1;
148                                                 break;
149                                         }
150                         }
151
152                         $photo = MPhoto::getPhoto($photoid, $scale);
153                         if ($photo === false) {
154                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
155                         }
156                 }
157
158                 $fetch = microtime(true) - $stamp;
159
160                 if ($photo === false) {
161                         throw new HTTPException\NotFoundException();
162                 }
163
164                 $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
165
166                 $stamp = microtime(true);
167
168                 $imgdata = MPhoto::getImageDataForPhoto($photo);
169                 if (empty($imgdata) && empty($photo['blurhash'])) {
170                         throw new HTTPException\NotFoundException();
171                 } elseif (empty($imgdata) && !empty($photo['blurhash'])) {
172                         $image = New Image('', 'image/png');
173                         $image->getFromBlurHash($photo['blurhash'], $photo['width'], $photo['height']);
174                         $imgdata = $image->asString();
175                 }
176
177                 // The mimetype for an external or system resource can only be known reliably after it had been fetched
178                 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
179                         $mimetype = Images::getMimeTypeByData($imgdata);
180                         if (!empty($mimetype)) {
181                                 $photo['type'] = $mimetype;
182                         }
183                 }
184
185                 $data = microtime(true) - $stamp;
186
187                 if (empty($imgdata)) {
188                         Logger::warning('Invalid photo', ['id' => $photo['id']]);
189                         if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
190                                 $reference = json_decode($photo['backend-ref'], true);
191                                 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
192                         } else {
193                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
194                         }
195                         throw new HTTPException\InternalServerErrorException($error);
196                 }
197
198                 if (!empty($request['static'])) {
199                         $img = new Image($imgdata, $photo['type']);
200                         $img->toStatic();
201                         $imgdata = $img->asString();
202                 }
203
204                 // if customsize is set and image is not a gif, resize it
205                 if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
206                         $img = new Image($imgdata, $photo['type']);
207                         $img->scaleToSquare($customsize);
208                         $imgdata = $img->asString();
209                 } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
210                         $img = new Image($imgdata, $photo['type']);
211                         $img->scaleDown($customsize);
212                         $imgdata = $img->asString();
213                 }
214
215                 if (function_exists('header_remove')) {
216                         header_remove('Pragma');
217                         header_remove('pragma');
218                 }
219
220                 header('Content-type: ' . $photo['type']);
221
222                 $stamp = microtime(true);
223                 if (!$cacheable) {
224                         // it is a private photo that they have no permission to view.
225                         // tell the browser not to cache it, in case they authenticate
226                         // and subsequently have permission to see it
227                         header('Cache-Control: no-store, no-cache, must-revalidate');
228                 } else {
229                         $md5 = $photo['hash'] ?: md5($imgdata);
230                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
231                         header("Etag: \"{$md5}\"");
232                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
233                         header('Cache-Control: max-age=31536000');
234                 }
235                 $checksum = microtime(true) - $stamp;
236
237                 $stamp = microtime(true);
238                 echo $imgdata;
239                 $output = microtime(true) - $stamp;
240
241                 $total = microtime(true) - $totalstamp;
242                 $rest = $total - ($fetch + $data + $checksum + $output);
243
244                 if (!is_null($scale) && ($scale < 4)) {
245                         Logger::debug('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
246                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
247                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
248                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
249                 }
250
251                 System::exit();
252         }
253
254         /**
255          * Fetches photo record by given id number, type and custom size
256          *
257          * @param int $id Photo id
258          * @param string $type Photo type
259          * @param int $customsize Custom size (?)
260          * @return array|bool Array on success, false on error
261          */
262         private static function getPhotoById(int $id, string $type, int $customsize)
263         {
264                 switch($type) {
265                         case 'preview':
266                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'preview-height', 'preview-width', 'height', 'width', 'mimetype', 'type', 'uri-id', 'blurhash'], ['id' => $id]);
267                                 if (empty($media)) {
268                                         return false;
269                                 }
270                                 $url    = $media['preview'];
271                                 $width  = $media['preview-width'];
272                                 $height = $media['preview-height'];
273
274                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
275                                         $url    = $media['url'];
276                                         $width  = $media['width'];
277                                         $height = $media['height'];
278                                 }
279
280                                 if (empty($url)) {
281                                         return false;
282                                 }
283
284                                 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
285                                         return MPhoto::getPhoto($matches[1], $matches[2]);
286                                 }
287
288                                 return MPhoto::createPhotoForExternalResource($url, (int)DI::userSession()->getLocalUserId(), $media['mimetype'] ?? '', $media['blurhash'], $width, $height);
289                         case 'media':
290                                 $media = DBA::selectFirst('post-media', ['url', 'height', 'width', 'mimetype', 'uri-id', 'blurhash'], ['id' => $id, 'type' => Post\Media::IMAGE]);
291                                 if (empty($media)) {
292                                         return false;
293                                 }
294
295                                 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
296                                         return MPhoto::getPhoto($matches[1], $matches[2]);
297                                 }
298
299                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)DI::userSession()->getLocalUserId(), $media['mimetype'], $media['blurhash'], $media['width'], $media['height']);
300                         case 'link':
301                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype', 'blurhash', 'width', 'height'], ['id' => $id]);
302                                 if (empty($link)) {
303                                         return false;
304                                 }
305
306                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0);
307                         case 'contact':
308                                 $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated'];
309                                 $contact = Contact::getById($id, $fields);
310                                 if (empty($contact)) {
311                                         return false;
312                                 }
313
314                                 // For local users directly use the photo record that is marked as the profile
315                                 if (Network::isLocalLink($contact['url'])) {
316                                         $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
317                                         if (!empty($contact)) {
318                                                 if ($customsize <= Proxy::PIXEL_MICRO) {
319                                                         $scale = 6;
320                                                 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
321                                                         $scale = 5;
322                                                 } else {
323                                                         $scale = 4;
324                                                 }
325                                                 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
326                                                 if (!empty($photo)) {
327                                                         return $photo;
328                                                 }
329                                         }
330                                 }
331
332                                 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
333                                         $contact = Contact::getByURL($contact['url'], false, $fields);
334                                 }
335
336                                 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
337                                         // Fetch photo directly
338                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
339                                         if (!empty($resourceid)) {
340                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
341                                                 if (!empty($photo)) {
342                                                         return $photo;
343                                                 } else {
344                                                         $url = $contact['avatar'];
345                                                 }
346                                         } else {
347                                                 $url = $contact['photo'];
348                                         }
349                                 } elseif (!empty($contact['avatar'])) {
350                                         $url = $contact['avatar'];
351                                 }
352                                 $mimetext = '';
353                                 if (!empty($url)) {
354                                         $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
355                                         if (!empty($mime)) {
356                                                 $mimetext = $mime[0] . '/' . $mime[1];
357                                         } else {
358                                                 // Only update federated accounts that hadn't failed before and hadn't been updated recently
359                                                 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
360                                                         && ((time() - strtotime($contact['updated']) > 86400));
361                                                 if ($update) {
362                                                         $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
363                                                         $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
364                                                         Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
365                                                 }
366                                                 if ($update) {
367                                                         try {
368                                                                 UpdateContact::add(Worker::PRIORITY_LOW, $id);
369                                                                 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
370                                                         } catch (\InvalidArgumentException $e) {
371                                                                 Logger::notice($e->getMessage(), ['id' => $id, 'contact' => $contact]);
372                                                         }
373                                                 } else {
374                                                         Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
375                                                 }
376                                         }
377                                         if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
378                                                 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
379                                                 $mimetext = '';
380                                         } if (!empty($mimetext)) {
381                                                 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
382                                         }
383                                 }
384                                 if (empty($mimetext) && !empty($contact['blurhash'])) {
385                                         $image = New Image('', 'image/png');
386                                         $image->getFromBlurHash($contact['blurhash'], $customsize, $customsize);
387                                         return MPhoto::createPhotoForImageData($image->asString());
388                                 } elseif (empty($mimetext)) {
389                                         if ($customsize <= Proxy::PIXEL_MICRO) {
390                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_MICRO);
391                                         } elseif ($customsize <= Proxy::PIXEL_THUMB) {
392                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_THUMB);
393                                         } else {
394                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_SMALL);
395                                         }
396                                 }
397                                 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext, $contact['blurhash'] ?? null, $customsize, $customsize);
398                         case 'header':
399                                 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
400                                 $contact = Contact::getById($id, $fields);
401                                 if (empty($contact)) {
402                                         return false;
403                                 }
404                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
405                                         $contact = Contact::getByURL($contact['url'], false, $fields);
406                                 }
407                                 if (!empty($contact['header'])) {
408                                         $url = $contact['header'];
409                                 } else {
410                                         $url = Contact::getDefaultHeader($contact);
411                                 }
412                                 return MPhoto::createPhotoForExternalResource($url);
413                         case 'banner':
414                                 $photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
415                                 if (!empty($photo)) {
416                                         return $photo;
417                                 }
418                                 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
419                         case 'profile':
420                         case 'custom':
421                                 $scale = 4;
422                                 break;
423                         case 'micro':
424                                 $scale = 6;
425                                 break;
426                         case 'avatar':
427                         default:
428                                 $scale = 5;
429                 }
430
431                 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
432                 if (empty($photo)) {
433                         $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
434
435                         switch($type) {
436                                 case 'profile':
437                                 case 'custom':
438                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
439                                         break;
440                                 case 'micro':
441                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
442                                         break;
443                                 case 'avatar':
444                                 default:
445                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
446                         }
447
448                         $parts = parse_url($default);
449                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
450                                 $photo = MPhoto::createPhotoForExternalResource($default);
451                         } else {
452                                 $photo = MPhoto::createPhotoForSystemResource($default);
453                         }
454                 }
455                 return $photo;
456         }
457 }