]> git.mxchange.org Git - friendica.git/blob - src/Module/Profile/Profile.php
Merge pull request #13262 from MrPetovan/task/decouple-conversations
[friendica.git] / src / Module / Profile / Profile.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Profile;
23
24 use Friendica\App;
25 use Friendica\Content\Feature;
26 use Friendica\Content\GroupManager;
27 use Friendica\Content\Nav;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Session\Capability\IHandleUserSessions;
35 use Friendica\Core\System;
36 use Friendica\Database\Database;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Profile as ProfileModel;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Module\BaseProfile;
43 use Friendica\Module\Response;
44 use Friendica\Module\Security\Login;
45 use Friendica\Network\HTTPException;
46 use Friendica\Profile\ProfileField\Repository\ProfileField;
47 use Friendica\Protocol\ActivityPub;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Profiler;
50 use Friendica\Util\Strings;
51 use Friendica\Util\Temporal;
52 use Psr\Log\LoggerInterface;
53
54 class Profile extends BaseProfile
55 {
56         /** @var Database */
57         private $database;
58         /** @var App */
59         private $app;
60         /** @var IHandleUserSessions */
61         private $session;
62         /** @var IManageConfigValues */
63         private $config;
64         /** @var App\Page */
65         private $page;
66         /** @var ProfileField */
67         private $profileField;
68
69         public function __construct(ProfileField $profileField, App\Page $page, IManageConfigValues $config, IHandleUserSessions $session, App $app, Database $database, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
70         {
71                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
72
73                 $this->database     = $database;
74                 $this->app          = $app;
75                 $this->session      = $session;
76                 $this->config       = $config;
77                 $this->page         = $page;
78                 $this->profileField = $profileField;
79         }
80
81         protected function rawContent(array $request = [])
82         {
83                 header('Vary: Accept', false);
84
85                 if (ActivityPub::isRequest()) {
86                         $user = $this->database->selectFirst('user', ['uid'], ['nickname' => $this->parameters['nickname'] ?? '', 'account_removed' => false]);
87                         if ($user) {
88                                 try {
89                                         $data = ActivityPub\Transmitter::getProfile($user['uid']);
90                                         header('Access-Control-Allow-Origin: *');
91                                         header('Cache-Control: max-age=23200, stale-while-revalidate=23200');
92                                         System::jsonExit($data, 'application/activity+json');
93                                 } catch (HTTPException\NotFoundException $e) {
94                                         System::jsonError(404, ['error' => 'Record not found']);
95                                 }
96                         }
97
98                         if ($this->database->exists('userd', ['username' => $this->parameters['nickname']])) {
99                                 // Known deleted user
100                                 $data = ActivityPub\Transmitter::getDeletedUser($this->parameters['nickname']);
101
102                                 System::jsonError(410, $data);
103                         } else {
104                                 // Any other case (unknown, blocked, nverified, expired, no profile, no self contact)
105                                 System::jsonError(404, []);
106                         }
107                 }
108         }
109
110         protected function content(array $request = []): string
111         {
112                 $profile = ProfileModel::load($this->app, $this->parameters['nickname'] ?? '');
113                 if (!$profile) {
114                         throw new HTTPException\NotFoundException($this->t('Profile not found.'));
115                 }
116
117                 $remote_contact_id = $this->session->getRemoteContactID($profile['uid']);
118
119                 if ($this->config->get('system', 'block_public') && !$this->session->isAuthenticated()) {
120                         return Login::form();
121                 }
122
123                 if (!empty($profile['hidewall']) && !$this->session->isAuthenticated()) {
124                         $this->baseUrl->redirect('profile/' . $profile['nickname'] . '/restricted');
125                 }
126
127                 if (!empty($profile['page-flags']) && $profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
128                         $this->page['htmlhead'] .= '<meta name="friendica.community" content="true" />' . "\n";
129                 }
130
131                 $this->page['htmlhead'] .= $this->buildHtmlHead($profile, $this->parameters['nickname']);
132
133                 Nav::setSelected('home');
134
135                 $is_owner = $this->session->getLocalUserId() == $profile['uid'];
136                 $o        = self::getTabsHTML('profile', $is_owner, $profile['nickname'], $profile['hide-friends']);
137
138                 $view_as_contacts      = [];
139                 $view_as_contact_id    = 0;
140                 $view_as_contact_alert = '';
141                 if ($is_owner) {
142                         $view_as_contact_id = intval($request['viewas'] ?? 0);
143
144                         $view_as_contacts = Contact::selectToArray(['id', 'name'], [
145                                 'uid'     => $this->session->getLocalUserId(),
146                                 'rel'     => [Contact::FOLLOWER, Contact::SHARING, Contact::FRIEND],
147                                 'network' => Protocol::DFRN,
148                                 'blocked' => false,
149                         ]);
150
151                         $view_as_contact_ids = array_column($view_as_contacts, 'id');
152
153                         // User manually provided a contact ID they aren't privy to, silently defaulting to their own view
154                         if (!in_array($view_as_contact_id, $view_as_contact_ids)) {
155                                 $view_as_contact_id = 0;
156                         }
157
158                         if (($key = array_search($view_as_contact_id, $view_as_contact_ids)) !== false) {
159                                 $view_as_contact_alert = $this->t(
160                                         'You\'re currently viewing your profile as <b>%s</b> <a href="%s" class="btn btn-sm pull-right">Cancel</a>',
161                                         htmlentities($view_as_contacts[$key]['name'], ENT_COMPAT, 'UTF-8'),
162                                         'profile/' . $this->parameters['nickname'] . '/profile'
163                                 );
164                         }
165                 }
166
167                 $basic_fields = [];
168
169                 $basic_fields += self::buildField('fullname', $this->t('Full Name:'), $profile['name']);
170
171                 if (Feature::isEnabled($profile['uid'], 'profile_membersince')) {
172                         $basic_fields += self::buildField(
173                                 'membersince',
174                                 $this->t('Member since:'),
175                                 DateTimeFormat::local($profile['register_date'])
176                         );
177                 }
178
179                 if (!empty($profile['dob']) && $profile['dob'] > DBA::NULL_DATE) {
180                         $year_bd_format  = $this->t('j F, Y');
181                         $short_bd_format = $this->t('j F');
182
183                         $dob = $this->l10n->getDay(
184                                 intval($profile['dob']) ?
185                                         DateTimeFormat::utc($profile['dob'] . ' 00:00 +00:00', $year_bd_format)
186                                         : DateTimeFormat::utc('2001-' . substr($profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
187                         );
188
189                         $basic_fields += self::buildField('dob', $this->t('Birthday:'), $dob);
190
191                         if ($age = Temporal::getAgeByTimezone($profile['dob'], $profile['timezone'])) {
192                                 $basic_fields += self::buildField('age', $this->t('Age: '), $this->tt('%d year old', '%d years old', $age));
193                         }
194                 }
195
196                 if ($profile['about']) {
197                         $basic_fields += self::buildField('about', $this->t('Description:'), BBCode::convertForUriId($profile['uri-id'], $profile['about']));
198                 }
199
200                 if ($profile['xmpp']) {
201                         $basic_fields += self::buildField('xmpp', $this->t('XMPP:'), $profile['xmpp']);
202                 }
203
204                 if ($profile['matrix']) {
205                         $basic_fields += self::buildField('matrix', $this->t('Matrix:'), $profile['matrix']);
206                 }
207
208                 if ($profile['homepage']) {
209                         $basic_fields += self::buildField(
210                                 'homepage',
211                                 $this->t('Homepage:'),
212                                 $this->tryRelMe($profile['homepage']) ?: $profile['homepage']
213                         );
214                 }
215
216                 if (
217                         $profile['address']
218                         || $profile['locality']
219                         || $profile['postal-code']
220                         || $profile['region']
221                         || $profile['country-name']
222                 ) {
223                         $basic_fields += self::buildField('location', $this->t('Location:'), ProfileModel::formatLocation($profile));
224                 }
225
226                 if ($profile['pub_keywords']) {
227                         $tags = [];
228                         // Separator is defined in Module\Settings\Profile\Index::cleanKeywords
229                         foreach (explode(', ', $profile['pub_keywords']) as $tag_label) {
230                                 $tags[] = [
231                                         'url'   => '/search?tag=' . $tag_label,
232                                         'label' => Tag::TAG_CHARACTER[Tag::HASHTAG] . $tag_label,
233                                 ];
234                         }
235
236                         $basic_fields += self::buildField('pub_keywords', $this->t('Tags:'), $tags);
237                 }
238
239                 $custom_fields = [];
240
241                 // Defaults to the current logged in user self contact id to show self-only fields
242                 $contact_id = $view_as_contact_id ?: $remote_contact_id ?: 0;
243
244                 if ($is_owner && $contact_id === 0) {
245                         $profile_fields = $this->profileField->selectByUserId($profile['uid']);
246                 } else {
247                         $profile_fields = $this->profileField->selectByContactId($contact_id, $profile['uid']);
248                 }
249
250                 foreach ($profile_fields as $profile_field) {
251                         $custom_fields += self::buildField(
252                                 'custom_' . $profile_field->order,
253                                 $profile_field->label,
254                                 $this->tryRelMe($profile_field->value) ?: BBCode::convertForUriId($profile['uri-id'], $profile_field->value),
255                                 'aprofile custom'
256                         );
257                 }
258
259                 //show subscribed group if it is enabled in the usersettings
260                 if (Feature::isEnabled($profile['uid'], 'forumlist_profile')) {
261                         $custom_fields += self::buildField(
262                                 'group_list',
263                                 $this->t('Groups:'),
264                                 GroupManager::profileAdvanced($profile['uid'])
265                         );
266                 }
267
268                 $tpl = Renderer::getMarkupTemplate('profile/profile.tpl');
269                 $o   .= Renderer::replaceMacros($tpl, [
270                         '$title'                 => $this->t('Profile'),
271                         '$yourself'              => $this->t('Yourself'),
272                         '$view_as_contacts'      => $view_as_contacts,
273                         '$view_as_contact_id'    => $view_as_contact_id,
274                         '$view_as_contact_alert' => $view_as_contact_alert,
275                         '$view_as'               => $this->t('View profile as:'),
276                         '$submit'                => $this->t('Submit'),
277                         '$basic'                 => $this->t('Basic'),
278                         '$advanced'              => $this->t('Advanced'),
279                         '$is_owner'              => $profile['uid'] == $this->session->getLocalUserId(),
280                         '$query_string'          => $this->args->getQueryString(),
281                         '$basic_fields'          => $basic_fields,
282                         '$custom_fields'         => $custom_fields,
283                         '$profile'               => $profile,
284                         '$edit_link'             => [
285                                 'url'   => 'settings/profile', $this->t('Edit profile'),
286                                 'title' => '',
287                                 'label' => $this->t('Edit profile')
288                         ],
289                         '$viewas_link'           => [
290                                 'url'   => $this->args->getQueryString() . '#viewas',
291                                 'title' => '',
292                                 'label' => $this->t('View as')
293                         ],
294                 ]);
295
296                 Hook::callAll('profile_advanced', $o);
297
298                 return $o;
299         }
300
301         /**
302          * Creates a profile field structure to be used in the profile template
303          *
304          * @param string $name  Arbitrary name of the field
305          * @param string $label Display label of the field
306          * @param mixed  $value Display value of the field
307          * @param string $class Optional CSS class to apply to the field
308          * @return array
309          */
310         private static function buildField(string $name, string $label, $value, string $class = 'aprofile'): array
311         {
312                 return [$name => [
313                         'id'    => 'aprofile-' . $name,
314                         'class' => $class,
315                         'label' => $label,
316                         'value' => $value,
317                 ]];
318         }
319
320         private function buildHtmlHead(array $profile, string $nickname): string
321         {
322                 $htmlhead = "\n";
323
324                 if (!empty($profile['page-flags']) && $profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
325                         $htmlhead .= '<meta name="friendica.community" content="true" />' . "\n";
326                 }
327
328                 if (!empty($profile['openidserver'])) {
329                         $htmlhead .= '<link rel="openid.server" href="' . $profile['openidserver'] . '" />' . "\n";
330                 }
331
332                 if (!empty($profile['openid'])) {
333                         $delegate = strstr($profile['openid'], '://') ? $profile['openid'] : 'https://' . $profile['openid'];
334                         $htmlhead .= '<link rel="openid.delegate" href="' . $delegate . '" />' . "\n";
335                 }
336
337                 // site block
338                 $blocked   = !$this->session->isAuthenticated() && $this->config->get('system', 'block_public');
339                 $userblock = !$this->session->isAuthenticated() && $profile['hidewall'];
340                 if (!$blocked && !$userblock) {
341                         $keywords = str_replace(['#', ',', ' ', ',,'], ['', ' ', ',', ','], $profile['pub_keywords'] ?? '');
342                         if (strlen($keywords)) {
343                                 $htmlhead .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";
344                         }
345                 }
346
347                 $htmlhead .= '<meta name="dfrn-global-visibility" content="' . ($profile['net-publish'] ? 'true' : 'false') . '" />' . "\n";
348
349                 if (!$profile['net-publish']) {
350                         $htmlhead .= '<meta content="noindex, noarchive" name="robots" />' . "\n";
351                 }
352
353                 $htmlhead .= '<link rel="alternate" type="application/atom+xml" href="' . $this->baseUrl . '/dfrn_poll/' . $nickname . '" title="DFRN: ' . $this->t('%s\'s timeline', $profile['name']) . '"/>' . "\n";
354                 $htmlhead .= '<link rel="alternate" type="application/atom+xml" href="' . $this->baseUrl . '/feed/' . $nickname . '/" title="' . $this->t('%s\'s posts', $profile['name']) . '"/>' . "\n";
355                 $htmlhead .= '<link rel="alternate" type="application/atom+xml" href="' . $this->baseUrl . '/feed/' . $nickname . '/comments" title="' . $this->t('%s\'s comments', $profile['name']) . '"/>' . "\n";
356                 $htmlhead .= '<link rel="alternate" type="application/atom+xml" href="' . $this->baseUrl . '/feed/' . $nickname . '/activity" title="' . $this->t('%s\'s timeline', $profile['name']) . '"/>' . "\n";
357                 $uri      = urlencode('acct:' . $profile['nickname'] . '@' . $this->baseUrl->getHost() . ($this->baseUrl->getPath() ? '/' . $this->baseUrl->getPath() : ''));
358                 $htmlhead .= '<link rel="lrdd" type="application/xrd+xml" href="' . $this->baseUrl . '/xrd/?uri=' . $uri . '" />' . "\n";
359                 header('Link: <' . $this->baseUrl . '/xrd/?uri=' . $uri . '>; rel="lrdd"; type="application/xrd+xml"', false);
360
361                 $dfrn_pages = ['request', 'confirm', 'notify', 'poll'];
362                 foreach ($dfrn_pages as $dfrn) {
363                         $htmlhead .= '<link rel="dfrn-' . $dfrn . '" href="' . $this->baseUrl . '/dfrn_' . $dfrn . '/' . $nickname . '" />' . "\n";
364                 }
365
366                 return $htmlhead;
367         }
368
369         /**
370          * Check if the input is an HTTP(S) link and returns a rel="me" link if yes, empty string if not
371          *
372          * @param string $input
373          * @return string
374          */
375         private function tryRelMe(string $input): string
376         {
377                 if (preg_match(Strings::onlyLinkRegEx(), trim($input))) {
378                         return '<a href="' . trim($input) . '" target="_blank" rel="noopener noreferrer me">' . trim($input) . '</a>';
379                 }
380
381                 return '';
382         }
383 }