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\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\Hook;
15 use Friendica\Core\L10n;
16 use Friendica\Core\Logger;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Network;
26 use Friendica\Util\Proxy as ProxyUtils;
27 use Friendica\Util\Strings;
28 use Friendica\Util\Temporal;
33 * @brief Returns default profile for a given user id
35 * @param integer User ID
37 * @return array Profile data
40 public static function getByUID($uid)
42 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
47 * @brief Returns a formatted location string from the given profile array
49 * @param array $profile Profile array (Generated from the "profile" table)
51 * @return string Location string
53 public static function formatLocation(array $profile)
57 if (!empty($profile['locality'])) {
58 $location .= $profile['locality'];
61 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
66 $location .= $profile['region'];
69 if (!empty($profile['country-name'])) {
74 $location .= $profile['country-name'];
82 * Loads a profile into the page sidebar.
84 * The function requires a writeable copy of the main App structure, and the nickname
85 * of a registered local account.
87 * If the viewer is an authenticated remote viewer, the profile displayed is the
88 * one that has been configured for his/her viewing in the Contact manager.
89 * Passing a non-zero profile ID can also allow a preview of a selected profile
92 * Profile information is placed in the App structure for later retrieval.
93 * Honours the owner's chosen theme for display.
95 * @attention Should only be run in the _init() functions of a module. That ensures that
96 * the theme is chosen before the _init() function of a theme is run, which will usually
97 * load a lot of theme-specific content
99 * @brief Loads a profile into the page sidebar.
101 * @param string $nickname string
102 * @param int $profile int
103 * @param array $profiledata array
104 * @param boolean $show_connect Show connect link
105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106 * @throws \ImagickException
108 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
110 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
112 if (!DBA::isResult($user) && empty($profiledata)) {
113 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
114 notice(L10n::t('Requested account is not available.') . EOL);
119 if (count($profiledata) > 0) {
120 // Add profile data to sidebar
121 $a->page['aside'] .= self::sidebar($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);
132 notice(L10n::t('Requested profile is not available.') . EOL);
138 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
141 // fetch user tags if this isn't the default profile
143 if (!$pdata['is-default']) {
144 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
145 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
146 if (DBA::isResult($profile)) {
147 $pdata['pub_keywords'] = $profile['pub_keywords'];
151 $a->profile = $pdata;
152 $a->profile_uid = $pdata['profile_uid'];
154 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
155 $a->profile['network'] = Protocol::DFRN;
157 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
159 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
160 $_SESSION['theme'] = $a->profile['theme'];
163 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
166 * load/reload current theme info
169 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
171 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
172 if (file_exists($theme_info_file)) {
173 require_once $theme_info_file;
176 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
177 $a->page['aside'] .= Renderer::replaceMacros(
178 Renderer::getMarkupTemplate('profile_edlink.tpl'),
180 '$editprofile' => L10n::t('Edit profile'),
181 '$profid' => $a->profile['id']
186 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
190 * By now, the contact block isn't shown, when a different profile is given
191 * But: When this profile was on the same server, then we could display the contacts
194 $a->page['aside'] .= self::sidebar($a->profile, $block, $show_connect);
201 * Get all profile data of a local user
203 * If the viewer is an authenticated remote viewer, the profile displayed is the
204 * one that has been configured for his/her viewing in the Contact manager.
205 * Passing a non-zero profile ID can also allow a preview of a selected profile
208 * Includes all available profile data
210 * @brief Get all profile data of a local user
211 * @param string $nickname nick
212 * @param int $uid uid
213 * @param int $profile_id ID of the profile
217 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
219 if (remote_user() && !empty($_SESSION['remote'])) {
220 foreach ($_SESSION['remote'] as $visitor) {
221 if ($visitor['uid'] == $uid) {
222 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
223 if (DBA::isResult($contact)) {
224 $profile_id = $contact['profile-id'];
234 $profile = DBA::fetchFirst(
235 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
236 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
237 `profile`.`uid` AS `profile_uid`, `profile`.*,
238 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
240 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
241 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
242 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
247 if (!DBA::isResult($profile)) {
248 $profile = DBA::fetchFirst(
249 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
250 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
251 `profile`.`uid` AS `profile_uid`, `profile`.*,
252 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
254 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
255 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
256 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
265 * Formats a profile for display in the sidebar.
267 * It is very difficult to templatise the HTML completely
268 * because of all the conditional logic.
270 * @brief Formats a profile for display in the sidebar.
271 * @param array $profile
273 * @param boolean $show_connect Show connect link
275 * @return string HTML sidebar module
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 * @throws \ImagickException
279 * @note Returns empty string if passed $profile is wrong type or not populated
281 * @hooks 'profile_sidebar_enter'
282 * array $profile - profile data
283 * @hooks 'profile_sidebar'
286 private static function sidebar($profile, $block = 0, $show_connect = true)
293 // This function can also use contact information in $profile
294 $is_contact = !empty($profile['cid']);
296 if (!is_array($profile) && !count($profile)) {
300 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
302 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
303 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
305 $profile['network_link'] = '';
308 Hook::callAll('profile_sidebar_enter', $profile);
311 // don't show connect link to yourself
312 $connect = $profile['uid'] != local_user() ? L10n::t('Connect') : false;
314 // don't show connect link to authenticated visitors either
315 if (remote_user() && !empty($_SESSION['remote'])) {
316 foreach ($_SESSION['remote'] as $visitor) {
317 if ($visitor['uid'] == $profile['uid']) {
324 if (!$show_connect) {
330 // Is the local user already connected to that user?
331 if ($connect && local_user()) {
332 if (isset($profile['url'])) {
333 $profile_url = Strings::normaliseLink($profile['url']);
335 $profile_url = Strings::normaliseLink(System::baseUrl() . '/profile/' . $profile['nickname']);
338 if (DBA::exists('contact', ['pending' => false, 'uid' => local_user(), 'nurl' => $profile_url])) {
343 // Is the remote user already connected to that user?
344 if ($connect && Contact::isFollower(remote_user(), $profile['uid'])) {
348 if ($connect && ($profile['network'] != Protocol::DFRN) && !isset($profile['remoteconnect'])) {
352 $remoteconnect = null;
353 if (isset($profile['remoteconnect'])) {
354 $remoteconnect = $profile['remoteconnect'];
357 if ($connect && ($profile['network'] == Protocol::DFRN) && !isset($remoteconnect)) {
358 $subscribe_feed = L10n::t('Atom feed');
360 $subscribe_feed = false;
363 $wallmessage = false;
364 $wallmessage_link = false;
366 // See issue https://github.com/friendica/friendica/issues/3838
367 // Either we remove the message link for remote users or we enable creating messages from remote users
368 if (remote_user() || (self::getMyURL() && !empty($profile['unkmail']) && ($profile['uid'] != local_user()))) {
369 $wallmessage = L10n::t('Message');
373 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
374 intval($profile['uid']),
375 intval(remote_user()),
376 intval(Contact::FRIEND)
380 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
381 intval($profile['uid']),
382 DBA::escape(Strings::normaliseLink(self::getMyURL())),
383 intval(Contact::FRIEND)
387 $remote_url = $r[0]['url'];
388 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
389 $wallmessage_link = $message_path . base64_encode(defaults($profile, 'addr', ''));
390 } else if (!empty($profile['nickname'])) {
391 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
395 // show edit profile to yourself
396 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
397 $profile['edit'] = [System::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 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
424 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
426 '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) && !local_user() && !remote_user()) {
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' => System::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' => defaults($profile, 'contact_photo', ''),
469 'photo100' => defaults($profile, 'contact_thumb', ''),
470 'photo50' => defaults($profile, 'contact_micro', ''),
480 $contact_block = HTML::contactBlock();
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']));
492 "SELECT COUNT(*) AS `total` FROM `contact`
494 AND NOT `self` AND NOT `blocked` AND NOT `pending`
495 AND NOT `hidden` AND NOT `archive`
496 AND `network` IN ('%s', '%s', '%s', '')",
497 intval($profile['uid']),
498 DBA::escape(Protocol::DFRN),
499 DBA::escape(Protocol::DIASPORA),
500 DBA::escape(Protocol::OSTATUS)
502 if (DBA::isResult($r)) {
503 $contacts = intval($r[0]['total']);
509 foreach ($profile as $k => $v) {
510 $k = str_replace('-', '_', $k);
514 if (isset($p['about'])) {
515 $p['about'] = BBCode::convert($p['about']);
518 if (empty($p['address']) && !empty($p['location'])) {
519 $p['address'] = $p['location'];
522 if (isset($p['address'])) {
523 $p['address'] = BBCode::convert($p['address']);
526 if (isset($p['photo'])) {
527 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
530 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
532 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
533 $o .= Renderer::replaceMacros($tpl, [
536 '$connect' => $connect,
537 '$remoteconnect' => $remoteconnect,
538 '$subscribe_feed' => $subscribe_feed,
539 '$wallmessage' => $wallmessage,
540 '$wallmessage_link' => $wallmessage_link,
541 '$account_type' => $account_type,
542 '$location' => $location,
543 '$gender' => $gender,
544 '$marital' => $marital,
545 '$homepage' => $homepage,
547 '$network' => L10n::t('Network:'),
548 '$contacts' => $contacts,
549 '$updated' => $updated,
550 '$diaspora' => $diaspora,
551 '$contact_block' => $contact_block,
554 $arr = ['profile' => &$profile, 'entry' => &$o];
556 Hook::callAll('profile_sidebar', $arr);
561 public static function getBirthdays()
566 if (!local_user() || $a->is_mobile || $a->is_tablet) {
571 * $mobile_detect = new Mobile_Detect();
572 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
577 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
578 $bd_short = L10n::t('F d');
580 $cachekey = 'get_birthdays:' . local_user();
581 $r = Cache::get($cachekey);
584 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
586 ON `contact`.`id` = `event`.`cid`
587 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
588 AND NOT `contact`.`pending`
589 AND NOT `contact`.`hidden`
590 AND NOT `contact`.`blocked`
591 AND NOT `contact`.`archive`
592 AND NOT `contact`.`deleted`
593 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
594 ORDER BY `start` ASC ",
598 DateTimeFormat::utc('now + 6 days'),
599 DateTimeFormat::utcNow()
601 if (DBA::isResult($s)) {
602 $r = DBA::toArray($s);
603 Cache::set($cachekey, $r, Cache::HOUR);
609 if (DBA::isResult($r)) {
610 $now = strtotime('now');
614 foreach ($r as $rr) {
615 if (strlen($rr['name'])) {
618 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
622 $classtoday = $istoday ? ' birthday-today ' : '';
624 foreach ($r as &$rr) {
625 if (!strlen($rr['name'])) {
631 if (in_array($rr['cid'], $cids)) {
634 $cids[] = $rr['cid'];
636 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
638 $rr['link'] = Contact::magicLink($rr['url']);
639 $rr['title'] = $rr['name'];
640 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
641 $rr['startime'] = null;
642 $rr['today'] = $today;
646 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
647 return Renderer::replaceMacros($tpl, [
648 '$baseurl' => System::baseUrl(),
649 '$classtoday' => $classtoday,
651 '$event_reminders' => L10n::t('Birthday Reminders'),
652 '$event_title' => L10n::t('Birthdays this week:'),
654 '$lbr' => '{', // raw brackets mess up if/endif macro processing
659 public static function getEventsReminderHTML()
664 if (!local_user() || $a->is_mobile || $a->is_tablet) {
669 * $mobile_detect = new Mobile_Detect();
670 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
675 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
678 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
679 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
680 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
684 if (DBA::isResult($s)) {
688 while ($rr = DBA::fetch($s)) {
689 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
690 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
691 'visible' => true, 'deleted' => false];
692 if (!Item::exists($condition)) {
696 if (strlen($rr['summary'])) {
700 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
701 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
705 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
707 if (strlen($title) > 35) {
708 $title = substr($title, 0, 32) . '... ';
711 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
713 $description = L10n::t('[No description]');
716 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
718 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
722 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
724 $rr['title'] = $title;
725 $rr['description'] = $description;
726 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
727 $rr['startime'] = $strt;
728 $rr['today'] = $today;
733 $classtoday = (($istoday) ? 'event-today' : '');
735 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
736 return Renderer::replaceMacros($tpl, [
737 '$baseurl' => System::baseUrl(),
738 '$classtoday' => $classtoday,
739 '$count' => count($r),
740 '$event_reminders' => L10n::t('Event Reminders'),
741 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
746 public static function getAdvanced(App $a)
749 $uid = $a->profile['uid'];
751 $o .= Renderer::replaceMacros(
752 Renderer::getMarkupTemplate('section_title.tpl'),
753 ['$title' => L10n::t('Profile')]
756 if ($a->profile['name']) {
757 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
761 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
763 if (Feature::isEnabled($uid, 'profile_membersince')) {
764 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
767 if ($a->profile['gender']) {
768 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
771 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
772 $year_bd_format = L10n::t('j F, Y');
773 $short_bd_format = L10n::t('j F');
776 intval($a->profile['dob']) ?
777 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
778 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
781 $profile['birthday'] = [L10n::t('Birthday:'), $val];
784 if (!empty($a->profile['dob'])
785 && $a->profile['dob'] > DBA::NULL_DATE
786 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
788 $profile['age'] = [L10n::t('Age:'), $age];
791 if ($a->profile['marital']) {
792 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
795 /// @TODO Maybe use x() here, plus below?
796 if ($a->profile['with']) {
797 $profile['marital']['with'] = $a->profile['with'];
800 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= DBA::NULL_DATETIME) {
801 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
804 if ($a->profile['sexual']) {
805 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
808 if ($a->profile['homepage']) {
809 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
812 if ($a->profile['hometown']) {
813 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
816 if ($a->profile['pub_keywords']) {
817 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
820 if ($a->profile['politic']) {
821 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
824 if ($a->profile['religion']) {
825 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
828 if ($txt = prepare_text($a->profile['about'])) {
829 $profile['about'] = [L10n::t('About:'), $txt];
832 if ($txt = prepare_text($a->profile['interest'])) {
833 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
836 if ($txt = prepare_text($a->profile['likes'])) {
837 $profile['likes'] = [L10n::t('Likes:'), $txt];
840 if ($txt = prepare_text($a->profile['dislikes'])) {
841 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
844 if ($txt = prepare_text($a->profile['contact'])) {
845 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
848 if ($txt = prepare_text($a->profile['music'])) {
849 $profile['music'] = [L10n::t('Musical interests:'), $txt];
852 if ($txt = prepare_text($a->profile['book'])) {
853 $profile['book'] = [L10n::t('Books, literature:'), $txt];
856 if ($txt = prepare_text($a->profile['tv'])) {
857 $profile['tv'] = [L10n::t('Television:'), $txt];
860 if ($txt = prepare_text($a->profile['film'])) {
861 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
864 if ($txt = prepare_text($a->profile['romance'])) {
865 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
868 if ($txt = prepare_text($a->profile['work'])) {
869 $profile['work'] = [L10n::t('Work/employment:'), $txt];
872 if ($txt = prepare_text($a->profile['education'])) {
873 $profile['education'] = [L10n::t('School/education:'), $txt];
876 //show subcribed forum if it is enabled in the usersettings
877 if (Feature::isEnabled($uid, 'forumlist_profile')) {
878 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
881 if ($a->profile['uid'] == local_user()) {
882 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
885 return Renderer::replaceMacros($tpl, [
886 '$title' => L10n::t('Profile'),
887 '$basic' => L10n::t('Basic'),
888 '$advanced' => L10n::t('Advanced'),
889 '$profile' => $profile
896 public static function getTabs($a, $is_owner = false, $nickname = null)
898 if (is_null($nickname)) {
899 $nickname = $a->user['nickname'];
903 if (!empty($_GET['tab'])) {
904 $tab = Strings::escapeTags(trim($_GET['tab']));
907 $url = System::baseUrl() . '/profile/' . $nickname;
911 'label' => L10n::t('Status'),
913 'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
914 'title' => L10n::t('Status Messages and Posts'),
915 'id' => 'status-tab',
919 'label' => L10n::t('Profile'),
920 'url' => $url . '/?tab=profile',
921 'sel' => $tab == 'profile' ? 'active' : '',
922 'title' => L10n::t('Profile Details'),
923 'id' => 'profile-tab',
927 'label' => L10n::t('Photos'),
928 'url' => System::baseUrl() . '/photos/' . $nickname,
929 'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
930 'title' => L10n::t('Photo Albums'),
935 'label' => L10n::t('Videos'),
936 'url' => System::baseUrl() . '/videos/' . $nickname,
937 'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
938 'title' => L10n::t('Videos'),
944 // the calendar link for the full featured events calendar
945 if ($is_owner && $a->theme_events_in_profile) {
947 'label' => L10n::t('Events'),
948 'url' => System::baseUrl() . '/events',
949 'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
950 'title' => L10n::t('Events and Calendar'),
951 'id' => 'events-tab',
954 // if the user is not the owner of the calendar we only show a calendar
955 // with the public events of the calendar owner
956 } elseif (!$is_owner) {
958 'label' => L10n::t('Events'),
959 'url' => System::baseUrl() . '/cal/' . $nickname,
960 'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
961 'title' => L10n::t('Events and Calendar'),
962 'id' => 'events-tab',
969 'label' => L10n::t('Personal Notes'),
970 'url' => System::baseUrl() . '/notes',
971 'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
972 'title' => L10n::t('Only You Can See This'),
978 if (!empty($_SESSION['new_member']) && $is_owner) {
980 'label' => L10n::t('Tips for New Members'),
981 'url' => System::baseUrl() . '/newmember',
983 'title' => L10n::t('Tips for New Members'),
984 'id' => 'newmember-tab',
988 if (!$is_owner && empty($a->profile['hide-friends'])) {
990 'label' => L10n::t('Contacts'),
991 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
992 'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
993 'title' => L10n::t('Contacts'),
994 'id' => 'viewcontacts-tab',
999 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
1000 Hook::callAll('profile_tabs', $arr);
1002 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1004 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1008 * Retrieves the my_url session variable
1012 public static function getMyURL()
1014 if (!empty($_SESSION['my_url'])) {
1015 return $_SESSION['my_url'];
1021 * Process the 'zrl' parameter and initiate the remote authentication.
1023 * This method checks if the visitor has a public contact entry and
1024 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1027 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1029 * @param App $a Application instance.
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031 * @throws \ImagickException
1033 public static function zrlInit(App $a)
1035 $my_url = self::getMyURL();
1036 $my_url = Network::isUrlValid($my_url);
1038 if (empty($my_url) || local_user()) {
1042 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1043 Hook::callAll('zrl_init', $arr);
1045 // Try to find the public contact entry of the visitor.
1046 $cid = Contact::getIdForURL($my_url);
1048 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1052 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1054 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1055 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1059 // Avoid endless loops
1060 $cachekey = 'zrlInit:' . $my_url;
1061 if (Cache::get($cachekey)) {
1062 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1065 Cache::set($cachekey, true, Cache::MINUTE);
1068 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1070 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1072 // Try to avoid recursion - but send them home to do a proper magic auth.
1073 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1074 // The other instance needs to know where to redirect.
1075 $dest = urlencode($a->getBaseURL() . '/' . $query);
1077 // We need to extract the basebath from the profile url
1078 // to redirect the visitors '/magic' module.
1079 // Note: We should have the basepath of a contact also in the contact table.
1080 $urlarr = explode('/profile/', $contact['url']);
1081 $basepath = $urlarr[0];
1083 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1084 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1086 // We have to check if the remote server does understand /magic without invoking something
1087 $serverret = Network::curl($basepath . '/magic');
1088 if ($serverret->isSuccess()) {
1089 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1090 System::externalRedirect($magic_path);
1096 * OpenWebAuth authentication.
1098 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1100 * @param string $token
1101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102 * @throws \ImagickException
1104 public static function openWebAuthInit($token)
1108 // Clean old OpenWebAuthToken entries.
1109 OpenWebAuthToken::purge('owt', '3 MINUTE');
1111 // Check if the token we got is the same one
1112 // we have stored in the database.
1113 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1115 if($visitor_handle === false) {
1119 // Try to find the public contact entry of the visitor.
1120 $cid = Contact::getIdForURL($visitor_handle);
1122 Logger::log('owt: unable to finger ' . $visitor_handle, Logger::DEBUG);
1126 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1128 // Authenticate the visitor.
1129 $_SESSION['authenticated'] = 1;
1130 $_SESSION['visitor_id'] = $visitor['id'];
1131 $_SESSION['visitor_handle'] = $visitor['addr'];
1132 $_SESSION['visitor_home'] = $visitor['url'];
1133 $_SESSION['my_url'] = $visitor['url'];
1135 /// @todo replace this and the query for this variable with some cleaner functionality
1136 $_SESSION['remote'] = [];
1138 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1139 while ($contact = DBA::fetch($remote_contacts)) {
1140 if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1144 $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
1147 'visitor' => $visitor,
1148 'url' => $a->query_string
1151 * @hooks magic_auth_success
1152 * Called when a magic-auth was successful.
1153 * * \e array \b visitor
1154 * * \e string \b url
1156 Hook::callAll('magic_auth_success', $arr);
1158 $a->contact = $arr['visitor'];
1160 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1162 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1165 public static function zrl($s, $force = false)
1170 if ((!strpos($s, '/profile/')) && (!$force)) {
1173 if ($force && substr($s, -1, 1) !== '/') {
1176 $achar = strpos($s, '?') ? '&' : '?';
1177 $mine = self::getMyURL();
1178 if ($mine && !Strings::compareLink($mine, $s)) {
1179 return $s . $achar . 'zrl=' . urlencode($mine);
1185 * Get the user ID of the page owner.
1187 * Used from within PCSS themes to set theme parameters. If there's a
1188 * profile_uid variable set in App, that is the "page owner" and normally their theme
1189 * settings take precedence; unless a local user sets the "always_my_theme"
1190 * system pconfig, which means they don't want to see anybody else's theme
1191 * settings except their own while on this site.
1193 * @brief Get the user ID of the page owner
1194 * @return int user ID
1196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1197 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1199 public static function getThemeUid(App $a)
1201 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1202 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1203 return local_user();
1210 * Strip zrl parameter from a string.
1212 * @param string $s The input string.
1213 * @return string The zrl.
1215 public static function stripZrls($s)
1217 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1221 * Strip query parameter from a string.
1223 * @param string $s The input string.
1225 * @return string The query parameter.
1227 public static function stripQueryParam($s, $param)
1229 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);