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 // Ensure to have a "nickname" field
121 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
122 $profiledata['nickname'] = $profiledata['nick'];
125 // Add profile data to sidebar
126 $a->page['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
128 if (!DBA::isResult($user)) {
133 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
135 if (empty($pdata) && empty($profiledata)) {
136 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
141 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
144 // fetch user tags if this isn't the default profile
146 if (!$pdata['is-default']) {
147 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
148 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
149 if (DBA::isResult($profile)) {
150 $pdata['pub_keywords'] = $profile['pub_keywords'];
154 $a->profile = $pdata;
155 $a->profile_uid = $pdata['profile_uid'];
157 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
158 $a->profile['network'] = Protocol::DFRN;
160 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
162 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
163 $_SESSION['theme'] = $a->profile['theme'];
166 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
169 * load/reload current theme info
172 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
174 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
175 if (file_exists($theme_info_file)) {
176 require_once $theme_info_file;
179 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
180 $a->page['aside'] .= Renderer::replaceMacros(
181 Renderer::getMarkupTemplate('profile_edlink.tpl'),
183 '$editprofile' => L10n::t('Edit profile'),
184 '$profid' => $a->profile['id']
189 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
193 * By now, the contact block isn't shown, when a different profile is given
194 * But: When this profile was on the same server, then we could display the contacts
197 $a->page['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
204 * Get all profile data of a local user
206 * If the viewer is an authenticated remote viewer, the profile displayed is the
207 * one that has been configured for his/her viewing in the Contact manager.
208 * Passing a non-zero profile ID can also allow a preview of a selected profile
211 * Includes all available profile data
213 * @brief Get all profile data of a local user
214 * @param string $nickname nick
215 * @param int $uid uid
216 * @param int $profile_id ID of the profile
220 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
222 if (remote_user() && !empty($_SESSION['remote'])) {
223 foreach ($_SESSION['remote'] as $visitor) {
224 if ($visitor['uid'] == $uid) {
225 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
226 if (DBA::isResult($contact)) {
227 $profile_id = $contact['profile-id'];
237 $profile = DBA::fetchFirst(
238 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
239 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
240 `profile`.`uid` AS `profile_uid`, `profile`.*,
241 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
243 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
244 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
245 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
250 if (!DBA::isResult($profile)) {
251 $profile = DBA::fetchFirst(
252 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
253 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
254 `profile`.`uid` AS `profile_uid`, `profile`.*,
255 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
257 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
258 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
259 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
268 * Formats a profile for display in the sidebar.
270 * It is very difficult to templatise the HTML completely
271 * because of all the conditional logic.
273 * @brief Formats a profile for display in the sidebar.
274 * @param array $profile
276 * @param boolean $show_connect Show connect link
278 * @return string HTML sidebar module
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 * @throws \ImagickException
282 * @note Returns empty string if passed $profile is wrong type or not populated
284 * @hooks 'profile_sidebar_enter'
285 * array $profile - profile data
286 * @hooks 'profile_sidebar'
289 private static function sidebar(App $a, $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);
311 if (isset($profile['url'])) {
312 $profile_url = $profile['url'];
314 $profile_url = $a->getBaseURL() . '/profile/' . $profile['nickname'];
318 $unfollow_link = null;
319 $subscribe_feed_link = null;
320 $wallmessage_link = null;
324 $visitor_contact = [];
325 if (!empty($profile['uid']) && self::getMyURL()) {
326 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
329 $profile_contact = [];
330 if (!empty($profile['cid']) && self::getMyURL()) {
331 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
334 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
335 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
336 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
337 $visitor_is_authenticated = (bool)self::getMyURL();
338 $visitor_is_following =
339 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
340 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
341 $visitor_is_followed =
342 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
343 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
344 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
346 if (!$local_user_is_self && $show_connect) {
347 if (!$visitor_is_authenticated) {
348 $follow_link = 'dfrn_request/' . $profile['nickname'];
349 } elseif ($profile_is_native) {
350 if ($visitor_is_following) {
351 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
353 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
357 if ($profile_is_dfrn) {
358 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
361 if (Contact::canReceivePrivateMessages($profile)) {
362 if ($visitor_is_followed || $visitor_is_following) {
363 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode(defaults($profile, 'addr', ''));
364 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
365 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
370 // show edit profile to yourself
371 if (!$is_contact && $local_user_is_self) {
372 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
373 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
375 "SELECT * FROM `profile` WHERE `uid` = %d",
380 'chg_photo' => L10n::t('Change profile photo'),
381 'cr_new' => L10n::t('Create New Profile'),
385 if (DBA::isResult($r)) {
386 foreach ($r as $rr) {
387 $profile['menu']['entries'][] = [
388 'photo' => $rr['thumb'],
390 'alt' => L10n::t('Profile Image'),
391 'profile_name' => $rr['profile-name'],
392 'isdefault' => $rr['is-default'],
393 'visibile_to_everybody' => L10n::t('visible to everybody'),
394 'edit_visibility' => L10n::t('Edit visibility'),
399 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
401 'chg_photo' => L10n::t('Change profile photo'),
408 // Fetch the account type
409 $account_type = Contact::getAccountType($profile);
411 if (!empty($profile['address'])
412 || !empty($profile['location'])
413 || !empty($profile['locality'])
414 || !empty($profile['region'])
415 || !empty($profile['postal-code'])
416 || !empty($profile['country-name'])
418 $location = L10n::t('Location:');
421 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
422 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
423 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
424 $about = !empty($profile['about']) ? L10n::t('About:') : false;
425 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
427 if ((!empty($profile['hidewall']) || $block) && !local_user() && !remote_user()) {
428 $location = $gender = $marital = $homepage = $about = false;
431 $split_name = Diaspora::splitName($profile['name']);
432 $firstname = $split_name['first'];
433 $lastname = $split_name['last'];
435 if (!empty($profile['guid'])) {
437 'guid' => $profile['guid'],
438 'podloc' => System::baseUrl(),
439 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
440 'nickname' => $profile['nickname'],
441 'fullname' => $profile['name'],
442 'firstname' => $firstname,
443 'lastname' => $lastname,
444 'photo300' => defaults($profile, 'contact_photo', ''),
445 'photo100' => defaults($profile, 'contact_thumb', ''),
446 'photo50' => defaults($profile, 'contact_micro', ''),
456 $contact_block = ContactBlock::getHTML($a->profile);
458 if (is_array($a->profile) && !$a->profile['hide-friends']) {
460 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
461 intval($a->profile['uid'])
463 if (DBA::isResult($r)) {
464 $updated = date('c', strtotime($r[0]['updated']));
467 $contact_count = DBA::count('contact', [
468 'uid' => $profile['uid'],
474 'network' => Protocol::FEDERATED,
480 foreach ($profile as $k => $v) {
481 $k = str_replace('-', '_', $k);
485 if (isset($p['about'])) {
486 $p['about'] = BBCode::convert($p['about']);
489 if (empty($p['address']) && !empty($p['location'])) {
490 $p['address'] = $p['location'];
493 if (isset($p['address'])) {
494 $p['address'] = BBCode::convert($p['address']);
497 if (isset($p['photo'])) {
498 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
501 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
503 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
504 $o .= Renderer::replaceMacros($tpl, [
507 '$follow' => L10n::t('Follow'),
508 '$follow_link' => $follow_link,
509 '$unfollow' => L10n::t('Unfollow'),
510 '$unfollow_link' => $unfollow_link,
511 '$subscribe_feed' => L10n::t('Atom feed'),
512 '$subscribe_feed_link' => $subscribe_feed_link,
513 '$wallmessage' => L10n::t('Message'),
514 '$wallmessage_link' => $wallmessage_link,
515 '$account_type' => $account_type,
516 '$location' => $location,
517 '$gender' => $gender,
518 '$marital' => $marital,
519 '$homepage' => $homepage,
521 '$network' => L10n::t('Network:'),
522 '$contacts' => $contact_count,
523 '$updated' => $updated,
524 '$diaspora' => $diaspora,
525 '$contact_block' => $contact_block,
528 $arr = ['profile' => &$profile, 'entry' => &$o];
530 Hook::callAll('profile_sidebar', $arr);
535 public static function getBirthdays()
540 if (!local_user() || $a->is_mobile || $a->is_tablet) {
545 * $mobile_detect = new Mobile_Detect();
546 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
551 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
552 $bd_short = L10n::t('F d');
554 $cachekey = 'get_birthdays:' . local_user();
555 $r = Cache::get($cachekey);
558 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
560 ON `contact`.`id` = `event`.`cid`
561 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
562 AND NOT `contact`.`pending`
563 AND NOT `contact`.`hidden`
564 AND NOT `contact`.`blocked`
565 AND NOT `contact`.`archive`
566 AND NOT `contact`.`deleted`
567 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
568 ORDER BY `start` ASC ",
572 DateTimeFormat::utc('now + 6 days'),
573 DateTimeFormat::utcNow()
575 if (DBA::isResult($s)) {
576 $r = DBA::toArray($s);
577 Cache::set($cachekey, $r, Cache::HOUR);
583 if (DBA::isResult($r)) {
584 $now = strtotime('now');
588 foreach ($r as $rr) {
589 if (strlen($rr['name'])) {
592 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
596 $classtoday = $istoday ? ' birthday-today ' : '';
598 foreach ($r as &$rr) {
599 if (!strlen($rr['name'])) {
605 if (in_array($rr['cid'], $cids)) {
608 $cids[] = $rr['cid'];
610 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
612 $rr['link'] = Contact::magicLink($rr['url']);
613 $rr['title'] = $rr['name'];
614 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
615 $rr['startime'] = null;
616 $rr['today'] = $today;
620 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
621 return Renderer::replaceMacros($tpl, [
622 '$classtoday' => $classtoday,
624 '$event_reminders' => L10n::t('Birthday Reminders'),
625 '$event_title' => L10n::t('Birthdays this week:'),
627 '$lbr' => '{', // raw brackets mess up if/endif macro processing
632 public static function getEventsReminderHTML()
637 if (!local_user() || $a->is_mobile || $a->is_tablet) {
642 * $mobile_detect = new Mobile_Detect();
643 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
648 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
651 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
652 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
653 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
657 if (DBA::isResult($s)) {
661 while ($rr = DBA::fetch($s)) {
662 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
663 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
664 'visible' => true, 'deleted' => false];
665 if (!Item::exists($condition)) {
669 if (strlen($rr['summary'])) {
673 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
674 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
678 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
680 if (strlen($title) > 35) {
681 $title = substr($title, 0, 32) . '... ';
684 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
686 $description = L10n::t('[No description]');
689 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
691 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
695 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
697 $rr['title'] = $title;
698 $rr['description'] = $description;
699 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
700 $rr['startime'] = $strt;
701 $rr['today'] = $today;
706 $classtoday = (($istoday) ? 'event-today' : '');
708 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
709 return Renderer::replaceMacros($tpl, [
710 '$classtoday' => $classtoday,
711 '$count' => count($r),
712 '$event_reminders' => L10n::t('Event Reminders'),
713 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
718 public static function getAdvanced(App $a)
720 $uid = $a->profile['uid'];
722 if ($a->profile['name']) {
723 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
727 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
729 if (Feature::isEnabled($uid, 'profile_membersince')) {
730 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
733 if ($a->profile['gender']) {
734 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
737 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
738 $year_bd_format = L10n::t('j F, Y');
739 $short_bd_format = L10n::t('j F');
742 intval($a->profile['dob']) ?
743 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
744 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
747 $profile['birthday'] = [L10n::t('Birthday:'), $val];
750 if (!empty($a->profile['dob'])
751 && $a->profile['dob'] > DBA::NULL_DATE
752 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
754 $profile['age'] = [L10n::t('Age:'), $age];
757 if ($a->profile['marital']) {
758 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
761 /// @TODO Maybe use x() here, plus below?
762 if ($a->profile['with']) {
763 $profile['marital']['with'] = $a->profile['with'];
766 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
767 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
770 if ($a->profile['sexual']) {
771 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
774 if ($a->profile['homepage']) {
775 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
778 if ($a->profile['hometown']) {
779 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
782 if ($a->profile['pub_keywords']) {
783 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
786 if ($a->profile['politic']) {
787 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
790 if ($a->profile['religion']) {
791 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
794 if ($txt = prepare_text($a->profile['about'])) {
795 $profile['about'] = [L10n::t('About:'), $txt];
798 if ($txt = prepare_text($a->profile['interest'])) {
799 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
802 if ($txt = prepare_text($a->profile['likes'])) {
803 $profile['likes'] = [L10n::t('Likes:'), $txt];
806 if ($txt = prepare_text($a->profile['dislikes'])) {
807 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
810 if ($txt = prepare_text($a->profile['contact'])) {
811 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
814 if ($txt = prepare_text($a->profile['music'])) {
815 $profile['music'] = [L10n::t('Musical interests:'), $txt];
818 if ($txt = prepare_text($a->profile['book'])) {
819 $profile['book'] = [L10n::t('Books, literature:'), $txt];
822 if ($txt = prepare_text($a->profile['tv'])) {
823 $profile['tv'] = [L10n::t('Television:'), $txt];
826 if ($txt = prepare_text($a->profile['film'])) {
827 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
830 if ($txt = prepare_text($a->profile['romance'])) {
831 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
834 if ($txt = prepare_text($a->profile['work'])) {
835 $profile['work'] = [L10n::t('Work/employment:'), $txt];
838 if ($txt = prepare_text($a->profile['education'])) {
839 $profile['education'] = [L10n::t('School/education:'), $txt];
842 //show subcribed forum if it is enabled in the usersettings
843 if (Feature::isEnabled($uid, 'forumlist_profile')) {
844 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
847 if ($a->profile['uid'] == local_user()) {
848 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
851 return Renderer::replaceMacros($tpl, [
852 '$title' => L10n::t('Profile'),
853 '$basic' => L10n::t('Basic'),
854 '$advanced' => L10n::t('Advanced'),
855 '$profile' => $profile
864 * @param string $current
865 * @param bool $is_owner
866 * @param string $nickname
868 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
872 if (is_null($nickname)) {
873 $nickname = $a->user['nickname'];
876 $baseProfileUrl = System::baseUrl() . '/profile/' . $nickname;
880 'label' => L10n::t('Status'),
881 'url' => $baseProfileUrl,
882 'sel' => !$current ? 'active' : '',
883 'title' => L10n::t('Status Messages and Posts'),
884 'id' => 'status-tab',
888 'label' => L10n::t('Profile'),
889 'url' => $baseProfileUrl . '/?tab=profile',
890 'sel' => $current == 'profile' ? 'active' : '',
891 'title' => L10n::t('Profile Details'),
892 'id' => 'profile-tab',
896 'label' => L10n::t('Photos'),
897 'url' => System::baseUrl() . '/photos/' . $nickname,
898 'sel' => $current == 'photos' ? 'active' : '',
899 'title' => L10n::t('Photo Albums'),
904 'label' => L10n::t('Videos'),
905 'url' => System::baseUrl() . '/videos/' . $nickname,
906 'sel' => $current == 'videos' ? 'active' : '',
907 'title' => L10n::t('Videos'),
913 // the calendar link for the full featured events calendar
914 if ($is_owner && $a->theme_events_in_profile) {
916 'label' => L10n::t('Events'),
917 'url' => System::baseUrl() . '/events',
918 'sel' => $current == 'events' ? 'active' : '',
919 'title' => L10n::t('Events and Calendar'),
920 'id' => 'events-tab',
923 // if the user is not the owner of the calendar we only show a calendar
924 // with the public events of the calendar owner
925 } elseif (!$is_owner) {
927 'label' => L10n::t('Events'),
928 'url' => System::baseUrl() . '/cal/' . $nickname,
929 'sel' => $current == 'cal' ? 'active' : '',
930 'title' => L10n::t('Events and Calendar'),
931 'id' => 'events-tab',
938 'label' => L10n::t('Personal Notes'),
939 'url' => System::baseUrl() . '/notes',
940 'sel' => $current == 'notes' ? 'active' : '',
941 'title' => L10n::t('Only You Can See This'),
947 if (!empty($_SESSION['new_member']) && $is_owner) {
949 'label' => L10n::t('Tips for New Members'),
950 'url' => System::baseUrl() . '/newmember',
952 'title' => L10n::t('Tips for New Members'),
953 'id' => 'newmember-tab',
957 if ($is_owner || empty($a->profile['hide-friends'])) {
959 'label' => L10n::t('Contacts'),
960 'url' => $baseProfileUrl . '/contacts',
961 'sel' => $current == 'contacts' ? 'active' : '',
962 'title' => L10n::t('Contacts'),
963 'id' => 'viewcontacts-tab',
968 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
969 Hook::callAll('profile_tabs', $arr);
971 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
973 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
977 * Retrieves the my_url session variable
981 public static function getMyURL()
983 return Session::get('my_url');
987 * Process the 'zrl' parameter and initiate the remote authentication.
989 * This method checks if the visitor has a public contact entry and
990 * redirects the visitor to his/her instance to start the magic auth (Authentication)
993 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
995 * @param App $a Application instance.
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 * @throws \ImagickException
999 public static function zrlInit(App $a)
1001 $my_url = self::getMyURL();
1002 $my_url = Network::isUrlValid($my_url);
1004 if (empty($my_url) || local_user()) {
1008 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1009 Hook::callAll('zrl_init', $arr);
1011 // Try to find the public contact entry of the visitor.
1012 $cid = Contact::getIdForURL($my_url);
1014 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1018 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1020 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1021 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1025 // Avoid endless loops
1026 $cachekey = 'zrlInit:' . $my_url;
1027 if (Cache::get($cachekey)) {
1028 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1031 Cache::set($cachekey, true, Cache::MINUTE);
1034 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1036 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1038 // Try to avoid recursion - but send them home to do a proper magic auth.
1039 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1040 // The other instance needs to know where to redirect.
1041 $dest = urlencode($a->getBaseURL() . '/' . $query);
1043 // We need to extract the basebath from the profile url
1044 // to redirect the visitors '/magic' module.
1045 // Note: We should have the basepath of a contact also in the contact table.
1046 $urlarr = explode('/profile/', $contact['url']);
1047 $basepath = $urlarr[0];
1049 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1050 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1052 // We have to check if the remote server does understand /magic without invoking something
1053 $serverret = Network::curl($basepath . '/magic');
1054 if ($serverret->isSuccess()) {
1055 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1056 System::externalRedirect($magic_path);
1062 * Set the visitor cookies (see remote_user()) for the given handle
1064 * @param string $handle Visitor handle
1065 * @return array Visitor contact array
1067 public static function addVisitorCookieForHandle($handle)
1071 // Try to find the public contact entry of the visitor.
1072 $cid = Contact::getIdForURL($handle);
1074 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1078 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1080 // Authenticate the visitor.
1081 $_SESSION['authenticated'] = 1;
1082 $_SESSION['visitor_id'] = $visitor['id'];
1083 $_SESSION['visitor_handle'] = $visitor['addr'];
1084 $_SESSION['visitor_home'] = $visitor['url'];
1085 $_SESSION['my_url'] = $visitor['url'];
1087 /// @todo replace this and the query for this variable with some cleaner functionality
1088 $_SESSION['remote'] = [];
1090 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1091 while ($contact = DBA::fetch($remote_contacts)) {
1092 if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1096 $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
1099 $a->contact = $visitor;
1101 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1107 * OpenWebAuth authentication.
1109 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1111 * @param string $token
1112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1113 * @throws \ImagickException
1115 public static function openWebAuthInit($token)
1119 // Clean old OpenWebAuthToken entries.
1120 OpenWebAuthToken::purge('owt', '3 MINUTE');
1122 // Check if the token we got is the same one
1123 // we have stored in the database.
1124 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1126 if ($visitor_handle === false) {
1130 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1131 if (empty($visitor)) {
1136 'visitor' => $visitor,
1137 'url' => $a->query_string
1140 * @hooks magic_auth_success
1141 * Called when a magic-auth was successful.
1142 * * \e array \b visitor
1143 * * \e string \b url
1145 Hook::callAll('magic_auth_success', $arr);
1147 $a->contact = $arr['visitor'];
1149 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1151 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1154 public static function zrl($s, $force = false)
1159 if ((!strpos($s, '/profile/')) && (!$force)) {
1162 if ($force && substr($s, -1, 1) !== '/') {
1165 $achar = strpos($s, '?') ? '&' : '?';
1166 $mine = self::getMyURL();
1167 if ($mine && !Strings::compareLink($mine, $s)) {
1168 return $s . $achar . 'zrl=' . urlencode($mine);
1174 * Get the user ID of the page owner.
1176 * Used from within PCSS themes to set theme parameters. If there's a
1177 * profile_uid variable set in App, that is the "page owner" and normally their theme
1178 * settings take precedence; unless a local user sets the "always_my_theme"
1179 * system pconfig, which means they don't want to see anybody else's theme
1180 * settings except their own while on this site.
1182 * @brief Get the user ID of the page owner
1183 * @return int user ID
1185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1186 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1188 public static function getThemeUid(App $a)
1190 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1191 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1192 return local_user();
1199 * Strip zrl parameter from a string.
1201 * @param string $s The input string.
1202 * @return string The zrl.
1204 public static function stripZrls($s)
1206 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1210 * Strip query parameter from a string.
1212 * @param string $s The input string.
1214 * @return string The query parameter.
1216 public static function stripQueryParam($s, $param)
1218 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1222 * search for Profiles
1226 * @param null $search
1228 * @return array [ 'total' => 123, 'entries' => [...] ];
1230 * @throws \Exception
1232 public static function searchProfiles($start = 0, $count = 100, $search = null)
1234 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1237 if (!empty($search)) {
1238 $searchTerm = '%' . $search . '%';
1239 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1241 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1242 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1243 AND ((`profile`.`name` LIKE ?) OR
1244 (`user`.`nickname` LIKE ?) OR
1245 (`profile`.`pdesc` LIKE ?) OR
1246 (`profile`.`locality` LIKE ?) OR
1247 (`profile`.`region` LIKE ?) OR
1248 (`profile`.`country-name` LIKE ?) OR
1249 (`profile`.`gender` LIKE ?) OR
1250 (`profile`.`marital` LIKE ?) OR
1251 (`profile`.`sexual` LIKE ?) OR
1252 (`profile`.`about` LIKE ?) OR
1253 (`profile`.`romance` LIKE ?) OR
1254 (`profile`.`work` LIKE ?) OR
1255 (`profile`.`education` LIKE ?) OR
1256 (`profile`.`pub_keywords` LIKE ?) OR
1257 (`profile`.`prv_keywords` LIKE ?))",
1258 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1259 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1261 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1263 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1264 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1267 if (DBA::isResult($cnt)) {
1268 $total = $cnt['total'];
1271 $order = " ORDER BY `name` ASC ";
1274 // If nothing found, don't try to select details
1276 if (!empty($search)) {
1277 $searchTerm = '%' . $search . '%';
1279 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1280 `contact`.`addr`, `contact`.`url` AS `profile_url`
1282 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1283 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1284 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1285 AND ((`profile`.`name` LIKE ?) OR
1286 (`user`.`nickname` LIKE ?) OR
1287 (`profile`.`pdesc` LIKE ?) OR
1288 (`profile`.`locality` LIKE ?) OR
1289 (`profile`.`region` LIKE ?) OR
1290 (`profile`.`country-name` LIKE ?) OR
1291 (`profile`.`gender` LIKE ?) OR
1292 (`profile`.`marital` LIKE ?) OR
1293 (`profile`.`sexual` LIKE ?) OR
1294 (`profile`.`about` LIKE ?) OR
1295 (`profile`.`romance` LIKE ?) OR
1296 (`profile`.`work` LIKE ?) OR
1297 (`profile`.`education` LIKE ?) OR
1298 (`profile`.`pub_keywords` LIKE ?) OR
1299 (`profile`.`prv_keywords` LIKE ?))
1301 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1302 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1306 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1307 `contact`.`addr`, `contact`.`url` AS `profile_url`
1309 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1310 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1311 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1318 if (DBA::isResult($profiles) && $total > 0) {
1321 'entries' => DBA::toArray($profiles),