]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Refactor IManageConfigValues interface
[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                         $photo = MPhoto::getPhoto($photoid, $scale);
141                         if ($photo === false) {
142                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
143                         }
144                 }
145
146                 $fetch = microtime(true) - $stamp;
147
148                 if ($photo === false) {
149                         throw new HTTPException\NotFoundException();
150                 }
151
152                 $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
153
154                 $stamp = microtime(true);
155
156                 $imgdata = MPhoto::getImageDataForPhoto($photo);
157                 if (empty($imgdata) && empty($photo['blurhash'])) {
158                         throw new HTTPException\NotFoundException();
159                 } elseif (empty($imgdata) && !empty($photo['blurhash'])) {
160                         $image = New Image('', 'image/png');
161                         $image->getFromBlurHash($photo['blurhash'], $photo['width'], $photo['height']);
162                         $imgdata = $image->asString();
163                 }
164
165                 // The mimetype for an external or system resource can only be known reliably after it had been fetched
166                 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
167                         $mimetype = Images::getMimeTypeByData($imgdata);
168                         if (!empty($mimetype)) {
169                                 $photo['type'] = $mimetype;
170                         }
171                 }
172
173                 $data = microtime(true) - $stamp;
174
175                 if (empty($imgdata)) {
176                         Logger::warning('Invalid photo', ['id' => $photo['id']]);
177                         if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
178                                 $reference = json_decode($photo['backend-ref'], true);
179                                 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
180                         } else {
181                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
182                         }
183                         throw new HTTPException\InternalServerErrorException($error);
184                 }
185
186                 if (!empty($request['static'])) {
187                         $img = new Image($imgdata, $photo['type']);
188                         $img->toStatic();
189                         $imgdata = $img->asString();
190                 }
191
192                 // if customsize is set and image is not a gif, resize it
193                 if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
194                         $img = new Image($imgdata, $photo['type']);
195                         $img->scaleToSquare($customsize);
196                         $imgdata = $img->asString();
197                 } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
198                         $img = new Image($imgdata, $photo['type']);
199                         $img->scaleDown($customsize);
200                         $imgdata = $img->asString();
201                 }
202
203                 if (function_exists('header_remove')) {
204                         header_remove('Pragma');
205                         header_remove('pragma');
206                 }
207
208                 header('Content-type: ' . $photo['type']);
209
210                 $stamp = microtime(true);
211                 if (!$cacheable) {
212                         // it is a private photo that they have no permission to view.
213                         // tell the browser not to cache it, in case they authenticate
214                         // and subsequently have permission to see it
215                         header('Cache-Control: no-store, no-cache, must-revalidate');
216                 } else {
217                         $md5 = $photo['hash'] ?: md5($imgdata);
218                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
219                         header("Etag: \"{$md5}\"");
220                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
221                         header('Cache-Control: max-age=31536000');
222                 }
223                 $checksum = microtime(true) - $stamp;
224
225                 $stamp = microtime(true);
226                 echo $imgdata;
227                 $output = microtime(true) - $stamp;
228
229                 $total = microtime(true) - $totalstamp;
230                 $rest = $total - ($fetch + $data + $checksum + $output);
231
232                 if (!is_null($scale) && ($scale < 4)) {
233                         Logger::debug('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
234                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
235                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
236                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
237                 }
238
239                 System::exit();
240         }
241
242         /**
243          * Fetches photo record by given id number, type and custom size
244          *
245          * @param int $id Photo id
246          * @param string $type Photo type
247          * @param int $customsize Custom size (?)
248          * @return array|bool Array on success, false on error
249          */
250         private static function getPhotoById(int $id, string $type, int $customsize)
251         {
252                 switch($type) {
253                         case 'preview':
254                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'preview-height', 'preview-width', 'height', 'width', 'mimetype', 'type', 'uri-id', 'blurhash'], ['id' => $id]);
255                                 if (empty($media)) {
256                                         return false;
257                                 }
258                                 $url    = $media['preview'];
259                                 $width  = $media['preview-width'];
260                                 $height = $media['preview-height'];
261
262                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
263                                         $url    = $media['url'];
264                                         $width  = $media['width'];
265                                         $height = $media['height'];
266                                 }
267
268                                 if (empty($url)) {
269                                         return false;
270                                 }
271
272                                 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
273                                         return MPhoto::getPhoto($matches[1], $matches[2]);
274                                 }
275
276                                 return MPhoto::createPhotoForExternalResource($url, (int)DI::userSession()->getLocalUserId(), $media['mimetype'] ?? '', $media['blurhash'], $width, $height);
277                         case 'media':
278                                 $media = DBA::selectFirst('post-media', ['url', 'height', 'width', 'mimetype', 'uri-id', 'blurhash'], ['id' => $id, 'type' => Post\Media::IMAGE]);
279                                 if (empty($media)) {
280                                         return false;
281                                 }
282
283                                 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
284                                         return MPhoto::getPhoto($matches[1], $matches[2]);
285                                 }
286
287                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)DI::userSession()->getLocalUserId(), $media['mimetype'], $media['blurhash'], $media['width'], $media['height']);
288                         case 'link':
289                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype', 'blurhash', 'width', 'height'], ['id' => $id]);
290                                 if (empty($link)) {
291                                         return false;
292                                 }
293
294                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0);
295                         case 'contact':
296                                 $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated'];
297                                 $contact = Contact::getById($id, $fields);
298                                 if (empty($contact)) {
299                                         return false;
300                                 }
301
302                                 // For local users directly use the photo record that is marked as the profile
303                                 if (Network::isLocalLink($contact['url'])) {
304                                         $contact = Contact::selectFirst($fields, ['nurl' => $contact['nurl'], 'self' => true]);
305                                         if (!empty($contact)) {
306                                                 if ($customsize <= Proxy::PIXEL_MICRO) {
307                                                         $scale = 6;
308                                                 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
309                                                         $scale = 5;
310                                                 } else {
311                                                         $scale = 4;
312                                                 }
313                                                 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
314                                                 if (!empty($photo)) {
315                                                         return $photo;
316                                                 }
317                                         }
318                                 }
319
320                                 if (!empty($contact['uid']) && empty($contact['photo']) && empty($contact['avatar'])) {
321                                         $contact = Contact::getByURL($contact['url'], false, $fields);
322                                 }
323
324                                 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
325                                         // Fetch photo directly
326                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
327                                         if (!empty($resourceid)) {
328                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
329                                                 if (!empty($photo)) {
330                                                         return $photo;
331                                                 } else {
332                                                         $url = $contact['avatar'];
333                                                 }
334                                         } else {
335                                                 $url = $contact['photo'];
336                                         }
337                                 } elseif (!empty($contact['avatar'])) {
338                                         $url = $contact['avatar'];
339                                 }
340                                 $mimetext = '';
341                                 if (!empty($url)) {
342                                         $mime = ParseUrl::getContentType($url, HttpClientAccept::IMAGE);
343                                         if (!empty($mime)) {
344                                                 $mimetext = $mime[0] . '/' . $mime[1];
345                                         } else {
346                                                 // Only update federated accounts that hadn't failed before and hadn't been updated recently
347                                                 $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
348                                                         && ((time() - strtotime($contact['updated']) > 86400));
349                                                 if ($update) {
350                                                         $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE]);
351                                                         $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
352                                                         Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
353                                                 }
354                                                 if ($update) {
355                                                         try {
356                                                                 UpdateContact::add(Worker::PRIORITY_LOW, $id);
357                                                                 Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
358                                                         } catch (\InvalidArgumentException $e) {
359                                                                 Logger::notice($e->getMessage(), ['id' => $id, 'contact' => $contact]);
360                                                         }
361                                                 } else {
362                                                         Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
363                                                 }
364                                         }
365                                         if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
366                                                 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
367                                                 $mimetext = '';
368                                         } if (!empty($mimetext)) {
369                                                 Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
370                                         }
371                                 }
372                                 if (empty($mimetext) && !empty($contact['blurhash'])) {
373                                         $image = New Image('', 'image/png');
374                                         $image->getFromBlurHash($contact['blurhash'], $customsize, $customsize);
375                                         return MPhoto::createPhotoForImageData($image->asString());
376                                 } elseif (empty($mimetext)) {
377                                         if ($customsize <= Proxy::PIXEL_MICRO) {
378                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_MICRO);
379                                         } elseif ($customsize <= Proxy::PIXEL_THUMB) {
380                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_THUMB);
381                                         } else {
382                                                 $url = Contact::getDefaultAvatar($contact ?: [], Proxy::SIZE_SMALL);
383                                         }
384                                 }
385                                 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext, $contact['blurhash'] ?? null, $customsize, $customsize);
386                         case 'header':
387                                 $fields = ['uid', 'url', 'header', 'network', 'gsid'];
388                                 $contact = Contact::getById($id, $fields);
389                                 if (empty($contact)) {
390                                         return false;
391                                 }
392                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
393                                         $contact = Contact::getByURL($contact['url'], false, $fields);
394                                 }
395                                 if (!empty($contact['header'])) {
396                                         $url = $contact['header'];
397                                 } else {
398                                         $url = Contact::getDefaultHeader($contact);
399                                 }
400                                 return MPhoto::createPhotoForExternalResource($url);
401                         case 'banner':
402                                 $photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
403                                 if (!empty($photo)) {
404                                         return $photo;
405                                 }
406                                 return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
407                         case 'profile':
408                         case 'custom':
409                                 $scale = 4;
410                                 break;
411                         case 'micro':
412                                 $scale = 6;
413                                 break;
414                         case 'avatar':
415                         default:
416                                 $scale = 5;
417                 }
418
419                 $photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
420                 if (empty($photo)) {
421                         $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
422
423                         switch($type) {
424                                 case 'profile':
425                                 case 'custom':
426                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
427                                         break;
428                                 case 'micro':
429                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
430                                         break;
431                                 case 'avatar':
432                                 default:
433                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
434                         }
435
436                         $parts = parse_url($default);
437                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
438                                 $photo = MPhoto::createPhotoForExternalResource($default);
439                         } else {
440                                 $photo = MPhoto::createPhotoForSystemResource($default);
441                         }
442                 }
443                 return $photo;
444         }
445 }