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