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\Core\Worker;
24 use Friendica\Database\DBA;
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 * @brief 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 * @brief Returns a formatted location string from the given profile array
51 * @param array $profile Profile array (Generated from the "profile" table)
53 * @return string Location string
55 public static function formatLocation(array $profile)
59 if (!empty($profile['locality'])) {
60 $location .= $profile['locality'];
63 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
68 $location .= $profile['region'];
71 if (!empty($profile['country-name'])) {
76 $location .= $profile['country-name'];
84 * Loads a profile into the page sidebar.
86 * The function requires a writeable copy of the main App structure, and the nickname
87 * of a registered local account.
89 * If the viewer is an authenticated remote viewer, the profile displayed is the
90 * one that has been configured for his/her viewing in the Contact manager.
91 * Passing a non-zero profile ID can also allow a preview of a selected profile
94 * Profile information is placed in the App structure for later retrieval.
95 * Honours the owner's chosen theme for display.
97 * @attention Should only be run in the _init() functions of a module. That ensures that
98 * the theme is chosen before the _init() function of a theme is run, which will usually
99 * load a lot of theme-specific content
101 * @brief Loads a profile into the page sidebar.
103 * @param string $nickname string
104 * @param int $profile int
105 * @param array $profiledata array
106 * @param boolean $show_connect Show connect link
107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
108 * @throws \ImagickException
110 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
112 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
114 if (!DBA::isResult($user) && empty($profiledata)) {
115 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
119 if (count($profiledata) > 0) {
120 // Add profile data to sidebar
121 $a->page['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
123 if (!DBA::isResult($user)) {
128 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
130 if (empty($pdata) && empty($profiledata)) {
131 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
136 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
139 // fetch user tags if this isn't the default profile
141 if (!$pdata['is-default']) {
142 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
143 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
144 if (DBA::isResult($profile)) {
145 $pdata['pub_keywords'] = $profile['pub_keywords'];
149 $a->profile = $pdata;
150 $a->profile_uid = $pdata['profile_uid'];
152 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
153 $a->profile['network'] = Protocol::DFRN;
155 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
157 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
158 $_SESSION['theme'] = $a->profile['theme'];
161 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
164 * load/reload current theme info
167 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
169 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
170 if (file_exists($theme_info_file)) {
171 require_once $theme_info_file;
174 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
175 $a->page['aside'] .= Renderer::replaceMacros(
176 Renderer::getMarkupTemplate('profile_edlink.tpl'),
178 '$editprofile' => L10n::t('Edit profile'),
179 '$profid' => $a->profile['id']
184 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
188 * By now, the contact block isn't shown, when a different profile is given
189 * But: When this profile was on the same server, then we could display the contacts
192 $a->page['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
199 * Get all profile data of a local user
201 * If the viewer is an authenticated remote viewer, the profile displayed is the
202 * one that has been configured for his/her viewing in the Contact manager.
203 * Passing a non-zero profile ID can also allow a preview of a selected profile
206 * Includes all available profile data
208 * @brief Get all profile data of a local user
209 * @param string $nickname nick
210 * @param int $uid uid
211 * @param int $profile_id ID of the profile
215 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
217 if (remote_user() && !empty($_SESSION['remote'])) {
218 foreach ($_SESSION['remote'] as $visitor) {
219 if ($visitor['uid'] == $uid) {
220 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
221 if (DBA::isResult($contact)) {
222 $profile_id = $contact['profile-id'];
232 $profile = DBA::fetchFirst(
233 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
234 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
235 `profile`.`uid` AS `profile_uid`, `profile`.*,
236 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
238 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
239 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
240 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
245 if (!DBA::isResult($profile)) {
246 $profile = DBA::fetchFirst(
247 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
248 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
249 `profile`.`uid` AS `profile_uid`, `profile`.*,
250 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
252 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
253 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
254 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
263 * Formats a profile for display in the sidebar.
265 * It is very difficult to templatise the HTML completely
266 * because of all the conditional logic.
268 * @brief Formats a profile for display in the sidebar.
269 * @param array $profile
271 * @param boolean $show_connect Show connect link
273 * @return string HTML sidebar module
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
277 * @note Returns empty string if passed $profile is wrong type or not populated
279 * @hooks 'profile_sidebar_enter'
280 * array $profile - profile data
281 * @hooks 'profile_sidebar'
284 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
289 // This function can also use contact information in $profile
290 $is_contact = !empty($profile['cid']);
292 if (!is_array($profile) && !count($profile)) {
296 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
298 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
299 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
301 $profile['network_link'] = '';
304 Hook::callAll('profile_sidebar_enter', $profile);
306 if (isset($profile['url'])) {
307 $profile_url = $profile['url'];
309 $profile_url = System::baseUrl() . '/profile/' . $profile['nickname'];
313 $unfollow_link = null;
314 $subscribe_feed_link = null;
315 $wallmessage_link = null;
319 $visitor_contact = [];
320 if ($profile['uid'] && self::getMyURL()) {
321 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
324 $profile_contact = [];
325 if ($profile['cid'] && self::getMyURL()) {
326 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
329 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
330 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
331 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
332 $visitor_is_authenticated = (bool)self::getMyURL();
333 $visitor_is_following =
334 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
335 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
336 $visitor_is_followed =
337 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
338 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
339 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
341 if (!$local_user_is_self) {
342 if (!$visitor_is_authenticated) {
343 $follow_link = 'dfrn_request/' . $profile['nickname'];
344 } elseif ($profile_is_native) {
345 if ($visitor_is_following) {
346 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
348 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
352 if ($profile_is_dfrn) {
353 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
356 if (Contact::canReceivePrivateMessages($profile)) {
357 if ($visitor_is_followed || $visitor_is_following) {
358 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode(defaults($profile, 'addr', ''));
359 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
360 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
365 // show edit profile to yourself
366 if (!$is_contact && $local_user_is_self) {
367 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
368 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
370 "SELECT * FROM `profile` WHERE `uid` = %d",
375 'chg_photo' => L10n::t('Change profile photo'),
376 'cr_new' => L10n::t('Create New Profile'),
380 if (DBA::isResult($r)) {
381 foreach ($r as $rr) {
382 $profile['menu']['entries'][] = [
383 'photo' => $rr['thumb'],
385 'alt' => L10n::t('Profile Image'),
386 'profile_name' => $rr['profile-name'],
387 'isdefault' => $rr['is-default'],
388 'visibile_to_everybody' => L10n::t('visible to everybody'),
389 'edit_visibility' => L10n::t('Edit visibility'),
394 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
396 'chg_photo' => L10n::t('Change profile photo'),
403 // Fetch the account type
404 $account_type = Contact::getAccountType($profile);
406 if (!empty($profile['address'])
407 || !empty($profile['location'])
408 || !empty($profile['locality'])
409 || !empty($profile['region'])
410 || !empty($profile['postal-code'])
411 || !empty($profile['country-name'])
413 $location = L10n::t('Location:');
416 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
417 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
418 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
419 $about = !empty($profile['about']) ? L10n::t('About:') : false;
420 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
422 if ((!empty($profile['hidewall']) || $block) && !local_user() && !remote_user()) {
423 $location = $gender = $marital = $homepage = $about = false;
426 $split_name = Diaspora::splitName($profile['name']);
427 $firstname = $split_name['first'];
428 $lastname = $split_name['last'];
430 if (!empty($profile['guid'])) {
432 'guid' => $profile['guid'],
433 'podloc' => System::baseUrl(),
434 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
435 'nickname' => $profile['nickname'],
436 'fullname' => $profile['name'],
437 'firstname' => $firstname,
438 'lastname' => $lastname,
439 'photo300' => defaults($profile, 'contact_photo', ''),
440 'photo100' => defaults($profile, 'contact_thumb', ''),
441 'photo50' => defaults($profile, 'contact_micro', ''),
451 $contact_block = ContactBlock::getHTML($a->profile);
453 if (is_array($a->profile) && !$a->profile['hide-friends']) {
455 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
456 intval($a->profile['uid'])
458 if (DBA::isResult($r)) {
459 $updated = date('c', strtotime($r[0]['updated']));
462 $contact_count = DBA::count('contact', [
463 'uid' => $profile['uid'],
469 'network' => [Protocol::DFRN, Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA],
475 foreach ($profile as $k => $v) {
476 $k = str_replace('-', '_', $k);
480 if (isset($p['about'])) {
481 $p['about'] = BBCode::convert($p['about']);
484 if (empty($p['address']) && !empty($p['location'])) {
485 $p['address'] = $p['location'];
488 if (isset($p['address'])) {
489 $p['address'] = BBCode::convert($p['address']);
492 if (isset($p['photo'])) {
493 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
496 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
498 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
499 $o .= Renderer::replaceMacros($tpl, [
502 '$follow' => L10n::t('Follow'),
503 '$follow_link' => $follow_link,
504 '$unfollow' => L10n::t('Unfollow'),
505 '$unfollow_link' => $unfollow_link,
506 '$subscribe_feed' => L10n::t('Atom feed'),
507 '$subscribe_feed_link' => $subscribe_feed_link,
508 '$wallmessage' => L10n::t('Message'),
509 '$wallmessage_link' => $wallmessage_link,
510 '$account_type' => $account_type,
511 '$location' => $location,
512 '$gender' => $gender,
513 '$marital' => $marital,
514 '$homepage' => $homepage,
516 '$network' => L10n::t('Network:'),
517 '$contacts' => $contact_count,
518 '$updated' => $updated,
519 '$diaspora' => $diaspora,
520 '$contact_block' => $contact_block,
523 $arr = ['profile' => &$profile, 'entry' => &$o];
525 Hook::callAll('profile_sidebar', $arr);
530 public static function getBirthdays()
535 if (!local_user() || $a->is_mobile || $a->is_tablet) {
540 * $mobile_detect = new Mobile_Detect();
541 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
546 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
547 $bd_short = L10n::t('F d');
549 $cachekey = 'get_birthdays:' . local_user();
550 $r = Cache::get($cachekey);
553 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
555 ON `contact`.`id` = `event`.`cid`
556 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
557 AND NOT `contact`.`pending`
558 AND NOT `contact`.`hidden`
559 AND NOT `contact`.`blocked`
560 AND NOT `contact`.`archive`
561 AND NOT `contact`.`deleted`
562 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
563 ORDER BY `start` ASC ",
567 DateTimeFormat::utc('now + 6 days'),
568 DateTimeFormat::utcNow()
570 if (DBA::isResult($s)) {
571 $r = DBA::toArray($s);
572 Cache::set($cachekey, $r, Cache::HOUR);
578 if (DBA::isResult($r)) {
579 $now = strtotime('now');
583 foreach ($r as $rr) {
584 if (strlen($rr['name'])) {
587 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
591 $classtoday = $istoday ? ' birthday-today ' : '';
593 foreach ($r as &$rr) {
594 if (!strlen($rr['name'])) {
600 if (in_array($rr['cid'], $cids)) {
603 $cids[] = $rr['cid'];
605 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
607 $rr['link'] = Contact::magicLink($rr['url']);
608 $rr['title'] = $rr['name'];
609 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
610 $rr['startime'] = null;
611 $rr['today'] = $today;
615 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
616 return Renderer::replaceMacros($tpl, [
617 '$classtoday' => $classtoday,
619 '$event_reminders' => L10n::t('Birthday Reminders'),
620 '$event_title' => L10n::t('Birthdays this week:'),
622 '$lbr' => '{', // raw brackets mess up if/endif macro processing
627 public static function getEventsReminderHTML()
632 if (!local_user() || $a->is_mobile || $a->is_tablet) {
637 * $mobile_detect = new Mobile_Detect();
638 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
643 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
646 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
647 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
648 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
652 if (DBA::isResult($s)) {
656 while ($rr = DBA::fetch($s)) {
657 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
658 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
659 'visible' => true, 'deleted' => false];
660 if (!Item::exists($condition)) {
664 if (strlen($rr['summary'])) {
668 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
669 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
673 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
675 if (strlen($title) > 35) {
676 $title = substr($title, 0, 32) . '... ';
679 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
681 $description = L10n::t('[No description]');
684 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
686 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
690 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
692 $rr['title'] = $title;
693 $rr['description'] = $description;
694 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
695 $rr['startime'] = $strt;
696 $rr['today'] = $today;
701 $classtoday = (($istoday) ? 'event-today' : '');
703 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
704 return Renderer::replaceMacros($tpl, [
705 '$classtoday' => $classtoday,
706 '$count' => count($r),
707 '$event_reminders' => L10n::t('Event Reminders'),
708 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
713 public static function getAdvanced(App $a)
715 $uid = $a->profile['uid'];
717 if ($a->profile['name']) {
718 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
722 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
724 if (Feature::isEnabled($uid, 'profile_membersince')) {
725 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
728 if ($a->profile['gender']) {
729 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
732 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
733 $year_bd_format = L10n::t('j F, Y');
734 $short_bd_format = L10n::t('j F');
737 intval($a->profile['dob']) ?
738 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
739 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
742 $profile['birthday'] = [L10n::t('Birthday:'), $val];
745 if (!empty($a->profile['dob'])
746 && $a->profile['dob'] > DBA::NULL_DATE
747 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
749 $profile['age'] = [L10n::t('Age:'), $age];
752 if ($a->profile['marital']) {
753 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
756 /// @TODO Maybe use x() here, plus below?
757 if ($a->profile['with']) {
758 $profile['marital']['with'] = $a->profile['with'];
761 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
762 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
765 if ($a->profile['sexual']) {
766 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
769 if ($a->profile['homepage']) {
770 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
773 if ($a->profile['hometown']) {
774 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
777 if ($a->profile['pub_keywords']) {
778 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
781 if ($a->profile['politic']) {
782 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
785 if ($a->profile['religion']) {
786 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
789 if ($txt = prepare_text($a->profile['about'])) {
790 $profile['about'] = [L10n::t('About:'), $txt];
793 if ($txt = prepare_text($a->profile['interest'])) {
794 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
797 if ($txt = prepare_text($a->profile['likes'])) {
798 $profile['likes'] = [L10n::t('Likes:'), $txt];
801 if ($txt = prepare_text($a->profile['dislikes'])) {
802 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
805 if ($txt = prepare_text($a->profile['contact'])) {
806 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
809 if ($txt = prepare_text($a->profile['music'])) {
810 $profile['music'] = [L10n::t('Musical interests:'), $txt];
813 if ($txt = prepare_text($a->profile['book'])) {
814 $profile['book'] = [L10n::t('Books, literature:'), $txt];
817 if ($txt = prepare_text($a->profile['tv'])) {
818 $profile['tv'] = [L10n::t('Television:'), $txt];
821 if ($txt = prepare_text($a->profile['film'])) {
822 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
825 if ($txt = prepare_text($a->profile['romance'])) {
826 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
829 if ($txt = prepare_text($a->profile['work'])) {
830 $profile['work'] = [L10n::t('Work/employment:'), $txt];
833 if ($txt = prepare_text($a->profile['education'])) {
834 $profile['education'] = [L10n::t('School/education:'), $txt];
837 //show subcribed forum if it is enabled in the usersettings
838 if (Feature::isEnabled($uid, 'forumlist_profile')) {
839 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
842 if ($a->profile['uid'] == local_user()) {
843 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
846 return Renderer::replaceMacros($tpl, [
847 '$title' => L10n::t('Profile'),
848 '$basic' => L10n::t('Basic'),
849 '$advanced' => L10n::t('Advanced'),
850 '$profile' => $profile
859 * @param string $current
860 * @param bool $is_owner
861 * @param string $nickname
863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
865 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
867 if (is_null($nickname)) {
868 $nickname = $a->user['nickname'];
871 $baseProfileUrl = System::baseUrl() . '/profile/' . $nickname;
875 'label' => L10n::t('Status'),
876 'url' => $baseProfileUrl,
877 'sel' => !$current ? 'active' : '',
878 'title' => L10n::t('Status Messages and Posts'),
879 'id' => 'status-tab',
883 'label' => L10n::t('Profile'),
884 'url' => $baseProfileUrl . '/?tab=profile',
885 'sel' => $current == 'profile' ? 'active' : '',
886 'title' => L10n::t('Profile Details'),
887 'id' => 'profile-tab',
891 'label' => L10n::t('Photos'),
892 'url' => System::baseUrl() . '/photos/' . $nickname,
893 'sel' => $current == 'photos' ? 'active' : '',
894 'title' => L10n::t('Photo Albums'),
899 'label' => L10n::t('Videos'),
900 'url' => System::baseUrl() . '/videos/' . $nickname,
901 'sel' => $current == 'videos' ? 'active' : '',
902 'title' => L10n::t('Videos'),
908 // the calendar link for the full featured events calendar
909 if ($is_owner && $a->theme_events_in_profile) {
911 'label' => L10n::t('Events'),
912 'url' => System::baseUrl() . '/events',
913 'sel' => $current == 'events' ? 'active' : '',
914 'title' => L10n::t('Events and Calendar'),
915 'id' => 'events-tab',
918 // if the user is not the owner of the calendar we only show a calendar
919 // with the public events of the calendar owner
920 } elseif (!$is_owner) {
922 'label' => L10n::t('Events'),
923 'url' => System::baseUrl() . '/cal/' . $nickname,
924 'sel' => $current == 'cal' ? 'active' : '',
925 'title' => L10n::t('Events and Calendar'),
926 'id' => 'events-tab',
933 'label' => L10n::t('Personal Notes'),
934 'url' => System::baseUrl() . '/notes',
935 'sel' => $current == 'notes' ? 'active' : '',
936 'title' => L10n::t('Only You Can See This'),
942 if (!empty($_SESSION['new_member']) && $is_owner) {
944 'label' => L10n::t('Tips for New Members'),
945 'url' => System::baseUrl() . '/newmember',
947 'title' => L10n::t('Tips for New Members'),
948 'id' => 'newmember-tab',
952 if ($is_owner || empty($a->profile['hide-friends'])) {
954 'label' => L10n::t('Contacts'),
955 'url' => $baseProfileUrl . '/contacts',
956 'sel' => $current == 'contacts' ? 'active' : '',
957 'title' => L10n::t('Contacts'),
958 'id' => 'viewcontacts-tab',
963 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
964 Hook::callAll('profile_tabs', $arr);
966 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
968 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
972 * Retrieves the my_url session variable
976 public static function getMyURL()
978 return Session::get('my_url');
982 * Process the 'zrl' parameter and initiate the remote authentication.
984 * This method checks if the visitor has a public contact entry and
985 * redirects the visitor to his/her instance to start the magic auth (Authentication)
988 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
990 * @param App $a Application instance.
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 * @throws \ImagickException
994 public static function zrlInit(App $a)
996 $my_url = self::getMyURL();
997 $my_url = Network::isUrlValid($my_url);
999 if (empty($my_url) || local_user()) {
1003 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1004 Hook::callAll('zrl_init', $arr);
1006 // Try to find the public contact entry of the visitor.
1007 $cid = Contact::getIdForURL($my_url);
1009 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1013 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1015 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1016 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1020 // Avoid endless loops
1021 $cachekey = 'zrlInit:' . $my_url;
1022 if (Cache::get($cachekey)) {
1023 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1026 Cache::set($cachekey, true, Cache::MINUTE);
1029 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1031 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1033 // Try to avoid recursion - but send them home to do a proper magic auth.
1034 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1035 // The other instance needs to know where to redirect.
1036 $dest = urlencode($a->getBaseURL() . '/' . $query);
1038 // We need to extract the basebath from the profile url
1039 // to redirect the visitors '/magic' module.
1040 // Note: We should have the basepath of a contact also in the contact table.
1041 $urlarr = explode('/profile/', $contact['url']);
1042 $basepath = $urlarr[0];
1044 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1045 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1047 // We have to check if the remote server does understand /magic without invoking something
1048 $serverret = Network::curl($basepath . '/magic');
1049 if ($serverret->isSuccess()) {
1050 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1051 System::externalRedirect($magic_path);
1057 * Set the visitor cookies (see remote_user()) for the given handle
1059 * @param string $handle Visitor handle
1060 * @return array Visitor contact array
1062 public static function addVisitorCookieForHandle($handle)
1066 // Try to find the public contact entry of the visitor.
1067 $cid = Contact::getIdForURL($handle);
1069 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1073 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1075 // Authenticate the visitor.
1076 $_SESSION['authenticated'] = 1;
1077 $_SESSION['visitor_id'] = $visitor['id'];
1078 $_SESSION['visitor_handle'] = $visitor['addr'];
1079 $_SESSION['visitor_home'] = $visitor['url'];
1080 $_SESSION['my_url'] = $visitor['url'];
1082 /// @todo replace this and the query for this variable with some cleaner functionality
1083 $_SESSION['remote'] = [];
1085 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1086 while ($contact = DBA::fetch($remote_contacts)) {
1087 if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1091 $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
1094 $a->contact = $visitor;
1096 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1102 * OpenWebAuth authentication.
1104 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1106 * @param string $token
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1108 * @throws \ImagickException
1110 public static function openWebAuthInit($token)
1114 // Clean old OpenWebAuthToken entries.
1115 OpenWebAuthToken::purge('owt', '3 MINUTE');
1117 // Check if the token we got is the same one
1118 // we have stored in the database.
1119 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1121 if ($visitor_handle === false) {
1125 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1126 if (empty($visitor)) {
1131 'visitor' => $visitor,
1132 'url' => $a->query_string
1135 * @hooks magic_auth_success
1136 * Called when a magic-auth was successful.
1137 * * \e array \b visitor
1138 * * \e string \b url
1140 Hook::callAll('magic_auth_success', $arr);
1142 $a->contact = $arr['visitor'];
1144 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1146 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1149 public static function zrl($s, $force = false)
1154 if ((!strpos($s, '/profile/')) && (!$force)) {
1157 if ($force && substr($s, -1, 1) !== '/') {
1160 $achar = strpos($s, '?') ? '&' : '?';
1161 $mine = self::getMyURL();
1162 if ($mine && !Strings::compareLink($mine, $s)) {
1163 return $s . $achar . 'zrl=' . urlencode($mine);
1169 * Get the user ID of the page owner.
1171 * Used from within PCSS themes to set theme parameters. If there's a
1172 * profile_uid variable set in App, that is the "page owner" and normally their theme
1173 * settings take precedence; unless a local user sets the "always_my_theme"
1174 * system pconfig, which means they don't want to see anybody else's theme
1175 * settings except their own while on this site.
1177 * @brief Get the user ID of the page owner
1178 * @return int user ID
1180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1181 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1183 public static function getThemeUid(App $a)
1185 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1186 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1187 return local_user();
1194 * Strip zrl parameter from a string.
1196 * @param string $s The input string.
1197 * @return string The zrl.
1199 public static function stripZrls($s)
1201 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1205 * Strip query parameter from a string.
1207 * @param string $s The input string.
1209 * @return string The query parameter.
1211 public static function stripQueryParam($s, $param)
1213 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1217 * search for Profiles
1221 * @param null $search
1223 * @return array [ 'total' => 123, 'entries' => [...] ];
1225 * @throws \Exception
1227 public static function searchProfiles($start = 0, $count = 100, $search = null)
1229 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1232 if (!empty($search)) {
1233 $searchTerm = '%' . $search . '%';
1234 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1236 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1237 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1238 AND ((`profile`.`name` LIKE ?) OR
1239 (`user`.`nickname` LIKE ?) OR
1240 (`profile`.`pdesc` LIKE ?) OR
1241 (`profile`.`locality` LIKE ?) OR
1242 (`profile`.`region` LIKE ?) OR
1243 (`profile`.`country-name` LIKE ?) OR
1244 (`profile`.`gender` LIKE ?) OR
1245 (`profile`.`marital` LIKE ?) OR
1246 (`profile`.`sexual` LIKE ?) OR
1247 (`profile`.`about` LIKE ?) OR
1248 (`profile`.`romance` LIKE ?) OR
1249 (`profile`.`work` LIKE ?) OR
1250 (`profile`.`education` LIKE ?) OR
1251 (`profile`.`pub_keywords` LIKE ?) OR
1252 (`profile`.`prv_keywords` LIKE ?))",
1253 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1254 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1256 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1258 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1259 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1262 if (DBA::isResult($cnt)) {
1263 $total = $cnt['total'];
1266 $order = " ORDER BY `name` ASC ";
1269 // If nothing found, don't try to select details
1271 if (!empty($search)) {
1272 $searchTerm = '%' . $search . '%';
1274 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1275 `contact`.`addr`, `contact`.`url` AS `profile_url`
1277 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1278 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1279 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1280 AND ((`profile`.`name` LIKE ?) OR
1281 (`user`.`nickname` LIKE ?) OR
1282 (`profile`.`pdesc` LIKE ?) OR
1283 (`profile`.`locality` LIKE ?) OR
1284 (`profile`.`region` LIKE ?) OR
1285 (`profile`.`country-name` LIKE ?) OR
1286 (`profile`.`gender` LIKE ?) OR
1287 (`profile`.`marital` LIKE ?) OR
1288 (`profile`.`sexual` LIKE ?) OR
1289 (`profile`.`about` LIKE ?) OR
1290 (`profile`.`romance` LIKE ?) OR
1291 (`profile`.`work` LIKE ?) OR
1292 (`profile`.`education` LIKE ?) OR
1293 (`profile`.`pub_keywords` LIKE ?) OR
1294 (`profile`.`prv_keywords` LIKE ?))
1296 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1297 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1301 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1302 `contact`.`addr`, `contact`.`url` AS `profile_url`
1304 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1305 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1306 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1313 if (DBA::isResult($profiles) && $total > 0) {
1316 'entries' => DBA::toArray($profiles),