3 * @file src/Model/Profile.php
5 namespace Friendica\Model;
8 use Friendica\Content\Feature;
9 use Friendica\Content\ForumManager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Content\Widget\ContactBlock;
13 use Friendica\Core\Cache\Duration;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\Session;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
24 use Friendica\Protocol\Activity;
25 use Friendica\Protocol\Diaspora;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\Temporal;
35 * Returns default profile for a given user id
37 * @param integer User ID
39 * @return array Profile data
42 public static function getByUID($uid)
44 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
49 * Returns default profile for a given user ID and ID
51 * @param int $uid The contact ID
52 * @param int $id The contact owner ID
53 * @param array $fields The selected fields
55 * @return array Profile data for the ID
58 public static function getById(int $uid, int $id, array $fields = [])
60 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
64 * Returns profile data for the contact owner
66 * @param int $uid The User ID
67 * @param array $fields The fields to retrieve
69 * @return array Array of profile data
72 public static function getListByUser(int $uid, array $fields = [])
74 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
78 * Returns a formatted location string from the given profile array
80 * @param array $profile Profile array (Generated from the "profile" table)
82 * @return string Location string
84 public static function formatLocation(array $profile)
88 if (!empty($profile['locality'])) {
89 $location .= $profile['locality'];
92 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
97 $location .= $profile['region'];
100 if (!empty($profile['country-name'])) {
105 $location .= $profile['country-name'];
112 * Loads a profile into the page sidebar.
114 * The function requires a writeable copy of the main App structure, and the nickname
115 * of a registered local account.
117 * If the viewer is an authenticated remote viewer, the profile displayed is the
118 * one that has been configured for his/her viewing in the Contact manager.
119 * Passing a non-zero profile ID can also allow a preview of a selected profile
122 * Profile information is placed in the App structure for later retrieval.
123 * Honours the owner's chosen theme for display.
125 * @attention Should only be run in the _init() functions of a module. That ensures that
126 * the theme is chosen before the _init() function of a theme is run, which will usually
127 * load a lot of theme-specific content
130 * @param string $nickname string
131 * @param int $profile int
132 * @param array $profiledata array
133 * @param boolean $show_connect Show connect link
134 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
135 * @throws \ImagickException
137 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
139 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
141 if (!DBA::isResult($user) && empty($profiledata)) {
142 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
146 if (count($profiledata) > 0) {
147 // Ensure to have a "nickname" field
148 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
149 $profiledata['nickname'] = $profiledata['nick'];
152 // Add profile data to sidebar
153 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
155 if (!DBA::isResult($user)) {
160 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
162 if (empty($pdata) && empty($profiledata)) {
163 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
168 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
171 // fetch user tags if this isn't the default profile
173 if (!$pdata['is-default']) {
174 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
175 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
176 if (DBA::isResult($profile)) {
177 $pdata['pub_keywords'] = $profile['pub_keywords'];
181 $a->profile = $pdata;
182 $a->profile_uid = $pdata['profile_uid'];
184 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['profile_uid'], 'system', 'mobile_theme');
185 $a->profile['network'] = Protocol::DFRN;
187 DI::page()['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
189 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
190 $a->setCurrentTheme($a->profile['theme']);
191 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
195 * load/reload current theme info
198 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
200 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
201 if (file_exists($theme_info_file)) {
202 require_once $theme_info_file;
205 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
206 DI::page()['aside'] .= Renderer::replaceMacros(
207 Renderer::getMarkupTemplate('profile_edlink.tpl'),
209 '$editprofile' => DI::l10n()->t('Edit profile'),
210 '$profid' => $a->profile['id']
215 $block = ((Config::get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
219 * By now, the contact block isn't shown, when a different profile is given
220 * But: When this profile was on the same server, then we could display the contacts
223 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
230 * Get all profile data of a local user
232 * If the viewer is an authenticated remote viewer, the profile displayed is the
233 * one that has been configured for his/her viewing in the Contact manager.
234 * Passing a non-zero profile ID can also allow a preview of a selected profile
237 * Includes all available profile data
239 * @param string $nickname nick
240 * @param int $uid uid
241 * @param int $profile_id ID of the profile
245 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
247 if (!empty(Session::getRemoteContactID($uid))) {
248 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => Session::getRemoteContactID($uid)]);
249 if (DBA::isResult($contact)) {
250 $profile_id = $contact['profile-id'];
257 $profile = DBA::fetchFirst(
258 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
259 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
260 `profile`.`uid` AS `profile_uid`, `profile`.*,
261 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
263 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
264 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
265 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
270 if (!DBA::isResult($profile)) {
271 $profile = DBA::fetchFirst(
272 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
273 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
274 `profile`.`uid` AS `profile_uid`, `profile`.*,
275 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
277 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
278 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
279 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
288 * Formats a profile for display in the sidebar.
290 * It is very difficult to templatise the HTML completely
291 * because of all the conditional logic.
293 * @param array $profile
295 * @param boolean $show_connect Show connect link
297 * @return string HTML sidebar module
299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
300 * @throws \ImagickException
301 * @note Returns empty string if passed $profile is wrong type or not populated
303 * @hooks 'profile_sidebar_enter'
304 * array $profile - profile data
305 * @hooks 'profile_sidebar'
308 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
313 // This function can also use contact information in $profile
314 $is_contact = !empty($profile['cid']);
316 if (!is_array($profile) && !count($profile)) {
320 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
322 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
323 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
325 $profile['network_link'] = '';
328 Hook::callAll('profile_sidebar_enter', $profile);
330 if (isset($profile['url'])) {
331 $profile_url = $profile['url'];
333 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
337 $unfollow_link = null;
338 $subscribe_feed_link = null;
339 $wallmessage_link = null;
343 $visitor_contact = [];
344 if (!empty($profile['uid']) && self::getMyURL()) {
345 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
348 $profile_contact = [];
349 if (!empty($profile['cid']) && self::getMyURL()) {
350 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
353 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
354 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
355 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
356 $visitor_is_authenticated = (bool)self::getMyURL();
357 $visitor_is_following =
358 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
359 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
360 $visitor_is_followed =
361 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
362 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
363 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
365 if (!$local_user_is_self && $show_connect) {
366 if (!$visitor_is_authenticated) {
367 if (!empty($profile['nickname'])) {
368 $follow_link = 'dfrn_request/' . $profile['nickname'];
370 } elseif ($profile_is_native) {
371 if ($visitor_is_following) {
372 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
374 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
378 if ($profile_is_dfrn) {
379 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
382 if (Contact::canReceivePrivateMessages($profile)) {
383 if ($visitor_is_followed || $visitor_is_following) {
384 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
385 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
386 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
391 // show edit profile to yourself
392 if (!$is_contact && $local_user_is_self) {
393 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
394 $profile['edit'] = [DI::baseUrl() . '/profiles', DI::l10n()->t('Profiles'), '', DI::l10n()->t('Manage/edit profiles')];
396 "SELECT * FROM `profile` WHERE `uid` = %d",
401 'chg_photo' => DI::l10n()->t('Change profile photo'),
402 'cr_new' => DI::l10n()->t('Create New Profile'),
406 if (DBA::isResult($r)) {
407 foreach ($r as $rr) {
408 $profile['menu']['entries'][] = [
409 'photo' => $rr['thumb'],
411 'alt' => DI::l10n()->t('Profile Image'),
412 'profile_name' => $rr['profile-name'],
413 'isdefault' => $rr['is-default'],
414 'visibile_to_everybody' => DI::l10n()->t('visible to everybody'),
415 'edit_visibility' => DI::l10n()->t('Edit visibility'),
420 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
422 'chg_photo' => DI::l10n()->t('Change profile photo'),
429 // Fetch the account type
430 $account_type = Contact::getAccountType($profile);
432 if (!empty($profile['address'])
433 || !empty($profile['location'])
434 || !empty($profile['locality'])
435 || !empty($profile['region'])
436 || !empty($profile['postal-code'])
437 || !empty($profile['country-name'])
439 $location = DI::l10n()->t('Location:');
442 $gender = !empty($profile['gender']) ? DI::l10n()->t('Gender:') : false;
443 $marital = !empty($profile['marital']) ? DI::l10n()->t('Status:') : false;
444 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
445 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
446 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
448 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
449 $location = $gender = $marital = $homepage = $about = false;
452 $split_name = Diaspora::splitName($profile['name']);
453 $firstname = $split_name['first'];
454 $lastname = $split_name['last'];
456 if (!empty($profile['guid'])) {
458 'guid' => $profile['guid'],
459 'podloc' => DI::baseUrl(),
460 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
461 'nickname' => $profile['nickname'],
462 'fullname' => $profile['name'],
463 'firstname' => $firstname,
464 'lastname' => $lastname,
465 'photo300' => $profile['contact_photo'] ?? '',
466 'photo100' => $profile['contact_thumb'] ?? '',
467 'photo50' => $profile['contact_micro'] ?? '',
477 $contact_block = ContactBlock::getHTML($a->profile);
479 if (is_array($a->profile) && !$a->profile['hide-friends']) {
481 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
482 intval($a->profile['uid'])
484 if (DBA::isResult($r)) {
485 $updated = date('c', strtotime($r[0]['updated']));
488 $contact_count = DBA::count('contact', [
489 'uid' => $profile['uid'],
495 'network' => Protocol::FEDERATED,
501 foreach ($profile as $k => $v) {
502 $k = str_replace('-', '_', $k);
506 if (isset($p['about'])) {
507 $p['about'] = BBCode::convert($p['about']);
510 if (empty($p['address']) && !empty($p['location'])) {
511 $p['address'] = $p['location'];
514 if (isset($p['address'])) {
515 $p['address'] = BBCode::convert($p['address']);
518 if (isset($p['gender'])) {
519 $p['gender'] = DI::l10n()->t($p['gender']);
522 if (isset($p['marital'])) {
523 $p['marital'] = DI::l10n()->t($p['marital']);
526 if (isset($p['photo'])) {
527 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
530 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
532 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
533 $o .= Renderer::replaceMacros($tpl, [
536 '$follow' => DI::l10n()->t('Follow'),
537 '$follow_link' => $follow_link,
538 '$unfollow' => DI::l10n()->t('Unfollow'),
539 '$unfollow_link' => $unfollow_link,
540 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
541 '$subscribe_feed_link' => $subscribe_feed_link,
542 '$wallmessage' => DI::l10n()->t('Message'),
543 '$wallmessage_link' => $wallmessage_link,
544 '$account_type' => $account_type,
545 '$location' => $location,
546 '$gender' => $gender,
547 '$marital' => $marital,
548 '$homepage' => $homepage,
550 '$network' => DI::l10n()->t('Network:'),
551 '$contacts' => $contact_count,
552 '$updated' => $updated,
553 '$diaspora' => $diaspora,
554 '$contact_block' => $contact_block,
557 $arr = ['profile' => &$profile, 'entry' => &$o];
559 Hook::callAll('profile_sidebar', $arr);
564 public static function getBirthdays()
569 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
574 * $mobile_detect = new Mobile_Detect();
575 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
580 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
581 $bd_short = DI::l10n()->t('F d');
583 $cachekey = 'get_birthdays:' . local_user();
584 $r = DI::cache()->get($cachekey);
587 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
589 ON `contact`.`id` = `event`.`cid`
590 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
591 AND NOT `contact`.`pending`
592 AND NOT `contact`.`hidden`
593 AND NOT `contact`.`blocked`
594 AND NOT `contact`.`archive`
595 AND NOT `contact`.`deleted`
596 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
597 ORDER BY `start` ASC ",
601 DateTimeFormat::utc('now + 6 days'),
602 DateTimeFormat::utcNow()
604 if (DBA::isResult($s)) {
605 $r = DBA::toArray($s);
606 DI::cache()->set($cachekey, $r, Duration::HOUR);
612 if (DBA::isResult($r)) {
613 $now = strtotime('now');
617 foreach ($r as $rr) {
618 if (strlen($rr['name'])) {
621 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
625 $classtoday = $istoday ? ' birthday-today ' : '';
627 foreach ($r as &$rr) {
628 if (!strlen($rr['name'])) {
634 if (in_array($rr['cid'], $cids)) {
637 $cids[] = $rr['cid'];
639 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
641 $rr['link'] = Contact::magicLink($rr['url']);
642 $rr['title'] = $rr['name'];
643 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
644 $rr['startime'] = null;
645 $rr['today'] = $today;
649 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
650 return Renderer::replaceMacros($tpl, [
651 '$classtoday' => $classtoday,
653 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
654 '$event_title' => DI::l10n()->t('Birthdays this week:'),
656 '$lbr' => '{', // raw brackets mess up if/endif macro processing
661 public static function getEventsReminderHTML()
666 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
671 * $mobile_detect = new Mobile_Detect();
672 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
677 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
680 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
681 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
682 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
686 if (DBA::isResult($s)) {
690 while ($rr = DBA::fetch($s)) {
691 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
692 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
693 'visible' => true, 'deleted' => false];
694 if (!Item::exists($condition)) {
698 if (strlen($rr['summary'])) {
702 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
703 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
707 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
709 if (strlen($title) > 35) {
710 $title = substr($title, 0, 32) . '... ';
713 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
715 $description = DI::l10n()->t('[No description]');
718 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
720 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
724 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
726 $rr['title'] = $title;
727 $rr['description'] = $description;
728 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
729 $rr['startime'] = $strt;
730 $rr['today'] = $today;
735 $classtoday = (($istoday) ? 'event-today' : '');
737 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
738 return Renderer::replaceMacros($tpl, [
739 '$classtoday' => $classtoday,
740 '$count' => count($r),
741 '$event_reminders' => DI::l10n()->t('Event Reminders'),
742 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
747 public static function getAdvanced(App $a)
749 $uid = intval($a->profile['uid']);
751 if ($a->profile['name']) {
752 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
756 $profile['fullname'] = [DI::l10n()->t('Full Name:'), $a->profile['name']];
758 if (Feature::isEnabled($uid, 'profile_membersince')) {
759 $profile['membersince'] = [DI::l10n()->t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
762 if ($a->profile['gender']) {
763 $profile['gender'] = [DI::l10n()->t('Gender:'), DI::l10n()->t($a->profile['gender'])];
766 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
767 $year_bd_format = DI::l10n()->t('j F, Y');
768 $short_bd_format = DI::l10n()->t('j F');
771 intval($a->profile['dob']) ?
772 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
773 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
776 $profile['birthday'] = [DI::l10n()->t('Birthday:'), $val];
779 if (!empty($a->profile['dob'])
780 && $a->profile['dob'] > DBA::NULL_DATE
781 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
783 $profile['age'] = [DI::l10n()->t('Age:'), $age];
786 if ($a->profile['marital']) {
787 $profile['marital'] = [DI::l10n()->t('Status:'), DI::l10n()->t($a->profile['marital'])];
790 /// @TODO Maybe use x() here, plus below?
791 if ($a->profile['with']) {
792 $profile['marital']['with'] = $a->profile['with'];
795 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
796 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], DI::l10n()->t('for %1$d %2$s'));
799 if ($a->profile['sexual']) {
800 $profile['sexual'] = [DI::l10n()->t('Sexual Preference:'), DI::l10n()->t($a->profile['sexual'])];
803 if ($a->profile['homepage']) {
804 $profile['homepage'] = [DI::l10n()->t('Homepage:'), HTML::toLink($a->profile['homepage'])];
807 if ($a->profile['hometown']) {
808 $profile['hometown'] = [DI::l10n()->t('Hometown:'), HTML::toLink($a->profile['hometown'])];
811 if ($a->profile['pub_keywords']) {
812 $profile['pub_keywords'] = [DI::l10n()->t('Tags:'), $a->profile['pub_keywords']];
815 if ($a->profile['politic']) {
816 $profile['politic'] = [DI::l10n()->t('Political Views:'), $a->profile['politic']];
819 if ($a->profile['religion']) {
820 $profile['religion'] = [DI::l10n()->t('Religion:'), $a->profile['religion']];
823 if ($txt = BBCode::convert($a->profile['about'])) {
824 $profile['about'] = [DI::l10n()->t('About:'), $txt];
827 if ($txt = BBCode::convert($a->profile['interest'])) {
828 $profile['interest'] = [DI::l10n()->t('Hobbies/Interests:'), $txt];
831 if ($txt = BBCode::convert($a->profile['likes'])) {
832 $profile['likes'] = [DI::l10n()->t('Likes:'), $txt];
835 if ($txt = BBCode::convert($a->profile['dislikes'])) {
836 $profile['dislikes'] = [DI::l10n()->t('Dislikes:'), $txt];
839 if ($txt = BBCode::convert($a->profile['contact'])) {
840 $profile['contact'] = [DI::l10n()->t('Contact information and Social Networks:'), $txt];
843 if ($txt = BBCode::convert($a->profile['music'])) {
844 $profile['music'] = [DI::l10n()->t('Musical interests:'), $txt];
847 if ($txt = BBCode::convert($a->profile['book'])) {
848 $profile['book'] = [DI::l10n()->t('Books, literature:'), $txt];
851 if ($txt = BBCode::convert($a->profile['tv'])) {
852 $profile['tv'] = [DI::l10n()->t('Television:'), $txt];
855 if ($txt = BBCode::convert($a->profile['film'])) {
856 $profile['film'] = [DI::l10n()->t('Film/dance/culture/entertainment:'), $txt];
859 if ($txt = BBCode::convert($a->profile['romance'])) {
860 $profile['romance'] = [DI::l10n()->t('Love/Romance:'), $txt];
863 if ($txt = BBCode::convert($a->profile['work'])) {
864 $profile['work'] = [DI::l10n()->t('Work/employment:'), $txt];
867 if ($txt = BBCode::convert($a->profile['education'])) {
868 $profile['education'] = [DI::l10n()->t('School/education:'), $txt];
871 //show subcribed forum if it is enabled in the usersettings
872 if (Feature::isEnabled($uid, 'forumlist_profile')) {
873 $profile['forumlist'] = [DI::l10n()->t('Forums:'), ForumManager::profileAdvanced($uid)];
876 if ($a->profile['uid'] == local_user()) {
877 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $a->profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
880 return Renderer::replaceMacros($tpl, [
881 '$title' => DI::l10n()->t('Profile'),
882 '$basic' => DI::l10n()->t('Basic'),
883 '$advanced' => DI::l10n()->t('Advanced'),
884 '$profile' => $profile
893 * @param string $current
894 * @param bool $is_owner
895 * @param string $nickname
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
899 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
901 if (is_null($nickname)) {
902 $nickname = $a->user['nickname'];
905 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
909 'label' => DI::l10n()->t('Status'),
910 'url' => $baseProfileUrl,
911 'sel' => !$current ? 'active' : '',
912 'title' => DI::l10n()->t('Status Messages and Posts'),
913 'id' => 'status-tab',
917 'label' => DI::l10n()->t('Profile'),
918 'url' => $baseProfileUrl . '/?tab=profile',
919 'sel' => $current == 'profile' ? 'active' : '',
920 'title' => DI::l10n()->t('Profile Details'),
921 'id' => 'profile-tab',
925 'label' => DI::l10n()->t('Photos'),
926 'url' => DI::baseUrl() . '/photos/' . $nickname,
927 'sel' => $current == 'photos' ? 'active' : '',
928 'title' => DI::l10n()->t('Photo Albums'),
933 'label' => DI::l10n()->t('Videos'),
934 'url' => DI::baseUrl() . '/videos/' . $nickname,
935 'sel' => $current == 'videos' ? 'active' : '',
936 'title' => DI::l10n()->t('Videos'),
942 // the calendar link for the full featured events calendar
943 if ($is_owner && $a->theme_events_in_profile) {
945 'label' => DI::l10n()->t('Events'),
946 'url' => DI::baseUrl() . '/events',
947 'sel' => $current == 'events' ? 'active' : '',
948 'title' => DI::l10n()->t('Events and Calendar'),
949 'id' => 'events-tab',
952 // if the user is not the owner of the calendar we only show a calendar
953 // with the public events of the calendar owner
954 } elseif (!$is_owner) {
956 'label' => DI::l10n()->t('Events'),
957 'url' => DI::baseUrl() . '/cal/' . $nickname,
958 'sel' => $current == 'cal' ? 'active' : '',
959 'title' => DI::l10n()->t('Events and Calendar'),
960 'id' => 'events-tab',
967 'label' => DI::l10n()->t('Personal Notes'),
968 'url' => DI::baseUrl() . '/notes',
969 'sel' => $current == 'notes' ? 'active' : '',
970 'title' => DI::l10n()->t('Only You Can See This'),
976 if (!empty($_SESSION['new_member']) && $is_owner) {
978 'label' => DI::l10n()->t('Tips for New Members'),
979 'url' => DI::baseUrl() . '/newmember',
981 'title' => DI::l10n()->t('Tips for New Members'),
982 'id' => 'newmember-tab',
986 if ($is_owner || empty($a->profile['hide-friends'])) {
988 'label' => DI::l10n()->t('Contacts'),
989 'url' => $baseProfileUrl . '/contacts',
990 'sel' => $current == 'contacts' ? 'active' : '',
991 'title' => DI::l10n()->t('Contacts'),
992 'id' => 'viewcontacts-tab',
997 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
998 Hook::callAll('profile_tabs', $arr);
1000 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1002 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1006 * Retrieves the my_url session variable
1010 public static function getMyURL()
1012 return Session::get('my_url');
1016 * Process the 'zrl' parameter and initiate the remote authentication.
1018 * This method checks if the visitor has a public contact entry and
1019 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1022 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1024 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
1025 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
1026 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
1028 * It would be favourable to harmonize the two implementations.
1030 * @param App $a Application instance.
1031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1032 * @throws \ImagickException
1034 public static function zrlInit(App $a)
1036 $my_url = self::getMyURL();
1037 $my_url = Network::isUrlValid($my_url);
1039 if (empty($my_url) || local_user()) {
1043 $addr = $_GET['addr'] ?? $my_url;
1045 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1046 Hook::callAll('zrl_init', $arr);
1048 // Try to find the public contact entry of the visitor.
1049 $cid = Contact::getIdForURL($my_url);
1051 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1055 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1057 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1058 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1062 // Avoid endless loops
1063 $cachekey = 'zrlInit:' . $my_url;
1064 if (DI::cache()->get($cachekey)) {
1065 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1068 DI::cache()->set($cachekey, true, Duration::MINUTE);
1071 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1073 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1074 $addr_request = 'addr=' . urlencode($addr);
1075 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1077 // The other instance needs to know where to redirect.
1078 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1080 // We need to extract the basebath from the profile url
1081 // to redirect the visitors '/magic' module.
1082 $basepath = Contact::getBasepath($contact['url']);
1084 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1085 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1087 // We have to check if the remote server does understand /magic without invoking something
1088 $serverret = Network::curl($basepath . '/magic');
1089 if ($serverret->isSuccess()) {
1090 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1091 System::externalRedirect($magic_path);
1097 * Set the visitor cookies (see remote_user()) for the given handle
1099 * @param string $handle Visitor handle
1100 * @return array Visitor contact array
1102 public static function addVisitorCookieForHandle($handle)
1106 // Try to find the public contact entry of the visitor.
1107 $cid = Contact::getIdForURL($handle);
1109 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1113 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1115 // Authenticate the visitor.
1116 $_SESSION['authenticated'] = 1;
1117 $_SESSION['visitor_id'] = $visitor['id'];
1118 $_SESSION['visitor_handle'] = $visitor['addr'];
1119 $_SESSION['visitor_home'] = $visitor['url'];
1120 $_SESSION['my_url'] = $visitor['url'];
1122 Session::setVisitorsContacts();
1124 $a->contact = $visitor;
1126 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1132 * OpenWebAuth authentication.
1134 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1136 * @param string $token
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 public static function openWebAuthInit($token)
1144 // Clean old OpenWebAuthToken entries.
1145 OpenWebAuthToken::purge('owt', '3 MINUTE');
1147 // Check if the token we got is the same one
1148 // we have stored in the database.
1149 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1151 if ($visitor_handle === false) {
1155 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1156 if (empty($visitor)) {
1161 'visitor' => $visitor,
1162 'url' => DI::args()->getQueryString()
1165 * @hooks magic_auth_success
1166 * Called when a magic-auth was successful.
1167 * * \e array \b visitor
1168 * * \e string \b url
1170 Hook::callAll('magic_auth_success', $arr);
1172 $a->contact = $arr['visitor'];
1174 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1176 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1179 public static function zrl($s, $force = false)
1184 if (!strpos($s, '/profile/') && !$force) {
1187 if ($force && substr($s, -1, 1) !== '/') {
1190 $achar = strpos($s, '?') ? '&' : '?';
1191 $mine = self::getMyURL();
1192 if ($mine && !Strings::compareLink($mine, $s)) {
1193 return $s . $achar . 'zrl=' . urlencode($mine);
1199 * Get the user ID of the page owner.
1201 * Used from within PCSS themes to set theme parameters. If there's a
1202 * profile_uid variable set in App, that is the "page owner" and normally their theme
1203 * settings take precedence; unless a local user sets the "always_my_theme"
1204 * system pconfig, which means they don't want to see anybody else's theme
1205 * settings except their own while on this site.
1207 * @return int user ID
1209 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1210 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1212 public static function getThemeUid(App $a)
1214 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1215 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1216 return local_user();
1223 * search for Profiles
1227 * @param null $search
1229 * @return array [ 'total' => 123, 'entries' => [...] ];
1231 * @throws \Exception
1233 public static function searchProfiles($start = 0, $count = 100, $search = null)
1235 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1238 if (!empty($search)) {
1239 $searchTerm = '%' . $search . '%';
1240 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1242 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1243 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1244 AND ((`profile`.`name` LIKE ?) OR
1245 (`user`.`nickname` LIKE ?) OR
1246 (`profile`.`pdesc` LIKE ?) OR
1247 (`profile`.`locality` LIKE ?) OR
1248 (`profile`.`region` LIKE ?) OR
1249 (`profile`.`country-name` LIKE ?) OR
1250 (`profile`.`gender` LIKE ?) OR
1251 (`profile`.`marital` LIKE ?) OR
1252 (`profile`.`sexual` LIKE ?) OR
1253 (`profile`.`about` LIKE ?) OR
1254 (`profile`.`romance` LIKE ?) OR
1255 (`profile`.`work` LIKE ?) OR
1256 (`profile`.`education` LIKE ?) OR
1257 (`profile`.`pub_keywords` LIKE ?) OR
1258 (`profile`.`prv_keywords` LIKE ?))",
1259 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1260 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1262 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1264 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1265 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1268 if (DBA::isResult($cnt)) {
1269 $total = $cnt['total'];
1272 $order = " ORDER BY `name` ASC ";
1275 // If nothing found, don't try to select details
1277 if (!empty($search)) {
1278 $searchTerm = '%' . $search . '%';
1280 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1281 `contact`.`addr`, `contact`.`url` AS `profile_url`
1283 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1284 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1285 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1286 AND ((`profile`.`name` LIKE ?) OR
1287 (`user`.`nickname` LIKE ?) OR
1288 (`profile`.`pdesc` LIKE ?) OR
1289 (`profile`.`locality` LIKE ?) OR
1290 (`profile`.`region` LIKE ?) OR
1291 (`profile`.`country-name` LIKE ?) OR
1292 (`profile`.`gender` LIKE ?) OR
1293 (`profile`.`marital` LIKE ?) OR
1294 (`profile`.`sexual` LIKE ?) OR
1295 (`profile`.`about` LIKE ?) OR
1296 (`profile`.`romance` LIKE ?) OR
1297 (`profile`.`work` LIKE ?) OR
1298 (`profile`.`education` LIKE ?) OR
1299 (`profile`.`pub_keywords` LIKE ?) OR
1300 (`profile`.`prv_keywords` LIKE ?))
1302 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1303 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1307 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1308 `contact`.`addr`, `contact`.`url` AS `profile_url`
1310 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1311 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1312 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1319 if (DBA::isResult($profiles) && $total > 0) {
1322 'entries' => DBA::toArray($profiles),