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\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
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 * @brief 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 * @brief Returns a formatted location string from the given profile array
50 * @param array $profile Profile array (Generated from the "profile" table)
52 * @return string Location string
54 public static function formatLocation(array $profile)
58 if (!empty($profile['locality'])) {
59 $location .= $profile['locality'];
62 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
67 $location .= $profile['region'];
70 if (!empty($profile['country-name'])) {
75 $location .= $profile['country-name'];
83 * Loads a profile into the page sidebar.
85 * The function requires a writeable copy of the main App structure, and the nickname
86 * of a registered local account.
88 * If the viewer is an authenticated remote viewer, the profile displayed is the
89 * one that has been configured for his/her viewing in the Contact manager.
90 * Passing a non-zero profile ID can also allow a preview of a selected profile
93 * Profile information is placed in the App structure for later retrieval.
94 * Honours the owner's chosen theme for display.
96 * @attention Should only be run in the _init() functions of a module. That ensures that
97 * the theme is chosen before the _init() function of a theme is run, which will usually
98 * load a lot of theme-specific content
100 * @brief Loads a profile into the page sidebar.
102 * @param string $nickname string
103 * @param int $profile int
104 * @param array $profiledata array
105 * @param boolean $show_connect Show connect link
106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
107 * @throws \ImagickException
109 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
111 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
113 if (!DBA::isResult($user) && empty($profiledata)) {
114 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
115 notice(L10n::t('Requested account is not available.') . EOL);
120 if (count($profiledata) > 0) {
121 // Add profile data to sidebar
122 $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
124 if (!DBA::isResult($user)) {
129 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
131 if (empty($pdata) && empty($profiledata)) {
132 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
133 notice(L10n::t('Requested profile is not available.') . EOL);
139 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
142 // fetch user tags if this isn't the default profile
144 if (!$pdata['is-default']) {
145 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
146 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
147 if (DBA::isResult($profile)) {
148 $pdata['pub_keywords'] = $profile['pub_keywords'];
152 $a->profile = $pdata;
153 $a->profile_uid = $pdata['profile_uid'];
155 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
156 $a->profile['network'] = Protocol::DFRN;
158 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
160 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
161 $_SESSION['theme'] = $a->profile['theme'];
164 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
167 * load/reload current theme info
170 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
172 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
173 if (file_exists($theme_info_file)) {
174 require_once $theme_info_file;
177 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
178 $a->page['aside'] .= Renderer::replaceMacros(
179 Renderer::getMarkupTemplate('profile_edlink.tpl'),
181 '$editprofile' => L10n::t('Edit profile'),
182 '$profid' => $a->profile['id']
187 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
191 * By now, the contact block isn't shown, when a different profile is given
192 * But: When this profile was on the same server, then we could display the contacts
195 $a->page['aside'] .= self::sidebar($a->profile, $block, $show_connect);
202 * Get all profile data of a local user
204 * If the viewer is an authenticated remote viewer, the profile displayed is the
205 * one that has been configured for his/her viewing in the Contact manager.
206 * Passing a non-zero profile ID can also allow a preview of a selected profile
209 * Includes all available profile data
211 * @brief Get all profile data of a local user
212 * @param string $nickname nick
213 * @param int $uid uid
214 * @param int $profile_id ID of the profile
218 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
220 if (remote_user() && !empty($_SESSION['remote'])) {
221 foreach ($_SESSION['remote'] as $visitor) {
222 if ($visitor['uid'] == $uid) {
223 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
224 if (DBA::isResult($contact)) {
225 $profile_id = $contact['profile-id'];
235 $profile = DBA::fetchFirst(
236 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
237 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
238 `profile`.`uid` AS `profile_uid`, `profile`.*,
239 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
241 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
242 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
243 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
248 if (!DBA::isResult($profile)) {
249 $profile = DBA::fetchFirst(
250 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
251 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
252 `profile`.`uid` AS `profile_uid`, `profile`.*,
253 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
255 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
256 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
257 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
266 * Formats a profile for display in the sidebar.
268 * It is very difficult to templatise the HTML completely
269 * because of all the conditional logic.
271 * @brief Formats a profile for display in the sidebar.
272 * @param array $profile
274 * @param boolean $show_connect Show connect link
276 * @return string HTML sidebar module
278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 * @throws \ImagickException
280 * @note Returns empty string if passed $profile is wrong type or not populated
282 * @hooks 'profile_sidebar_enter'
283 * array $profile - profile data
284 * @hooks 'profile_sidebar'
287 private static function sidebar($profile, $block = 0, $show_connect = true)
294 // This function can also use contact information in $profile
295 $is_contact = !empty($profile['cid']);
297 if (!is_array($profile) && !count($profile)) {
301 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
303 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
304 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
306 $profile['network_link'] = '';
309 Hook::callAll('profile_sidebar_enter', $profile);
312 // don't show connect link to yourself
313 $connect = $profile['uid'] != local_user() ? L10n::t('Connect') : false;
315 // don't show connect link to authenticated visitors either
316 if (remote_user() && !empty($_SESSION['remote'])) {
317 foreach ($_SESSION['remote'] as $visitor) {
318 if ($visitor['uid'] == $profile['uid']) {
325 if (!$show_connect) {
331 // Is the local user already connected to that user?
332 if ($connect && local_user()) {
333 if (isset($profile['url'])) {
334 $profile_url = Strings::normaliseLink($profile['url']);
336 $profile_url = Strings::normaliseLink(System::baseUrl() . '/profile/' . $profile['nickname']);
339 if (DBA::exists('contact', ['pending' => false, 'uid' => local_user(), 'nurl' => $profile_url])) {
344 // Is the remote user already connected to that user?
345 if ($connect && Contact::isFollower(remote_user(), $profile['uid'])) {
349 if ($connect && ($profile['network'] != Protocol::DFRN) && !isset($profile['remoteconnect'])) {
353 $remoteconnect = null;
354 if (isset($profile['remoteconnect'])) {
355 $remoteconnect = $profile['remoteconnect'];
358 if ($connect && ($profile['network'] == Protocol::DFRN) && !isset($remoteconnect)) {
359 $subscribe_feed = L10n::t('Atom feed');
361 $subscribe_feed = false;
364 $wallmessage = false;
365 $wallmessage_link = false;
367 // See issue https://github.com/friendica/friendica/issues/3838
368 // Either we remove the message link for remote users or we enable creating messages from remote users
369 if (remote_user() || (self::getMyURL() && !empty($profile['unkmail']) && ($profile['uid'] != local_user()))) {
370 $wallmessage = L10n::t('Message');
374 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
375 intval($profile['uid']),
376 intval(remote_user()),
377 intval(Contact::FRIEND)
381 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
382 intval($profile['uid']),
383 DBA::escape(Strings::normaliseLink(self::getMyURL())),
384 intval(Contact::FRIEND)
388 $remote_url = $r[0]['url'];
389 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
390 $wallmessage_link = $message_path . base64_encode(defaults($profile, 'addr', ''));
391 } else if (!empty($profile['nickname'])) {
392 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
396 // show edit profile to yourself
397 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
398 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
400 "SELECT * FROM `profile` WHERE `uid` = %d",
405 'chg_photo' => L10n::t('Change profile photo'),
406 'cr_new' => L10n::t('Create New Profile'),
410 if (DBA::isResult($r)) {
411 foreach ($r as $rr) {
412 $profile['menu']['entries'][] = [
413 'photo' => $rr['thumb'],
415 'alt' => L10n::t('Profile Image'),
416 'profile_name' => $rr['profile-name'],
417 'isdefault' => $rr['is-default'],
418 'visibile_to_everybody' => L10n::t('visible to everybody'),
419 'edit_visibility' => L10n::t('Edit visibility'),
424 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
425 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
427 'chg_photo' => L10n::t('Change profile photo'),
433 // Fetch the account type
434 $account_type = Contact::getAccountType($profile);
436 if (!empty($profile['address'])
437 || !empty($profile['location'])
438 || !empty($profile['locality'])
439 || !empty($profile['region'])
440 || !empty($profile['postal-code'])
441 || !empty($profile['country-name'])
443 $location = L10n::t('Location:');
446 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
447 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
448 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
449 $about = !empty($profile['about']) ? L10n::t('About:') : false;
450 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
452 if ((!empty($profile['hidewall']) || $block) && !local_user() && !remote_user()) {
453 $location = $gender = $marital = $homepage = $about = false;
456 $split_name = Diaspora::splitName($profile['name']);
457 $firstname = $split_name['first'];
458 $lastname = $split_name['last'];
460 if (!empty($profile['guid'])) {
462 'guid' => $profile['guid'],
463 'podloc' => System::baseUrl(),
464 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
465 'nickname' => $profile['nickname'],
466 'fullname' => $profile['name'],
467 'firstname' => $firstname,
468 'lastname' => $lastname,
469 'photo300' => defaults($profile, 'contact_photo', ''),
470 'photo100' => defaults($profile, 'contact_thumb', ''),
471 'photo50' => defaults($profile, 'contact_micro', ''),
481 $contact_block = ContactBlock::getHTML($a->profile);
483 if (is_array($a->profile) && !$a->profile['hide-friends']) {
485 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
486 intval($a->profile['uid'])
488 if (DBA::isResult($r)) {
489 $updated = date('c', strtotime($r[0]['updated']));
492 $contact_count = DBA::count('contact', [
493 'uid' => $profile['uid'],
499 'network' => [Protocol::DFRN, Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA],
505 foreach ($profile as $k => $v) {
506 $k = str_replace('-', '_', $k);
510 if (isset($p['about'])) {
511 $p['about'] = BBCode::convert($p['about']);
514 if (empty($p['address']) && !empty($p['location'])) {
515 $p['address'] = $p['location'];
518 if (isset($p['address'])) {
519 $p['address'] = BBCode::convert($p['address']);
522 if (isset($p['photo'])) {
523 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
526 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
528 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
529 $o .= Renderer::replaceMacros($tpl, [
532 '$connect' => $connect,
533 '$remoteconnect' => $remoteconnect,
534 '$subscribe_feed' => $subscribe_feed,
535 '$wallmessage' => $wallmessage,
536 '$wallmessage_link' => $wallmessage_link,
537 '$account_type' => $account_type,
538 '$location' => $location,
539 '$gender' => $gender,
540 '$marital' => $marital,
541 '$homepage' => $homepage,
543 '$network' => L10n::t('Network:'),
544 '$contacts' => $contact_count,
545 '$updated' => $updated,
546 '$diaspora' => $diaspora,
547 '$contact_block' => $contact_block,
550 $arr = ['profile' => &$profile, 'entry' => &$o];
552 Hook::callAll('profile_sidebar', $arr);
557 public static function getBirthdays()
562 if (!local_user() || $a->is_mobile || $a->is_tablet) {
567 * $mobile_detect = new Mobile_Detect();
568 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
573 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
574 $bd_short = L10n::t('F d');
576 $cachekey = 'get_birthdays:' . local_user();
577 $r = Cache::get($cachekey);
580 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
582 ON `contact`.`id` = `event`.`cid`
583 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
584 AND NOT `contact`.`pending`
585 AND NOT `contact`.`hidden`
586 AND NOT `contact`.`blocked`
587 AND NOT `contact`.`archive`
588 AND NOT `contact`.`deleted`
589 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
590 ORDER BY `start` ASC ",
594 DateTimeFormat::utc('now + 6 days'),
595 DateTimeFormat::utcNow()
597 if (DBA::isResult($s)) {
598 $r = DBA::toArray($s);
599 Cache::set($cachekey, $r, Cache::HOUR);
605 if (DBA::isResult($r)) {
606 $now = strtotime('now');
610 foreach ($r as $rr) {
611 if (strlen($rr['name'])) {
614 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
618 $classtoday = $istoday ? ' birthday-today ' : '';
620 foreach ($r as &$rr) {
621 if (!strlen($rr['name'])) {
627 if (in_array($rr['cid'], $cids)) {
630 $cids[] = $rr['cid'];
632 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
634 $rr['link'] = Contact::magicLink($rr['url']);
635 $rr['title'] = $rr['name'];
636 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
637 $rr['startime'] = null;
638 $rr['today'] = $today;
642 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
643 return Renderer::replaceMacros($tpl, [
644 '$baseurl' => System::baseUrl(),
645 '$classtoday' => $classtoday,
647 '$event_reminders' => L10n::t('Birthday Reminders'),
648 '$event_title' => L10n::t('Birthdays this week:'),
650 '$lbr' => '{', // raw brackets mess up if/endif macro processing
655 public static function getEventsReminderHTML()
660 if (!local_user() || $a->is_mobile || $a->is_tablet) {
665 * $mobile_detect = new Mobile_Detect();
666 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
671 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
674 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
675 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
676 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
680 if (DBA::isResult($s)) {
684 while ($rr = DBA::fetch($s)) {
685 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
686 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
687 'visible' => true, 'deleted' => false];
688 if (!Item::exists($condition)) {
692 if (strlen($rr['summary'])) {
696 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
697 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
701 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
703 if (strlen($title) > 35) {
704 $title = substr($title, 0, 32) . '... ';
707 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
709 $description = L10n::t('[No description]');
712 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
714 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
718 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
720 $rr['title'] = $title;
721 $rr['description'] = $description;
722 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
723 $rr['startime'] = $strt;
724 $rr['today'] = $today;
729 $classtoday = (($istoday) ? 'event-today' : '');
731 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
732 return Renderer::replaceMacros($tpl, [
733 '$baseurl' => System::baseUrl(),
734 '$classtoday' => $classtoday,
735 '$count' => count($r),
736 '$event_reminders' => L10n::t('Event Reminders'),
737 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
742 public static function getAdvanced(App $a)
744 $uid = $a->profile['uid'];
746 if ($a->profile['name']) {
747 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
751 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
753 if (Feature::isEnabled($uid, 'profile_membersince')) {
754 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
757 if ($a->profile['gender']) {
758 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
761 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
762 $year_bd_format = L10n::t('j F, Y');
763 $short_bd_format = L10n::t('j F');
766 intval($a->profile['dob']) ?
767 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
768 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
771 $profile['birthday'] = [L10n::t('Birthday:'), $val];
774 if (!empty($a->profile['dob'])
775 && $a->profile['dob'] > DBA::NULL_DATE
776 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
778 $profile['age'] = [L10n::t('Age:'), $age];
781 if ($a->profile['marital']) {
782 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
785 /// @TODO Maybe use x() here, plus below?
786 if ($a->profile['with']) {
787 $profile['marital']['with'] = $a->profile['with'];
790 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
791 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
794 if ($a->profile['sexual']) {
795 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
798 if ($a->profile['homepage']) {
799 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
802 if ($a->profile['hometown']) {
803 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
806 if ($a->profile['pub_keywords']) {
807 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
810 if ($a->profile['politic']) {
811 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
814 if ($a->profile['religion']) {
815 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
818 if ($txt = prepare_text($a->profile['about'])) {
819 $profile['about'] = [L10n::t('About:'), $txt];
822 if ($txt = prepare_text($a->profile['interest'])) {
823 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
826 if ($txt = prepare_text($a->profile['likes'])) {
827 $profile['likes'] = [L10n::t('Likes:'), $txt];
830 if ($txt = prepare_text($a->profile['dislikes'])) {
831 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
834 if ($txt = prepare_text($a->profile['contact'])) {
835 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
838 if ($txt = prepare_text($a->profile['music'])) {
839 $profile['music'] = [L10n::t('Musical interests:'), $txt];
842 if ($txt = prepare_text($a->profile['book'])) {
843 $profile['book'] = [L10n::t('Books, literature:'), $txt];
846 if ($txt = prepare_text($a->profile['tv'])) {
847 $profile['tv'] = [L10n::t('Television:'), $txt];
850 if ($txt = prepare_text($a->profile['film'])) {
851 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
854 if ($txt = prepare_text($a->profile['romance'])) {
855 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
858 if ($txt = prepare_text($a->profile['work'])) {
859 $profile['work'] = [L10n::t('Work/employment:'), $txt];
862 if ($txt = prepare_text($a->profile['education'])) {
863 $profile['education'] = [L10n::t('School/education:'), $txt];
866 //show subcribed forum if it is enabled in the usersettings
867 if (Feature::isEnabled($uid, 'forumlist_profile')) {
868 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
871 if ($a->profile['uid'] == local_user()) {
872 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
875 return Renderer::replaceMacros($tpl, [
876 '$title' => L10n::t('Profile'),
877 '$basic' => L10n::t('Basic'),
878 '$advanced' => L10n::t('Advanced'),
879 '$profile' => $profile
886 public static function getTabs($a, $is_owner = false, $nickname = null)
888 if (is_null($nickname)) {
889 $nickname = $a->user['nickname'];
893 if (!empty($_GET['tab'])) {
894 $tab = Strings::escapeTags(trim($_GET['tab']));
897 $url = System::baseUrl() . '/profile/' . $nickname;
901 'label' => L10n::t('Status'),
903 'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
904 'title' => L10n::t('Status Messages and Posts'),
905 'id' => 'status-tab',
909 'label' => L10n::t('Profile'),
910 'url' => $url . '/?tab=profile',
911 'sel' => $tab == 'profile' ? 'active' : '',
912 'title' => L10n::t('Profile Details'),
913 'id' => 'profile-tab',
917 'label' => L10n::t('Photos'),
918 'url' => System::baseUrl() . '/photos/' . $nickname,
919 'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
920 'title' => L10n::t('Photo Albums'),
925 'label' => L10n::t('Videos'),
926 'url' => System::baseUrl() . '/videos/' . $nickname,
927 'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
928 'title' => L10n::t('Videos'),
934 // the calendar link for the full featured events calendar
935 if ($is_owner && $a->theme_events_in_profile) {
937 'label' => L10n::t('Events'),
938 'url' => System::baseUrl() . '/events',
939 'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
940 'title' => L10n::t('Events and Calendar'),
941 'id' => 'events-tab',
944 // if the user is not the owner of the calendar we only show a calendar
945 // with the public events of the calendar owner
946 } elseif (!$is_owner) {
948 'label' => L10n::t('Events'),
949 'url' => System::baseUrl() . '/cal/' . $nickname,
950 'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
951 'title' => L10n::t('Events and Calendar'),
952 'id' => 'events-tab',
959 'label' => L10n::t('Personal Notes'),
960 'url' => System::baseUrl() . '/notes',
961 'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
962 'title' => L10n::t('Only You Can See This'),
968 if (!empty($_SESSION['new_member']) && $is_owner) {
970 'label' => L10n::t('Tips for New Members'),
971 'url' => System::baseUrl() . '/newmember',
973 'title' => L10n::t('Tips for New Members'),
974 'id' => 'newmember-tab',
978 if (!$is_owner && empty($a->profile['hide-friends'])) {
980 'label' => L10n::t('Contacts'),
981 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
982 'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
983 'title' => L10n::t('Contacts'),
984 'id' => 'viewcontacts-tab',
989 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
990 Hook::callAll('profile_tabs', $arr);
992 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
994 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
998 * Retrieves the my_url session variable
1002 public static function getMyURL()
1004 if (!empty($_SESSION['my_url'])) {
1005 return $_SESSION['my_url'];
1011 * Process the 'zrl' parameter and initiate the remote authentication.
1013 * This method checks if the visitor has a public contact entry and
1014 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1017 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1019 * @param App $a Application instance.
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 public static function zrlInit(App $a)
1025 $my_url = self::getMyURL();
1026 $my_url = Network::isUrlValid($my_url);
1028 if (empty($my_url) || local_user()) {
1032 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1033 Hook::callAll('zrl_init', $arr);
1035 // Try to find the public contact entry of the visitor.
1036 $cid = Contact::getIdForURL($my_url);
1038 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1042 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1044 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1045 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1049 // Avoid endless loops
1050 $cachekey = 'zrlInit:' . $my_url;
1051 if (Cache::get($cachekey)) {
1052 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1055 Cache::set($cachekey, true, Cache::MINUTE);
1058 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1060 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1062 // Try to avoid recursion - but send them home to do a proper magic auth.
1063 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1064 // The other instance needs to know where to redirect.
1065 $dest = urlencode($a->getBaseURL() . '/' . $query);
1067 // We need to extract the basebath from the profile url
1068 // to redirect the visitors '/magic' module.
1069 // Note: We should have the basepath of a contact also in the contact table.
1070 $urlarr = explode('/profile/', $contact['url']);
1071 $basepath = $urlarr[0];
1073 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1074 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1076 // We have to check if the remote server does understand /magic without invoking something
1077 $serverret = Network::curl($basepath . '/magic');
1078 if ($serverret->isSuccess()) {
1079 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1080 System::externalRedirect($magic_path);
1086 * Set the visitor cookies (see remote_user()) for the given handle
1088 * @param string $handle Visitor handle
1089 * @return array Visitor contact array
1091 public static function addVisitorCookieForHandle($handle)
1095 // Try to find the public contact entry of the visitor.
1096 $cid = Contact::getIdForURL($handle);
1098 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1102 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1104 // Authenticate the visitor.
1105 $_SESSION['authenticated'] = 1;
1106 $_SESSION['visitor_id'] = $visitor['id'];
1107 $_SESSION['visitor_handle'] = $visitor['addr'];
1108 $_SESSION['visitor_home'] = $visitor['url'];
1109 $_SESSION['my_url'] = $visitor['url'];
1111 /// @todo replace this and the query for this variable with some cleaner functionality
1112 $_SESSION['remote'] = [];
1114 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1115 while ($contact = DBA::fetch($remote_contacts)) {
1116 if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1120 $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
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' => $a->query_string
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(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->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 * @brief Get the user ID of the page owner
1207 * @return int user ID
1209 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1210 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1212 public static function getThemeUid(App $a)
1214 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1215 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1216 return local_user();
1223 * Strip zrl parameter from a string.
1225 * @param string $s The input string.
1226 * @return string The zrl.
1228 public static function stripZrls($s)
1230 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1234 * Strip query parameter from a string.
1236 * @param string $s The input string.
1238 * @return string The query parameter.
1240 public static function stripQueryParam($s, $param)
1242 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);