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