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;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Database\DBA;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Proxy as ProxyUtils;
30 use Friendica\Util\Strings;
31 use Friendica\Util\Temporal;
36 * @brief Returns default profile for a given user id
38 * @param integer User ID
40 * @return array Profile data
43 public static function getByUID($uid)
45 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
50 * @brief Returns default profile for a given user ID and ID
52 * @param int $uid The contact ID
53 * @param int $id The contact owner ID
54 * @param array $fields The selected fields
56 * @return array Profile data for the ID
59 public static function getById(int $uid, int $id, array $fields = [])
61 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
65 * @brief Returns profile data for the contact owner
67 * @param int $uid The User ID
68 * @param array $fields The fields to retrieve
70 * @return array Array of profile data
73 public static function getListByUser(int $uid, array $fields = [])
75 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
79 * @brief Returns a formatted location string from the given profile array
81 * @param array $profile Profile array (Generated from the "profile" table)
83 * @return string Location string
85 public static function formatLocation(array $profile)
89 if (!empty($profile['locality'])) {
90 $location .= $profile['locality'];
93 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
98 $location .= $profile['region'];
101 if (!empty($profile['country-name'])) {
106 $location .= $profile['country-name'];
114 * Loads a profile into the page sidebar.
116 * The function requires a writeable copy of the main App structure, and the nickname
117 * of a registered local account.
119 * If the viewer is an authenticated remote viewer, the profile displayed is the
120 * one that has been configured for his/her viewing in the Contact manager.
121 * Passing a non-zero profile ID can also allow a preview of a selected profile
124 * Profile information is placed in the App structure for later retrieval.
125 * Honours the owner's chosen theme for display.
127 * @attention Should only be run in the _init() functions of a module. That ensures that
128 * the theme is chosen before the _init() function of a theme is run, which will usually
129 * load a lot of theme-specific content
131 * @brief Loads a profile into the page sidebar.
133 * @param string $nickname string
134 * @param int $profile int
135 * @param array $profiledata array
136 * @param boolean $show_connect Show connect link
137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
138 * @throws \ImagickException
140 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
142 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
144 if (!DBA::isResult($user) && empty($profiledata)) {
145 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
149 if (count($profiledata) > 0) {
150 // Ensure to have a "nickname" field
151 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
152 $profiledata['nickname'] = $profiledata['nick'];
155 // Add profile data to sidebar
156 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
158 if (!DBA::isResult($user)) {
163 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
165 if (empty($pdata) && empty($profiledata)) {
166 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
171 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
174 // fetch user tags if this isn't the default profile
176 if (!$pdata['is-default']) {
177 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
178 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
179 if (DBA::isResult($profile)) {
180 $pdata['pub_keywords'] = $profile['pub_keywords'];
184 $a->profile = $pdata;
185 $a->profile_uid = $pdata['profile_uid'];
187 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
188 $a->profile['network'] = Protocol::DFRN;
190 DI::page()['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
192 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
193 $a->setCurrentTheme($a->profile['theme']);
194 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
198 * load/reload current theme info
201 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
203 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
204 if (file_exists($theme_info_file)) {
205 require_once $theme_info_file;
208 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
209 DI::page()['aside'] .= Renderer::replaceMacros(
210 Renderer::getMarkupTemplate('profile_edlink.tpl'),
212 '$editprofile' => L10n::t('Edit profile'),
213 '$profid' => $a->profile['id']
218 $block = ((Config::get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
222 * By now, the contact block isn't shown, when a different profile is given
223 * But: When this profile was on the same server, then we could display the contacts
226 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
233 * Get all profile data of a local user
235 * If the viewer is an authenticated remote viewer, the profile displayed is the
236 * one that has been configured for his/her viewing in the Contact manager.
237 * Passing a non-zero profile ID can also allow a preview of a selected profile
240 * Includes all available profile data
242 * @brief Get all profile data of a local user
243 * @param string $nickname nick
244 * @param int $uid uid
245 * @param int $profile_id ID of the profile
249 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
251 if (!empty(Session::getRemoteContactID($uid))) {
252 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => Session::getRemoteContactID($uid)]);
253 if (DBA::isResult($contact)) {
254 $profile_id = $contact['profile-id'];
261 $profile = DBA::fetchFirst(
262 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
263 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
264 `profile`.`uid` AS `profile_uid`, `profile`.*,
265 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
267 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
268 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
269 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
274 if (!DBA::isResult($profile)) {
275 $profile = DBA::fetchFirst(
276 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
277 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
278 `profile`.`uid` AS `profile_uid`, `profile`.*,
279 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
281 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
282 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
283 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
292 * Formats a profile for display in the sidebar.
294 * It is very difficult to templatise the HTML completely
295 * because of all the conditional logic.
297 * @brief Formats a profile for display in the sidebar.
298 * @param array $profile
300 * @param boolean $show_connect Show connect link
302 * @return string HTML sidebar module
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
306 * @note Returns empty string if passed $profile is wrong type or not populated
308 * @hooks 'profile_sidebar_enter'
309 * array $profile - profile data
310 * @hooks 'profile_sidebar'
313 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
318 // This function can also use contact information in $profile
319 $is_contact = !empty($profile['cid']);
321 if (!is_array($profile) && !count($profile)) {
325 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
327 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
328 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
330 $profile['network_link'] = '';
333 Hook::callAll('profile_sidebar_enter', $profile);
335 if (isset($profile['url'])) {
336 $profile_url = $profile['url'];
338 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
342 $unfollow_link = null;
343 $subscribe_feed_link = null;
344 $wallmessage_link = null;
348 $visitor_contact = [];
349 if (!empty($profile['uid']) && self::getMyURL()) {
350 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
353 $profile_contact = [];
354 if (!empty($profile['cid']) && self::getMyURL()) {
355 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
358 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
359 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
360 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
361 $visitor_is_authenticated = (bool)self::getMyURL();
362 $visitor_is_following =
363 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
364 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
365 $visitor_is_followed =
366 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
367 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
368 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
370 if (!$local_user_is_self && $show_connect) {
371 if (!$visitor_is_authenticated) {
372 $follow_link = 'dfrn_request/' . $profile['nickname'];
373 } elseif ($profile_is_native) {
374 if ($visitor_is_following) {
375 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
377 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
381 if ($profile_is_dfrn) {
382 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
385 if (Contact::canReceivePrivateMessages($profile)) {
386 if ($visitor_is_followed || $visitor_is_following) {
387 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
388 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
389 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
394 // show edit profile to yourself
395 if (!$is_contact && $local_user_is_self) {
396 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
397 $profile['edit'] = [DI::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
399 "SELECT * FROM `profile` WHERE `uid` = %d",
404 'chg_photo' => L10n::t('Change profile photo'),
405 'cr_new' => L10n::t('Create New Profile'),
409 if (DBA::isResult($r)) {
410 foreach ($r as $rr) {
411 $profile['menu']['entries'][] = [
412 'photo' => $rr['thumb'],
414 'alt' => L10n::t('Profile Image'),
415 'profile_name' => $rr['profile-name'],
416 'isdefault' => $rr['is-default'],
417 'visibile_to_everybody' => L10n::t('visible to everybody'),
418 'edit_visibility' => L10n::t('Edit visibility'),
423 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
425 'chg_photo' => L10n::t('Change profile photo'),
432 // Fetch the account type
433 $account_type = Contact::getAccountType($profile);
435 if (!empty($profile['address'])
436 || !empty($profile['location'])
437 || !empty($profile['locality'])
438 || !empty($profile['region'])
439 || !empty($profile['postal-code'])
440 || !empty($profile['country-name'])
442 $location = L10n::t('Location:');
445 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
446 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
447 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
448 $about = !empty($profile['about']) ? L10n::t('About:') : false;
449 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
451 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
452 $location = $gender = $marital = $homepage = $about = false;
455 $split_name = Diaspora::splitName($profile['name']);
456 $firstname = $split_name['first'];
457 $lastname = $split_name['last'];
459 if (!empty($profile['guid'])) {
461 'guid' => $profile['guid'],
462 'podloc' => DI::baseUrl(),
463 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
464 'nickname' => $profile['nickname'],
465 'fullname' => $profile['name'],
466 'firstname' => $firstname,
467 'lastname' => $lastname,
468 'photo300' => $profile['contact_photo'] ?? '',
469 'photo100' => $profile['contact_thumb'] ?? '',
470 'photo50' => $profile['contact_micro'] ?? '',
480 $contact_block = ContactBlock::getHTML($a->profile);
482 if (is_array($a->profile) && !$a->profile['hide-friends']) {
484 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
485 intval($a->profile['uid'])
487 if (DBA::isResult($r)) {
488 $updated = date('c', strtotime($r[0]['updated']));
491 $contact_count = DBA::count('contact', [
492 'uid' => $profile['uid'],
498 'network' => Protocol::FEDERATED,
504 foreach ($profile as $k => $v) {
505 $k = str_replace('-', '_', $k);
509 if (isset($p['about'])) {
510 $p['about'] = BBCode::convert($p['about']);
513 if (empty($p['address']) && !empty($p['location'])) {
514 $p['address'] = $p['location'];
517 if (isset($p['address'])) {
518 $p['address'] = BBCode::convert($p['address']);
521 if (isset($p['gender'])) {
522 $p['gender'] = L10n::t($p['gender']);
525 if (isset($p['marital'])) {
526 $p['marital'] = L10n::t($p['marital']);
529 if (isset($p['photo'])) {
530 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
533 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
535 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
536 $o .= Renderer::replaceMacros($tpl, [
539 '$follow' => L10n::t('Follow'),
540 '$follow_link' => $follow_link,
541 '$unfollow' => L10n::t('Unfollow'),
542 '$unfollow_link' => $unfollow_link,
543 '$subscribe_feed' => L10n::t('Atom feed'),
544 '$subscribe_feed_link' => $subscribe_feed_link,
545 '$wallmessage' => L10n::t('Message'),
546 '$wallmessage_link' => $wallmessage_link,
547 '$account_type' => $account_type,
548 '$location' => $location,
549 '$gender' => $gender,
550 '$marital' => $marital,
551 '$homepage' => $homepage,
553 '$network' => L10n::t('Network:'),
554 '$contacts' => $contact_count,
555 '$updated' => $updated,
556 '$diaspora' => $diaspora,
557 '$contact_block' => $contact_block,
560 $arr = ['profile' => &$profile, 'entry' => &$o];
562 Hook::callAll('profile_sidebar', $arr);
567 public static function getBirthdays()
572 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
577 * $mobile_detect = new Mobile_Detect();
578 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
583 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
584 $bd_short = L10n::t('F d');
586 $cachekey = 'get_birthdays:' . local_user();
587 $r = Cache::get($cachekey);
590 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
592 ON `contact`.`id` = `event`.`cid`
593 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
594 AND NOT `contact`.`pending`
595 AND NOT `contact`.`hidden`
596 AND NOT `contact`.`blocked`
597 AND NOT `contact`.`archive`
598 AND NOT `contact`.`deleted`
599 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
600 ORDER BY `start` ASC ",
604 DateTimeFormat::utc('now + 6 days'),
605 DateTimeFormat::utcNow()
607 if (DBA::isResult($s)) {
608 $r = DBA::toArray($s);
609 Cache::set($cachekey, $r, Cache::HOUR);
615 if (DBA::isResult($r)) {
616 $now = strtotime('now');
620 foreach ($r as $rr) {
621 if (strlen($rr['name'])) {
624 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
628 $classtoday = $istoday ? ' birthday-today ' : '';
630 foreach ($r as &$rr) {
631 if (!strlen($rr['name'])) {
637 if (in_array($rr['cid'], $cids)) {
640 $cids[] = $rr['cid'];
642 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
644 $rr['link'] = Contact::magicLink($rr['url']);
645 $rr['title'] = $rr['name'];
646 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
647 $rr['startime'] = null;
648 $rr['today'] = $today;
652 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
653 return Renderer::replaceMacros($tpl, [
654 '$classtoday' => $classtoday,
656 '$event_reminders' => L10n::t('Birthday Reminders'),
657 '$event_title' => L10n::t('Birthdays this week:'),
659 '$lbr' => '{', // raw brackets mess up if/endif macro processing
664 public static function getEventsReminderHTML()
669 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
674 * $mobile_detect = new Mobile_Detect();
675 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
680 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
683 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
684 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
685 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
689 if (DBA::isResult($s)) {
693 while ($rr = DBA::fetch($s)) {
694 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
695 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
696 'visible' => true, 'deleted' => false];
697 if (!Item::exists($condition)) {
701 if (strlen($rr['summary'])) {
705 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
706 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
710 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
712 if (strlen($title) > 35) {
713 $title = substr($title, 0, 32) . '... ';
716 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
718 $description = L10n::t('[No description]');
721 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
723 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
727 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
729 $rr['title'] = $title;
730 $rr['description'] = $description;
731 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
732 $rr['startime'] = $strt;
733 $rr['today'] = $today;
738 $classtoday = (($istoday) ? 'event-today' : '');
740 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
741 return Renderer::replaceMacros($tpl, [
742 '$classtoday' => $classtoday,
743 '$count' => count($r),
744 '$event_reminders' => L10n::t('Event Reminders'),
745 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
750 public static function getAdvanced(App $a)
752 $uid = intval($a->profile['uid']);
754 if ($a->profile['name']) {
755 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
759 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
761 if (Feature::isEnabled($uid, 'profile_membersince')) {
762 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
765 if ($a->profile['gender']) {
766 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
769 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
770 $year_bd_format = L10n::t('j F, Y');
771 $short_bd_format = L10n::t('j F');
774 intval($a->profile['dob']) ?
775 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
776 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
779 $profile['birthday'] = [L10n::t('Birthday:'), $val];
782 if (!empty($a->profile['dob'])
783 && $a->profile['dob'] > DBA::NULL_DATE
784 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
786 $profile['age'] = [L10n::t('Age:'), $age];
789 if ($a->profile['marital']) {
790 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
793 /// @TODO Maybe use x() here, plus below?
794 if ($a->profile['with']) {
795 $profile['marital']['with'] = $a->profile['with'];
798 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
799 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
802 if ($a->profile['sexual']) {
803 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
806 if ($a->profile['homepage']) {
807 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
810 if ($a->profile['hometown']) {
811 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
814 if ($a->profile['pub_keywords']) {
815 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
818 if ($a->profile['politic']) {
819 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
822 if ($a->profile['religion']) {
823 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
826 if ($txt = BBCode::convert($a->profile['about'])) {
827 $profile['about'] = [L10n::t('About:'), $txt];
830 if ($txt = BBCode::convert($a->profile['interest'])) {
831 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
834 if ($txt = BBCode::convert($a->profile['likes'])) {
835 $profile['likes'] = [L10n::t('Likes:'), $txt];
838 if ($txt = BBCode::convert($a->profile['dislikes'])) {
839 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
842 if ($txt = BBCode::convert($a->profile['contact'])) {
843 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
846 if ($txt = BBCode::convert($a->profile['music'])) {
847 $profile['music'] = [L10n::t('Musical interests:'), $txt];
850 if ($txt = BBCode::convert($a->profile['book'])) {
851 $profile['book'] = [L10n::t('Books, literature:'), $txt];
854 if ($txt = BBCode::convert($a->profile['tv'])) {
855 $profile['tv'] = [L10n::t('Television:'), $txt];
858 if ($txt = BBCode::convert($a->profile['film'])) {
859 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
862 if ($txt = BBCode::convert($a->profile['romance'])) {
863 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
866 if ($txt = BBCode::convert($a->profile['work'])) {
867 $profile['work'] = [L10n::t('Work/employment:'), $txt];
870 if ($txt = BBCode::convert($a->profile['education'])) {
871 $profile['education'] = [L10n::t('School/education:'), $txt];
874 //show subcribed forum if it is enabled in the usersettings
875 if (Feature::isEnabled($uid, 'forumlist_profile')) {
876 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
879 if ($a->profile['uid'] == local_user()) {
880 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
883 return Renderer::replaceMacros($tpl, [
884 '$title' => L10n::t('Profile'),
885 '$basic' => L10n::t('Basic'),
886 '$advanced' => L10n::t('Advanced'),
887 '$profile' => $profile
896 * @param string $current
897 * @param bool $is_owner
898 * @param string $nickname
900 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
904 if (is_null($nickname)) {
905 $nickname = $a->user['nickname'];
908 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
912 'label' => L10n::t('Status'),
913 'url' => $baseProfileUrl,
914 'sel' => !$current ? 'active' : '',
915 'title' => L10n::t('Status Messages and Posts'),
916 'id' => 'status-tab',
920 'label' => L10n::t('Profile'),
921 'url' => $baseProfileUrl . '/?tab=profile',
922 'sel' => $current == 'profile' ? 'active' : '',
923 'title' => L10n::t('Profile Details'),
924 'id' => 'profile-tab',
928 'label' => L10n::t('Photos'),
929 'url' => DI::baseUrl() . '/photos/' . $nickname,
930 'sel' => $current == 'photos' ? 'active' : '',
931 'title' => L10n::t('Photo Albums'),
936 'label' => L10n::t('Videos'),
937 'url' => DI::baseUrl() . '/videos/' . $nickname,
938 'sel' => $current == 'videos' ? 'active' : '',
939 'title' => L10n::t('Videos'),
945 // the calendar link for the full featured events calendar
946 if ($is_owner && $a->theme_events_in_profile) {
948 'label' => L10n::t('Events'),
949 'url' => DI::baseUrl() . '/events',
950 'sel' => $current == 'events' ? 'active' : '',
951 'title' => L10n::t('Events and Calendar'),
952 'id' => 'events-tab',
955 // if the user is not the owner of the calendar we only show a calendar
956 // with the public events of the calendar owner
957 } elseif (!$is_owner) {
959 'label' => L10n::t('Events'),
960 'url' => DI::baseUrl() . '/cal/' . $nickname,
961 'sel' => $current == 'cal' ? 'active' : '',
962 'title' => L10n::t('Events and Calendar'),
963 'id' => 'events-tab',
970 'label' => L10n::t('Personal Notes'),
971 'url' => DI::baseUrl() . '/notes',
972 'sel' => $current == 'notes' ? 'active' : '',
973 'title' => L10n::t('Only You Can See This'),
979 if (!empty($_SESSION['new_member']) && $is_owner) {
981 'label' => L10n::t('Tips for New Members'),
982 'url' => DI::baseUrl() . '/newmember',
984 'title' => L10n::t('Tips for New Members'),
985 'id' => 'newmember-tab',
989 if ($is_owner || empty($a->profile['hide-friends'])) {
991 'label' => L10n::t('Contacts'),
992 'url' => $baseProfileUrl . '/contacts',
993 'sel' => $current == 'contacts' ? 'active' : '',
994 'title' => L10n::t('Contacts'),
995 'id' => 'viewcontacts-tab',
1000 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
1001 Hook::callAll('profile_tabs', $arr);
1003 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1005 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1009 * Retrieves the my_url session variable
1013 public static function getMyURL()
1015 return Session::get('my_url');
1019 * Process the 'zrl' parameter and initiate the remote authentication.
1021 * This method checks if the visitor has a public contact entry and
1022 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1025 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1027 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
1028 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
1029 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
1031 * It would be favourable to harmonize the two implementations.
1033 * @param App $a Application instance.
1034 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1035 * @throws \ImagickException
1037 public static function zrlInit(App $a)
1039 $my_url = self::getMyURL();
1040 $my_url = Network::isUrlValid($my_url);
1042 if (empty($my_url) || local_user()) {
1046 $addr = $_GET['addr'] ?? $my_url;
1048 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1049 Hook::callAll('zrl_init', $arr);
1051 // Try to find the public contact entry of the visitor.
1052 $cid = Contact::getIdForURL($my_url);
1054 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1058 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1060 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1061 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1065 // Avoid endless loops
1066 $cachekey = 'zrlInit:' . $my_url;
1067 if (Cache::get($cachekey)) {
1068 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1071 Cache::set($cachekey, true, Cache::MINUTE);
1074 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1076 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1077 $addr_request = 'addr=' . urlencode($addr);
1078 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1080 // The other instance needs to know where to redirect.
1081 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1083 // We need to extract the basebath from the profile url
1084 // to redirect the visitors '/magic' module.
1085 $basepath = Contact::getBasepath($contact['url']);
1087 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1088 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1090 // We have to check if the remote server does understand /magic without invoking something
1091 $serverret = Network::curl($basepath . '/magic');
1092 if ($serverret->isSuccess()) {
1093 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1094 System::externalRedirect($magic_path);
1100 * Set the visitor cookies (see remote_user()) for the given handle
1102 * @param string $handle Visitor handle
1103 * @return array Visitor contact array
1105 public static function addVisitorCookieForHandle($handle)
1109 // Try to find the public contact entry of the visitor.
1110 $cid = Contact::getIdForURL($handle);
1112 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1116 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1118 // Authenticate the visitor.
1119 $_SESSION['authenticated'] = 1;
1120 $_SESSION['visitor_id'] = $visitor['id'];
1121 $_SESSION['visitor_handle'] = $visitor['addr'];
1122 $_SESSION['visitor_home'] = $visitor['url'];
1123 $_SESSION['my_url'] = $visitor['url'];
1125 Session::setVisitorsContacts();
1127 $a->contact = $visitor;
1129 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1135 * OpenWebAuth authentication.
1137 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1139 * @param string $token
1140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1141 * @throws \ImagickException
1143 public static function openWebAuthInit($token)
1147 // Clean old OpenWebAuthToken entries.
1148 OpenWebAuthToken::purge('owt', '3 MINUTE');
1150 // Check if the token we got is the same one
1151 // we have stored in the database.
1152 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1154 if ($visitor_handle === false) {
1158 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1159 if (empty($visitor)) {
1164 'visitor' => $visitor,
1165 'url' => DI::args()->getQueryString()
1168 * @hooks magic_auth_success
1169 * Called when a magic-auth was successful.
1170 * * \e array \b visitor
1171 * * \e string \b url
1173 Hook::callAll('magic_auth_success', $arr);
1175 $a->contact = $arr['visitor'];
1177 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1179 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1182 public static function zrl($s, $force = false)
1187 if (!strpos($s, '/profile/') && !$force) {
1190 if ($force && substr($s, -1, 1) !== '/') {
1193 $achar = strpos($s, '?') ? '&' : '?';
1194 $mine = self::getMyURL();
1195 if ($mine && !Strings::compareLink($mine, $s)) {
1196 return $s . $achar . 'zrl=' . urlencode($mine);
1202 * Get the user ID of the page owner.
1204 * Used from within PCSS themes to set theme parameters. If there's a
1205 * profile_uid variable set in App, that is the "page owner" and normally their theme
1206 * settings take precedence; unless a local user sets the "always_my_theme"
1207 * system pconfig, which means they don't want to see anybody else's theme
1208 * settings except their own while on this site.
1210 * @brief Get the user ID of the page owner
1211 * @return int user ID
1213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1214 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1216 public static function getThemeUid(App $a)
1218 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1219 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1220 return local_user();
1227 * search for Profiles
1231 * @param null $search
1233 * @return array [ 'total' => 123, 'entries' => [...] ];
1235 * @throws \Exception
1237 public static function searchProfiles($start = 0, $count = 100, $search = null)
1239 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1242 if (!empty($search)) {
1243 $searchTerm = '%' . $search . '%';
1244 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1246 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1247 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1248 AND ((`profile`.`name` LIKE ?) OR
1249 (`user`.`nickname` LIKE ?) OR
1250 (`profile`.`pdesc` LIKE ?) OR
1251 (`profile`.`locality` LIKE ?) OR
1252 (`profile`.`region` LIKE ?) OR
1253 (`profile`.`country-name` LIKE ?) OR
1254 (`profile`.`gender` LIKE ?) OR
1255 (`profile`.`marital` LIKE ?) OR
1256 (`profile`.`sexual` LIKE ?) OR
1257 (`profile`.`about` LIKE ?) OR
1258 (`profile`.`romance` LIKE ?) OR
1259 (`profile`.`work` LIKE ?) OR
1260 (`profile`.`education` LIKE ?) OR
1261 (`profile`.`pub_keywords` LIKE ?) OR
1262 (`profile`.`prv_keywords` LIKE ?))",
1263 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1264 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1266 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1268 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1269 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1272 if (DBA::isResult($cnt)) {
1273 $total = $cnt['total'];
1276 $order = " ORDER BY `name` ASC ";
1279 // If nothing found, don't try to select details
1281 if (!empty($search)) {
1282 $searchTerm = '%' . $search . '%';
1284 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1285 `contact`.`addr`, `contact`.`url` AS `profile_url`
1287 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1288 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1289 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1290 AND ((`profile`.`name` LIKE ?) OR
1291 (`user`.`nickname` LIKE ?) OR
1292 (`profile`.`pdesc` LIKE ?) OR
1293 (`profile`.`locality` LIKE ?) OR
1294 (`profile`.`region` LIKE ?) OR
1295 (`profile`.`country-name` LIKE ?) OR
1296 (`profile`.`gender` LIKE ?) OR
1297 (`profile`.`marital` LIKE ?) OR
1298 (`profile`.`sexual` LIKE ?) OR
1299 (`profile`.`about` LIKE ?) OR
1300 (`profile`.`romance` LIKE ?) OR
1301 (`profile`.`work` LIKE ?) OR
1302 (`profile`.`education` LIKE ?) OR
1303 (`profile`.`pub_keywords` LIKE ?) OR
1304 (`profile`.`prv_keywords` LIKE ?))
1306 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1307 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1311 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1312 `contact`.`addr`, `contact`.`url` AS `profile_url`
1314 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1315 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1316 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1323 if (DBA::isResult($profiles) && $total > 0) {
1326 'entries' => DBA::toArray($profiles),