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