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\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\Renderer;
19 use Friendica\Core\Session;
20 use Friendica\Core\System;
21 use Friendica\Database\DBA;
23 use Friendica\Protocol\Activity;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Proxy as ProxyUtils;
28 use Friendica\Util\Strings;
29 use Friendica\Util\Temporal;
34 * Returns default profile for a given user id
36 * @param integer User ID
38 * @return array Profile data
41 public static function getByUID($uid)
43 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
48 * Returns default profile for a given user ID and ID
50 * @param int $uid The contact ID
51 * @param int $id The contact owner ID
52 * @param array $fields The selected fields
54 * @return array Profile data for the ID
57 public static function getById(int $uid, int $id, array $fields = [])
59 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
63 * Returns profile data for the contact owner
65 * @param int $uid The User ID
66 * @param array $fields The fields to retrieve
68 * @return array Array of profile data
71 public static function getListByUser(int $uid, array $fields = [])
73 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
77 * Returns a formatted location string from the given profile array
79 * @param array $profile Profile array (Generated from the "profile" table)
81 * @return string Location string
83 public static function formatLocation(array $profile)
87 if (!empty($profile['locality'])) {
88 $location .= $profile['locality'];
91 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
96 $location .= $profile['region'];
99 if (!empty($profile['country-name'])) {
104 $location .= $profile['country-name'];
111 * Loads a profile into the page sidebar.
113 * The function requires a writeable copy of the main App structure, and the nickname
114 * of a registered local account.
116 * If the viewer is an authenticated remote viewer, the profile displayed is the
117 * one that has been configured for his/her viewing in the Contact manager.
118 * Passing a non-zero profile ID can also allow a preview of a selected profile
121 * Profile information is placed in the App structure for later retrieval.
122 * Honours the owner's chosen theme for display.
124 * @attention Should only be run in the _init() functions of a module. That ensures that
125 * the theme is chosen before the _init() function of a theme is run, which will usually
126 * load a lot of theme-specific content
129 * @param string $nickname string
130 * @param int $profile int
131 * @param array $profiledata array
132 * @param boolean $show_connect Show connect link
133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
134 * @throws \ImagickException
136 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
138 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
140 if (!DBA::isResult($user) && empty($profiledata)) {
141 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
145 if (count($profiledata) > 0) {
146 // Ensure to have a "nickname" field
147 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
148 $profiledata['nickname'] = $profiledata['nick'];
151 // Add profile data to sidebar
152 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
154 if (!DBA::isResult($user)) {
159 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
161 if (empty($pdata) && empty($profiledata)) {
162 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
167 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
170 // fetch user tags if this isn't the default profile
172 if (!$pdata['is-default']) {
173 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
174 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
175 if (DBA::isResult($profile)) {
176 $pdata['pub_keywords'] = $profile['pub_keywords'];
180 $a->profile = $pdata;
181 $a->profile_uid = $pdata['profile_uid'];
183 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['profile_uid'], 'system', 'mobile_theme');
184 $a->profile['network'] = Protocol::DFRN;
186 DI::page()['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
188 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
189 $a->setCurrentTheme($a->profile['theme']);
190 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
194 * load/reload current theme info
197 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
199 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
200 if (file_exists($theme_info_file)) {
201 require_once $theme_info_file;
204 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
205 DI::page()['aside'] .= Renderer::replaceMacros(
206 Renderer::getMarkupTemplate('profile_edlink.tpl'),
208 '$editprofile' => DI::l10n()->t('Edit profile'),
209 '$profid' => $a->profile['id']
214 $block = ((Config::get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
218 * By now, the contact block isn't shown, when a different profile is given
219 * But: When this profile was on the same server, then we could display the contacts
222 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
229 * Get all profile data of a local user
231 * If the viewer is an authenticated remote viewer, the profile displayed is the
232 * one that has been configured for his/her viewing in the Contact manager.
233 * Passing a non-zero profile ID can also allow a preview of a selected profile
236 * Includes all available profile data
238 * @param string $nickname nick
239 * @param int $uid uid
240 * @param int $profile_id ID of the profile
244 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
246 if (!empty(Session::getRemoteContactID($uid))) {
247 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => Session::getRemoteContactID($uid)]);
248 if (DBA::isResult($contact)) {
249 $profile_id = $contact['profile-id'];
256 $profile = DBA::fetchFirst(
257 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
258 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
259 `profile`.`uid` AS `profile_uid`, `profile`.*,
260 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
262 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
263 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
264 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
269 if (!DBA::isResult($profile)) {
270 $profile = DBA::fetchFirst(
271 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
272 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
273 `profile`.`uid` AS `profile_uid`, `profile`.*,
274 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
276 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
277 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
278 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
287 * Formats a profile for display in the sidebar.
289 * It is very difficult to templatise the HTML completely
290 * because of all the conditional logic.
292 * @param array $profile
294 * @param boolean $show_connect Show connect link
296 * @return string HTML sidebar module
298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
299 * @throws \ImagickException
300 * @note Returns empty string if passed $profile is wrong type or not populated
302 * @hooks 'profile_sidebar_enter'
303 * array $profile - profile data
304 * @hooks 'profile_sidebar'
307 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
312 // This function can also use contact information in $profile
313 $is_contact = !empty($profile['cid']);
315 if (!is_array($profile) && !count($profile)) {
319 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
321 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
322 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
324 $profile['network_link'] = '';
327 Hook::callAll('profile_sidebar_enter', $profile);
329 if (isset($profile['url'])) {
330 $profile_url = $profile['url'];
332 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
336 $unfollow_link = null;
337 $subscribe_feed_link = null;
338 $wallmessage_link = null;
342 $visitor_contact = [];
343 if (!empty($profile['uid']) && self::getMyURL()) {
344 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
347 $profile_contact = [];
348 if (!empty($profile['cid']) && self::getMyURL()) {
349 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
352 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
353 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
354 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
355 $visitor_is_authenticated = (bool)self::getMyURL();
356 $visitor_is_following =
357 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
358 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
359 $visitor_is_followed =
360 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
361 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
362 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
364 if (!$local_user_is_self && $show_connect) {
365 if (!$visitor_is_authenticated) {
366 if (!empty($profile['nickname'])) {
367 $follow_link = 'dfrn_request/' . $profile['nickname'];
369 } elseif ($profile_is_native) {
370 if ($visitor_is_following) {
371 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
373 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
377 if ($profile_is_dfrn) {
378 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
381 if (Contact::canReceivePrivateMessages($profile)) {
382 if ($visitor_is_followed || $visitor_is_following) {
383 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
384 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
385 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
390 // show edit profile to yourself
391 if (!$is_contact && $local_user_is_self) {
392 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
393 $profile['edit'] = [DI::baseUrl() . '/profiles', DI::l10n()->t('Profiles'), '', DI::l10n()->t('Manage/edit profiles')];
395 "SELECT * FROM `profile` WHERE `uid` = %d",
400 'chg_photo' => DI::l10n()->t('Change profile photo'),
401 'cr_new' => DI::l10n()->t('Create New Profile'),
405 if (DBA::isResult($r)) {
406 foreach ($r as $rr) {
407 $profile['menu']['entries'][] = [
408 'photo' => $rr['thumb'],
410 'alt' => DI::l10n()->t('Profile Image'),
411 'profile_name' => $rr['profile-name'],
412 'isdefault' => $rr['is-default'],
413 'visibile_to_everybody' => DI::l10n()->t('visible to everybody'),
414 'edit_visibility' => DI::l10n()->t('Edit visibility'),
419 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
421 'chg_photo' => DI::l10n()->t('Change profile photo'),
428 // Fetch the account type
429 $account_type = Contact::getAccountType($profile);
431 if (!empty($profile['address'])
432 || !empty($profile['location'])
433 || !empty($profile['locality'])
434 || !empty($profile['region'])
435 || !empty($profile['postal-code'])
436 || !empty($profile['country-name'])
438 $location = DI::l10n()->t('Location:');
441 $gender = !empty($profile['gender']) ? DI::l10n()->t('Gender:') : false;
442 $marital = !empty($profile['marital']) ? DI::l10n()->t('Status:') : false;
443 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
444 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
445 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
447 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
448 $location = $gender = $marital = $homepage = $about = false;
451 $split_name = Diaspora::splitName($profile['name']);
452 $firstname = $split_name['first'];
453 $lastname = $split_name['last'];
455 if (!empty($profile['guid'])) {
457 'guid' => $profile['guid'],
458 'podloc' => DI::baseUrl(),
459 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
460 'nickname' => $profile['nickname'],
461 'fullname' => $profile['name'],
462 'firstname' => $firstname,
463 'lastname' => $lastname,
464 'photo300' => $profile['contact_photo'] ?? '',
465 'photo100' => $profile['contact_thumb'] ?? '',
466 'photo50' => $profile['contact_micro'] ?? '',
476 $contact_block = ContactBlock::getHTML($a->profile);
478 if (is_array($a->profile) && !$a->profile['hide-friends']) {
480 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
481 intval($a->profile['uid'])
483 if (DBA::isResult($r)) {
484 $updated = date('c', strtotime($r[0]['updated']));
487 $contact_count = DBA::count('contact', [
488 'uid' => $profile['uid'],
494 'network' => Protocol::FEDERATED,
500 foreach ($profile as $k => $v) {
501 $k = str_replace('-', '_', $k);
505 if (isset($p['about'])) {
506 $p['about'] = BBCode::convert($p['about']);
509 if (empty($p['address']) && !empty($p['location'])) {
510 $p['address'] = $p['location'];
513 if (isset($p['address'])) {
514 $p['address'] = BBCode::convert($p['address']);
517 if (isset($p['gender'])) {
518 $p['gender'] = DI::l10n()->t($p['gender']);
521 if (isset($p['marital'])) {
522 $p['marital'] = DI::l10n()->t($p['marital']);
525 if (isset($p['photo'])) {
526 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
529 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
531 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
532 $o .= Renderer::replaceMacros($tpl, [
535 '$follow' => DI::l10n()->t('Follow'),
536 '$follow_link' => $follow_link,
537 '$unfollow' => DI::l10n()->t('Unfollow'),
538 '$unfollow_link' => $unfollow_link,
539 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
540 '$subscribe_feed_link' => $subscribe_feed_link,
541 '$wallmessage' => DI::l10n()->t('Message'),
542 '$wallmessage_link' => $wallmessage_link,
543 '$account_type' => $account_type,
544 '$location' => $location,
545 '$gender' => $gender,
546 '$marital' => $marital,
547 '$homepage' => $homepage,
549 '$network' => DI::l10n()->t('Network:'),
550 '$contacts' => $contact_count,
551 '$updated' => $updated,
552 '$diaspora' => $diaspora,
553 '$contact_block' => $contact_block,
556 $arr = ['profile' => &$profile, 'entry' => &$o];
558 Hook::callAll('profile_sidebar', $arr);
563 public static function getBirthdays()
568 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
573 * $mobile_detect = new Mobile_Detect();
574 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
579 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
580 $bd_short = DI::l10n()->t('F d');
582 $cachekey = 'get_birthdays:' . local_user();
583 $r = DI::cache()->get($cachekey);
586 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
588 ON `contact`.`id` = `event`.`cid`
589 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
590 AND NOT `contact`.`pending`
591 AND NOT `contact`.`hidden`
592 AND NOT `contact`.`blocked`
593 AND NOT `contact`.`archive`
594 AND NOT `contact`.`deleted`
595 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
596 ORDER BY `start` ASC ",
600 DateTimeFormat::utc('now + 6 days'),
601 DateTimeFormat::utcNow()
603 if (DBA::isResult($s)) {
604 $r = DBA::toArray($s);
605 DI::cache()->set($cachekey, $r, Duration::HOUR);
611 if (DBA::isResult($r)) {
612 $now = strtotime('now');
616 foreach ($r as $rr) {
617 if (strlen($rr['name'])) {
620 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
624 $classtoday = $istoday ? ' birthday-today ' : '';
626 foreach ($r as &$rr) {
627 if (!strlen($rr['name'])) {
633 if (in_array($rr['cid'], $cids)) {
636 $cids[] = $rr['cid'];
638 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
640 $rr['link'] = Contact::magicLink($rr['url']);
641 $rr['title'] = $rr['name'];
642 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
643 $rr['startime'] = null;
644 $rr['today'] = $today;
648 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
649 return Renderer::replaceMacros($tpl, [
650 '$classtoday' => $classtoday,
652 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
653 '$event_title' => DI::l10n()->t('Birthdays this week:'),
655 '$lbr' => '{', // raw brackets mess up if/endif macro processing
660 public static function getEventsReminderHTML()
665 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
670 * $mobile_detect = new Mobile_Detect();
671 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
676 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
679 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
680 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
681 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
685 if (DBA::isResult($s)) {
689 while ($rr = DBA::fetch($s)) {
690 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
691 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
692 'visible' => true, 'deleted' => false];
693 if (!Item::exists($condition)) {
697 if (strlen($rr['summary'])) {
701 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
702 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
706 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
708 if (strlen($title) > 35) {
709 $title = substr($title, 0, 32) . '... ';
712 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
714 $description = DI::l10n()->t('[No description]');
717 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
719 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
723 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
725 $rr['title'] = $title;
726 $rr['description'] = $description;
727 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
728 $rr['startime'] = $strt;
729 $rr['today'] = $today;
734 $classtoday = (($istoday) ? 'event-today' : '');
736 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
737 return Renderer::replaceMacros($tpl, [
738 '$classtoday' => $classtoday,
739 '$count' => count($r),
740 '$event_reminders' => DI::l10n()->t('Event Reminders'),
741 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
746 public static function getAdvanced(App $a)
748 $uid = intval($a->profile['uid']);
750 if ($a->profile['name']) {
751 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
755 $profile['fullname'] = [DI::l10n()->t('Full Name:'), $a->profile['name']];
757 if (Feature::isEnabled($uid, 'profile_membersince')) {
758 $profile['membersince'] = [DI::l10n()->t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
761 if ($a->profile['gender']) {
762 $profile['gender'] = [DI::l10n()->t('Gender:'), DI::l10n()->t($a->profile['gender'])];
765 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
766 $year_bd_format = DI::l10n()->t('j F, Y');
767 $short_bd_format = DI::l10n()->t('j F');
769 $val = DI::l10n()->getDay(
770 intval($a->profile['dob']) ?
771 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
772 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
775 $profile['birthday'] = [DI::l10n()->t('Birthday:'), $val];
778 if (!empty($a->profile['dob'])
779 && $a->profile['dob'] > DBA::NULL_DATE
780 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
782 $profile['age'] = [DI::l10n()->t('Age:'), $age];
785 if ($a->profile['marital']) {
786 $profile['marital'] = [DI::l10n()->t('Status:'), DI::l10n()->t($a->profile['marital'])];
789 /// @TODO Maybe use x() here, plus below?
790 if ($a->profile['with']) {
791 $profile['marital']['with'] = $a->profile['with'];
794 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
795 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], DI::l10n()->t('for %1$d %2$s'));
798 if ($a->profile['sexual']) {
799 $profile['sexual'] = [DI::l10n()->t('Sexual Preference:'), DI::l10n()->t($a->profile['sexual'])];
802 if ($a->profile['homepage']) {
803 $profile['homepage'] = [DI::l10n()->t('Homepage:'), HTML::toLink($a->profile['homepage'])];
806 if ($a->profile['hometown']) {
807 $profile['hometown'] = [DI::l10n()->t('Hometown:'), HTML::toLink($a->profile['hometown'])];
810 if ($a->profile['pub_keywords']) {
811 $profile['pub_keywords'] = [DI::l10n()->t('Tags:'), $a->profile['pub_keywords']];
814 if ($a->profile['politic']) {
815 $profile['politic'] = [DI::l10n()->t('Political Views:'), $a->profile['politic']];
818 if ($a->profile['religion']) {
819 $profile['religion'] = [DI::l10n()->t('Religion:'), $a->profile['religion']];
822 if ($txt = BBCode::convert($a->profile['about'])) {
823 $profile['about'] = [DI::l10n()->t('About:'), $txt];
826 if ($txt = BBCode::convert($a->profile['interest'])) {
827 $profile['interest'] = [DI::l10n()->t('Hobbies/Interests:'), $txt];
830 if ($txt = BBCode::convert($a->profile['likes'])) {
831 $profile['likes'] = [DI::l10n()->t('Likes:'), $txt];
834 if ($txt = BBCode::convert($a->profile['dislikes'])) {
835 $profile['dislikes'] = [DI::l10n()->t('Dislikes:'), $txt];
838 if ($txt = BBCode::convert($a->profile['contact'])) {
839 $profile['contact'] = [DI::l10n()->t('Contact information and Social Networks:'), $txt];
842 if ($txt = BBCode::convert($a->profile['music'])) {
843 $profile['music'] = [DI::l10n()->t('Musical interests:'), $txt];
846 if ($txt = BBCode::convert($a->profile['book'])) {
847 $profile['book'] = [DI::l10n()->t('Books, literature:'), $txt];
850 if ($txt = BBCode::convert($a->profile['tv'])) {
851 $profile['tv'] = [DI::l10n()->t('Television:'), $txt];
854 if ($txt = BBCode::convert($a->profile['film'])) {
855 $profile['film'] = [DI::l10n()->t('Film/dance/culture/entertainment:'), $txt];
858 if ($txt = BBCode::convert($a->profile['romance'])) {
859 $profile['romance'] = [DI::l10n()->t('Love/Romance:'), $txt];
862 if ($txt = BBCode::convert($a->profile['work'])) {
863 $profile['work'] = [DI::l10n()->t('Work/employment:'), $txt];
866 if ($txt = BBCode::convert($a->profile['education'])) {
867 $profile['education'] = [DI::l10n()->t('School/education:'), $txt];
870 //show subcribed forum if it is enabled in the usersettings
871 if (Feature::isEnabled($uid, 'forumlist_profile')) {
872 $profile['forumlist'] = [DI::l10n()->t('Forums:'), ForumManager::profileAdvanced($uid)];
875 if ($a->profile['uid'] == local_user()) {
876 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $a->profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
879 return Renderer::replaceMacros($tpl, [
880 '$title' => DI::l10n()->t('Profile'),
881 '$basic' => DI::l10n()->t('Basic'),
882 '$advanced' => DI::l10n()->t('Advanced'),
883 '$profile' => $profile
892 * @param string $current
893 * @param bool $is_owner
894 * @param string $nickname
896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
900 if (is_null($nickname)) {
901 $nickname = $a->user['nickname'];
904 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
908 'label' => DI::l10n()->t('Status'),
909 'url' => $baseProfileUrl,
910 'sel' => !$current ? 'active' : '',
911 'title' => DI::l10n()->t('Status Messages and Posts'),
912 'id' => 'status-tab',
916 'label' => DI::l10n()->t('Profile'),
917 'url' => $baseProfileUrl . '/?tab=profile',
918 'sel' => $current == 'profile' ? 'active' : '',
919 'title' => DI::l10n()->t('Profile Details'),
920 'id' => 'profile-tab',
924 'label' => DI::l10n()->t('Photos'),
925 'url' => DI::baseUrl() . '/photos/' . $nickname,
926 'sel' => $current == 'photos' ? 'active' : '',
927 'title' => DI::l10n()->t('Photo Albums'),
932 'label' => DI::l10n()->t('Videos'),
933 'url' => DI::baseUrl() . '/videos/' . $nickname,
934 'sel' => $current == 'videos' ? 'active' : '',
935 'title' => DI::l10n()->t('Videos'),
941 // the calendar link for the full featured events calendar
942 if ($is_owner && $a->theme_events_in_profile) {
944 'label' => DI::l10n()->t('Events'),
945 'url' => DI::baseUrl() . '/events',
946 'sel' => $current == 'events' ? 'active' : '',
947 'title' => DI::l10n()->t('Events and Calendar'),
948 'id' => 'events-tab',
951 // if the user is not the owner of the calendar we only show a calendar
952 // with the public events of the calendar owner
953 } elseif (!$is_owner) {
955 'label' => DI::l10n()->t('Events'),
956 'url' => DI::baseUrl() . '/cal/' . $nickname,
957 'sel' => $current == 'cal' ? 'active' : '',
958 'title' => DI::l10n()->t('Events and Calendar'),
959 'id' => 'events-tab',
966 'label' => DI::l10n()->t('Personal Notes'),
967 'url' => DI::baseUrl() . '/notes',
968 'sel' => $current == 'notes' ? 'active' : '',
969 'title' => DI::l10n()->t('Only You Can See This'),
975 if (!empty($_SESSION['new_member']) && $is_owner) {
977 'label' => DI::l10n()->t('Tips for New Members'),
978 'url' => DI::baseUrl() . '/newmember',
980 'title' => DI::l10n()->t('Tips for New Members'),
981 'id' => 'newmember-tab',
985 if ($is_owner || empty($a->profile['hide-friends'])) {
987 'label' => DI::l10n()->t('Contacts'),
988 'url' => $baseProfileUrl . '/contacts',
989 'sel' => $current == 'contacts' ? 'active' : '',
990 'title' => DI::l10n()->t('Contacts'),
991 'id' => 'viewcontacts-tab',
996 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
997 Hook::callAll('profile_tabs', $arr);
999 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1001 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1005 * Retrieves the my_url session variable
1009 public static function getMyURL()
1011 return Session::get('my_url');
1015 * Process the 'zrl' parameter and initiate the remote authentication.
1017 * This method checks if the visitor has a public contact entry and
1018 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1021 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1023 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
1024 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
1025 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
1027 * It would be favourable to harmonize the two implementations.
1029 * @param App $a Application instance.
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031 * @throws \ImagickException
1033 public static function zrlInit(App $a)
1035 $my_url = self::getMyURL();
1036 $my_url = Network::isUrlValid($my_url);
1038 if (empty($my_url) || local_user()) {
1042 $addr = $_GET['addr'] ?? $my_url;
1044 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1045 Hook::callAll('zrl_init', $arr);
1047 // Try to find the public contact entry of the visitor.
1048 $cid = Contact::getIdForURL($my_url);
1050 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1054 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1056 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1057 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1061 // Avoid endless loops
1062 $cachekey = 'zrlInit:' . $my_url;
1063 if (DI::cache()->get($cachekey)) {
1064 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1067 DI::cache()->set($cachekey, true, Duration::MINUTE);
1070 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1072 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1073 $addr_request = 'addr=' . urlencode($addr);
1074 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1076 // The other instance needs to know where to redirect.
1077 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1079 // We need to extract the basebath from the profile url
1080 // to redirect the visitors '/magic' module.
1081 $basepath = Contact::getBasepath($contact['url']);
1083 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1084 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1086 // We have to check if the remote server does understand /magic without invoking something
1087 $serverret = Network::curl($basepath . '/magic');
1088 if ($serverret->isSuccess()) {
1089 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1090 System::externalRedirect($magic_path);
1096 * Set the visitor cookies (see remote_user()) for the given handle
1098 * @param string $handle Visitor handle
1099 * @return array Visitor contact array
1101 public static function addVisitorCookieForHandle($handle)
1105 // Try to find the public contact entry of the visitor.
1106 $cid = Contact::getIdForURL($handle);
1108 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1112 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1114 // Authenticate the visitor.
1115 $_SESSION['authenticated'] = 1;
1116 $_SESSION['visitor_id'] = $visitor['id'];
1117 $_SESSION['visitor_handle'] = $visitor['addr'];
1118 $_SESSION['visitor_home'] = $visitor['url'];
1119 $_SESSION['my_url'] = $visitor['url'];
1121 Session::setVisitorsContacts();
1123 $a->contact = $visitor;
1125 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1131 * OpenWebAuth authentication.
1133 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1135 * @param string $token
1136 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137 * @throws \ImagickException
1139 public static function openWebAuthInit($token)
1143 // Clean old OpenWebAuthToken entries.
1144 OpenWebAuthToken::purge('owt', '3 MINUTE');
1146 // Check if the token we got is the same one
1147 // we have stored in the database.
1148 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1150 if ($visitor_handle === false) {
1154 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1155 if (empty($visitor)) {
1160 'visitor' => $visitor,
1161 'url' => DI::args()->getQueryString()
1164 * @hooks magic_auth_success
1165 * Called when a magic-auth was successful.
1166 * * \e array \b visitor
1167 * * \e string \b url
1169 Hook::callAll('magic_auth_success', $arr);
1171 $a->contact = $arr['visitor'];
1173 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1175 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1178 public static function zrl($s, $force = false)
1183 if (!strpos($s, '/profile/') && !$force) {
1186 if ($force && substr($s, -1, 1) !== '/') {
1189 $achar = strpos($s, '?') ? '&' : '?';
1190 $mine = self::getMyURL();
1191 if ($mine && !Strings::compareLink($mine, $s)) {
1192 return $s . $achar . 'zrl=' . urlencode($mine);
1198 * Get the user ID of the page owner.
1200 * Used from within PCSS themes to set theme parameters. If there's a
1201 * profile_uid variable set in App, that is the "page owner" and normally their theme
1202 * settings take precedence; unless a local user sets the "always_my_theme"
1203 * system pconfig, which means they don't want to see anybody else's theme
1204 * settings except their own while on this site.
1206 * @return int user ID
1208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1209 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1211 public static function getThemeUid(App $a)
1213 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1214 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1215 return local_user();
1222 * search for Profiles
1226 * @param null $search
1228 * @return array [ 'total' => 123, 'entries' => [...] ];
1230 * @throws \Exception
1232 public static function searchProfiles($start = 0, $count = 100, $search = null)
1234 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1237 if (!empty($search)) {
1238 $searchTerm = '%' . $search . '%';
1239 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1241 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1242 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1243 AND ((`profile`.`name` LIKE ?) OR
1244 (`user`.`nickname` LIKE ?) OR
1245 (`profile`.`pdesc` LIKE ?) OR
1246 (`profile`.`locality` LIKE ?) OR
1247 (`profile`.`region` LIKE ?) OR
1248 (`profile`.`country-name` LIKE ?) OR
1249 (`profile`.`gender` LIKE ?) OR
1250 (`profile`.`marital` LIKE ?) OR
1251 (`profile`.`sexual` LIKE ?) OR
1252 (`profile`.`about` LIKE ?) OR
1253 (`profile`.`romance` LIKE ?) OR
1254 (`profile`.`work` LIKE ?) OR
1255 (`profile`.`education` LIKE ?) OR
1256 (`profile`.`pub_keywords` LIKE ?) OR
1257 (`profile`.`prv_keywords` LIKE ?))",
1258 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1259 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1261 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1263 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1264 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1267 if (DBA::isResult($cnt)) {
1268 $total = $cnt['total'];
1271 $order = " ORDER BY `name` ASC ";
1274 // If nothing found, don't try to select details
1276 if (!empty($search)) {
1277 $searchTerm = '%' . $search . '%';
1279 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1280 `contact`.`addr`, `contact`.`url` AS `profile_url`
1282 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1283 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1284 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1285 AND ((`profile`.`name` LIKE ?) OR
1286 (`user`.`nickname` LIKE ?) OR
1287 (`profile`.`pdesc` LIKE ?) OR
1288 (`profile`.`locality` LIKE ?) OR
1289 (`profile`.`region` LIKE ?) OR
1290 (`profile`.`country-name` LIKE ?) OR
1291 (`profile`.`gender` LIKE ?) OR
1292 (`profile`.`marital` LIKE ?) OR
1293 (`profile`.`sexual` LIKE ?) OR
1294 (`profile`.`about` LIKE ?) OR
1295 (`profile`.`romance` LIKE ?) OR
1296 (`profile`.`work` LIKE ?) OR
1297 (`profile`.`education` LIKE ?) OR
1298 (`profile`.`pub_keywords` LIKE ?) OR
1299 (`profile`.`prv_keywords` LIKE ?))
1301 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1302 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1306 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1307 `contact`.`addr`, `contact`.`url` AS `profile_url`
1309 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1310 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1311 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1318 if (DBA::isResult($profiles) && $total > 0) {
1321 'entries' => DBA::toArray($profiles),