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