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