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