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\Duration;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Database\DBA;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Proxy as ProxyUtils;
30 use Friendica\Util\Strings;
31 use Friendica\Util\Temporal;
36 * @brief Returns default profile for a given user id
38 * @param integer User ID
40 * @return array Profile data
43 public static function getByUID($uid)
45 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
50 * @brief Returns default profile for a given user ID and ID
52 * @param int $uid The contact ID
53 * @param int $id The contact owner ID
54 * @param array $fields The selected fields
56 * @return array Profile data for the ID
59 public static function getById(int $uid, int $id, array $fields = [])
61 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
65 * @brief Returns profile data for the contact owner
67 * @param int $uid The User ID
68 * @param array $fields The fields to retrieve
70 * @return array Array of profile data
73 public static function getListByUser(int $uid, array $fields = [])
75 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
79 * @brief Returns a formatted location string from the given profile array
81 * @param array $profile Profile array (Generated from the "profile" table)
83 * @return string Location string
85 public static function formatLocation(array $profile)
89 if (!empty($profile['locality'])) {
90 $location .= $profile['locality'];
93 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
98 $location .= $profile['region'];
101 if (!empty($profile['country-name'])) {
106 $location .= $profile['country-name'];
114 * Loads a profile into the page sidebar.
116 * The function requires a writeable copy of the main App structure, and the nickname
117 * of a registered local account.
119 * If the viewer is an authenticated remote viewer, the profile displayed is the
120 * one that has been configured for his/her viewing in the Contact manager.
121 * Passing a non-zero profile ID can also allow a preview of a selected profile
124 * Profile information is placed in the App structure for later retrieval.
125 * Honours the owner's chosen theme for display.
127 * @attention Should only be run in the _init() functions of a module. That ensures that
128 * the theme is chosen before the _init() function of a theme is run, which will usually
129 * load a lot of theme-specific content
131 * @brief Loads a profile into the page sidebar.
133 * @param string $nickname string
134 * @param int $profile int
135 * @param array $profiledata array
136 * @param boolean $show_connect Show connect link
137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
138 * @throws \ImagickException
140 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
142 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
144 if (!DBA::isResult($user) && empty($profiledata)) {
145 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
149 if (count($profiledata) > 0) {
150 // Ensure to have a "nickname" field
151 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
152 $profiledata['nickname'] = $profiledata['nick'];
155 // Add profile data to sidebar
156 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
158 if (!DBA::isResult($user)) {
163 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
165 if (empty($pdata) && empty($profiledata)) {
166 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
171 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
174 // fetch user tags if this isn't the default profile
176 if (!$pdata['is-default']) {
177 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
178 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
179 if (DBA::isResult($profile)) {
180 $pdata['pub_keywords'] = $profile['pub_keywords'];
184 $a->profile = $pdata;
185 $a->profile_uid = $pdata['profile_uid'];
187 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
188 $a->profile['network'] = Protocol::DFRN;
190 DI::page()['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
192 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
193 $a->setCurrentTheme($a->profile['theme']);
194 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
198 * load/reload current theme info
201 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
203 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
204 if (file_exists($theme_info_file)) {
205 require_once $theme_info_file;
208 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
209 DI::page()['aside'] .= Renderer::replaceMacros(
210 Renderer::getMarkupTemplate('profile_edlink.tpl'),
212 '$editprofile' => L10n::t('Edit profile'),
213 '$profid' => $a->profile['id']
218 $block = ((Config::get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
222 * By now, the contact block isn't shown, when a different profile is given
223 * But: When this profile was on the same server, then we could display the contacts
226 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
233 * Get all profile data of a local user
235 * If the viewer is an authenticated remote viewer, the profile displayed is the
236 * one that has been configured for his/her viewing in the Contact manager.
237 * Passing a non-zero profile ID can also allow a preview of a selected profile
240 * Includes all available profile data
242 * @brief Get all profile data of a local user
243 * @param string $nickname nick
244 * @param int $uid uid
245 * @param int $profile_id ID of the profile
249 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
251 if (!empty(Session::getRemoteContactID($uid))) {
252 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => Session::getRemoteContactID($uid)]);
253 if (DBA::isResult($contact)) {
254 $profile_id = $contact['profile-id'];
261 $profile = DBA::fetchFirst(
262 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
263 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
264 `profile`.`uid` AS `profile_uid`, `profile`.*,
265 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
267 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
268 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
269 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
274 if (!DBA::isResult($profile)) {
275 $profile = DBA::fetchFirst(
276 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
277 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
278 `profile`.`uid` AS `profile_uid`, `profile`.*,
279 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
281 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
282 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
283 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
292 * Formats a profile for display in the sidebar.
294 * It is very difficult to templatise the HTML completely
295 * because of all the conditional logic.
297 * @brief Formats a profile for display in the sidebar.
298 * @param array $profile
300 * @param boolean $show_connect Show connect link
302 * @return string HTML sidebar module
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
306 * @note Returns empty string if passed $profile is wrong type or not populated
308 * @hooks 'profile_sidebar_enter'
309 * array $profile - profile data
310 * @hooks 'profile_sidebar'
313 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
318 // This function can also use contact information in $profile
319 $is_contact = !empty($profile['cid']);
321 if (!is_array($profile) && !count($profile)) {
325 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
327 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
328 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
330 $profile['network_link'] = '';
333 Hook::callAll('profile_sidebar_enter', $profile);
335 if (isset($profile['url'])) {
336 $profile_url = $profile['url'];
338 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
342 $unfollow_link = null;
343 $subscribe_feed_link = null;
344 $wallmessage_link = null;
348 $visitor_contact = [];
349 if (!empty($profile['uid']) && self::getMyURL()) {
350 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
353 $profile_contact = [];
354 if (!empty($profile['cid']) && self::getMyURL()) {
355 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
358 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
359 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
360 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
361 $visitor_is_authenticated = (bool)self::getMyURL();
362 $visitor_is_following =
363 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
364 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
365 $visitor_is_followed =
366 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
367 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
368 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
370 if (!$local_user_is_self && $show_connect) {
371 if (!$visitor_is_authenticated) {
372 if (!empty($profile['nickname'])) {
373 $follow_link = 'dfrn_request/' . $profile['nickname'];
375 } elseif ($profile_is_native) {
376 if ($visitor_is_following) {
377 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
379 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
383 if ($profile_is_dfrn) {
384 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
387 if (Contact::canReceivePrivateMessages($profile)) {
388 if ($visitor_is_followed || $visitor_is_following) {
389 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
390 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
391 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
396 // show edit profile to yourself
397 if (!$is_contact && $local_user_is_self) {
398 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
399 $profile['edit'] = [DI::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
401 "SELECT * FROM `profile` WHERE `uid` = %d",
406 'chg_photo' => L10n::t('Change profile photo'),
407 'cr_new' => L10n::t('Create New Profile'),
411 if (DBA::isResult($r)) {
412 foreach ($r as $rr) {
413 $profile['menu']['entries'][] = [
414 'photo' => $rr['thumb'],
416 'alt' => L10n::t('Profile Image'),
417 'profile_name' => $rr['profile-name'],
418 'isdefault' => $rr['is-default'],
419 'visibile_to_everybody' => L10n::t('visible to everybody'),
420 'edit_visibility' => L10n::t('Edit visibility'),
425 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
427 'chg_photo' => L10n::t('Change profile photo'),
434 // Fetch the account type
435 $account_type = Contact::getAccountType($profile);
437 if (!empty($profile['address'])
438 || !empty($profile['location'])
439 || !empty($profile['locality'])
440 || !empty($profile['region'])
441 || !empty($profile['postal-code'])
442 || !empty($profile['country-name'])
444 $location = L10n::t('Location:');
447 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
448 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
449 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
450 $about = !empty($profile['about']) ? L10n::t('About:') : false;
451 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
453 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
454 $location = $gender = $marital = $homepage = $about = false;
457 $split_name = Diaspora::splitName($profile['name']);
458 $firstname = $split_name['first'];
459 $lastname = $split_name['last'];
461 if (!empty($profile['guid'])) {
463 'guid' => $profile['guid'],
464 'podloc' => DI::baseUrl(),
465 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
466 'nickname' => $profile['nickname'],
467 'fullname' => $profile['name'],
468 'firstname' => $firstname,
469 'lastname' => $lastname,
470 'photo300' => $profile['contact_photo'] ?? '',
471 'photo100' => $profile['contact_thumb'] ?? '',
472 'photo50' => $profile['contact_micro'] ?? '',
482 $contact_block = ContactBlock::getHTML($a->profile);
484 if (is_array($a->profile) && !$a->profile['hide-friends']) {
486 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
487 intval($a->profile['uid'])
489 if (DBA::isResult($r)) {
490 $updated = date('c', strtotime($r[0]['updated']));
493 $contact_count = DBA::count('contact', [
494 'uid' => $profile['uid'],
500 'network' => Protocol::FEDERATED,
506 foreach ($profile as $k => $v) {
507 $k = str_replace('-', '_', $k);
511 if (isset($p['about'])) {
512 $p['about'] = BBCode::convert($p['about']);
515 if (empty($p['address']) && !empty($p['location'])) {
516 $p['address'] = $p['location'];
519 if (isset($p['address'])) {
520 $p['address'] = BBCode::convert($p['address']);
523 if (isset($p['gender'])) {
524 $p['gender'] = L10n::t($p['gender']);
527 if (isset($p['marital'])) {
528 $p['marital'] = L10n::t($p['marital']);
531 if (isset($p['photo'])) {
532 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
535 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
537 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
538 $o .= Renderer::replaceMacros($tpl, [
541 '$follow' => L10n::t('Follow'),
542 '$follow_link' => $follow_link,
543 '$unfollow' => L10n::t('Unfollow'),
544 '$unfollow_link' => $unfollow_link,
545 '$subscribe_feed' => L10n::t('Atom feed'),
546 '$subscribe_feed_link' => $subscribe_feed_link,
547 '$wallmessage' => L10n::t('Message'),
548 '$wallmessage_link' => $wallmessage_link,
549 '$account_type' => $account_type,
550 '$location' => $location,
551 '$gender' => $gender,
552 '$marital' => $marital,
553 '$homepage' => $homepage,
555 '$network' => L10n::t('Network:'),
556 '$contacts' => $contact_count,
557 '$updated' => $updated,
558 '$diaspora' => $diaspora,
559 '$contact_block' => $contact_block,
562 $arr = ['profile' => &$profile, 'entry' => &$o];
564 Hook::callAll('profile_sidebar', $arr);
569 public static function getBirthdays()
574 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
579 * $mobile_detect = new Mobile_Detect();
580 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
585 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
586 $bd_short = L10n::t('F d');
588 $cachekey = 'get_birthdays:' . local_user();
589 $r = DI::cache()->get($cachekey);
592 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
594 ON `contact`.`id` = `event`.`cid`
595 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
596 AND NOT `contact`.`pending`
597 AND NOT `contact`.`hidden`
598 AND NOT `contact`.`blocked`
599 AND NOT `contact`.`archive`
600 AND NOT `contact`.`deleted`
601 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
602 ORDER BY `start` ASC ",
606 DateTimeFormat::utc('now + 6 days'),
607 DateTimeFormat::utcNow()
609 if (DBA::isResult($s)) {
610 $r = DBA::toArray($s);
611 DI::cache()->set($cachekey, $r, Duration::HOUR);
617 if (DBA::isResult($r)) {
618 $now = strtotime('now');
622 foreach ($r as $rr) {
623 if (strlen($rr['name'])) {
626 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
630 $classtoday = $istoday ? ' birthday-today ' : '';
632 foreach ($r as &$rr) {
633 if (!strlen($rr['name'])) {
639 if (in_array($rr['cid'], $cids)) {
642 $cids[] = $rr['cid'];
644 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
646 $rr['link'] = Contact::magicLink($rr['url']);
647 $rr['title'] = $rr['name'];
648 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
649 $rr['startime'] = null;
650 $rr['today'] = $today;
654 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
655 return Renderer::replaceMacros($tpl, [
656 '$classtoday' => $classtoday,
658 '$event_reminders' => L10n::t('Birthday Reminders'),
659 '$event_title' => L10n::t('Birthdays this week:'),
661 '$lbr' => '{', // raw brackets mess up if/endif macro processing
666 public static function getEventsReminderHTML()
671 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
676 * $mobile_detect = new Mobile_Detect();
677 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
682 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
685 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
686 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
687 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
691 if (DBA::isResult($s)) {
695 while ($rr = DBA::fetch($s)) {
696 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
697 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
698 'visible' => true, 'deleted' => false];
699 if (!Item::exists($condition)) {
703 if (strlen($rr['summary'])) {
707 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
708 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
712 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
714 if (strlen($title) > 35) {
715 $title = substr($title, 0, 32) . '... ';
718 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
720 $description = L10n::t('[No description]');
723 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
725 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
729 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
731 $rr['title'] = $title;
732 $rr['description'] = $description;
733 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
734 $rr['startime'] = $strt;
735 $rr['today'] = $today;
740 $classtoday = (($istoday) ? 'event-today' : '');
742 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
743 return Renderer::replaceMacros($tpl, [
744 '$classtoday' => $classtoday,
745 '$count' => count($r),
746 '$event_reminders' => L10n::t('Event Reminders'),
747 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
752 public static function getAdvanced(App $a)
754 $uid = intval($a->profile['uid']);
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 = BBCode::convert($a->profile['about'])) {
829 $profile['about'] = [L10n::t('About:'), $txt];
832 if ($txt = BBCode::convert($a->profile['interest'])) {
833 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
836 if ($txt = BBCode::convert($a->profile['likes'])) {
837 $profile['likes'] = [L10n::t('Likes:'), $txt];
840 if ($txt = BBCode::convert($a->profile['dislikes'])) {
841 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
844 if ($txt = BBCode::convert($a->profile['contact'])) {
845 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
848 if ($txt = BBCode::convert($a->profile['music'])) {
849 $profile['music'] = [L10n::t('Musical interests:'), $txt];
852 if ($txt = BBCode::convert($a->profile['book'])) {
853 $profile['book'] = [L10n::t('Books, literature:'), $txt];
856 if ($txt = BBCode::convert($a->profile['tv'])) {
857 $profile['tv'] = [L10n::t('Television:'), $txt];
860 if ($txt = BBCode::convert($a->profile['film'])) {
861 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
864 if ($txt = BBCode::convert($a->profile['romance'])) {
865 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
868 if ($txt = BBCode::convert($a->profile['work'])) {
869 $profile['work'] = [L10n::t('Work/employment:'), $txt];
872 if ($txt = BBCode::convert($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'] = [DI::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
898 * @param string $current
899 * @param bool $is_owner
900 * @param string $nickname
902 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
904 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
906 if (is_null($nickname)) {
907 $nickname = $a->user['nickname'];
910 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
914 'label' => L10n::t('Status'),
915 'url' => $baseProfileUrl,
916 'sel' => !$current ? 'active' : '',
917 'title' => L10n::t('Status Messages and Posts'),
918 'id' => 'status-tab',
922 'label' => L10n::t('Profile'),
923 'url' => $baseProfileUrl . '/?tab=profile',
924 'sel' => $current == 'profile' ? 'active' : '',
925 'title' => L10n::t('Profile Details'),
926 'id' => 'profile-tab',
930 'label' => L10n::t('Photos'),
931 'url' => DI::baseUrl() . '/photos/' . $nickname,
932 'sel' => $current == 'photos' ? 'active' : '',
933 'title' => L10n::t('Photo Albums'),
938 'label' => L10n::t('Videos'),
939 'url' => DI::baseUrl() . '/videos/' . $nickname,
940 'sel' => $current == 'videos' ? 'active' : '',
941 'title' => L10n::t('Videos'),
947 // the calendar link for the full featured events calendar
948 if ($is_owner && $a->theme_events_in_profile) {
950 'label' => L10n::t('Events'),
951 'url' => DI::baseUrl() . '/events',
952 'sel' => $current == 'events' ? 'active' : '',
953 'title' => L10n::t('Events and Calendar'),
954 'id' => 'events-tab',
957 // if the user is not the owner of the calendar we only show a calendar
958 // with the public events of the calendar owner
959 } elseif (!$is_owner) {
961 'label' => L10n::t('Events'),
962 'url' => DI::baseUrl() . '/cal/' . $nickname,
963 'sel' => $current == 'cal' ? 'active' : '',
964 'title' => L10n::t('Events and Calendar'),
965 'id' => 'events-tab',
972 'label' => L10n::t('Personal Notes'),
973 'url' => DI::baseUrl() . '/notes',
974 'sel' => $current == 'notes' ? 'active' : '',
975 'title' => L10n::t('Only You Can See This'),
981 if (!empty($_SESSION['new_member']) && $is_owner) {
983 'label' => L10n::t('Tips for New Members'),
984 'url' => DI::baseUrl() . '/newmember',
986 'title' => L10n::t('Tips for New Members'),
987 'id' => 'newmember-tab',
991 if ($is_owner || empty($a->profile['hide-friends'])) {
993 'label' => L10n::t('Contacts'),
994 'url' => $baseProfileUrl . '/contacts',
995 'sel' => $current == 'contacts' ? 'active' : '',
996 'title' => L10n::t('Contacts'),
997 'id' => 'viewcontacts-tab',
1002 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
1003 Hook::callAll('profile_tabs', $arr);
1005 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1007 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1011 * Retrieves the my_url session variable
1015 public static function getMyURL()
1017 return Session::get('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 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
1030 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
1031 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
1033 * It would be favourable to harmonize the two implementations.
1035 * @param App $a Application instance.
1036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037 * @throws \ImagickException
1039 public static function zrlInit(App $a)
1041 $my_url = self::getMyURL();
1042 $my_url = Network::isUrlValid($my_url);
1044 if (empty($my_url) || local_user()) {
1048 $addr = $_GET['addr'] ?? $my_url;
1050 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1051 Hook::callAll('zrl_init', $arr);
1053 // Try to find the public contact entry of the visitor.
1054 $cid = Contact::getIdForURL($my_url);
1056 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1060 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1062 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1063 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1067 // Avoid endless loops
1068 $cachekey = 'zrlInit:' . $my_url;
1069 if (DI::cache()->get($cachekey)) {
1070 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1073 DI::cache()->set($cachekey, true, Duration::MINUTE);
1076 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1078 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1079 $addr_request = 'addr=' . urlencode($addr);
1080 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1082 // The other instance needs to know where to redirect.
1083 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1085 // We need to extract the basebath from the profile url
1086 // to redirect the visitors '/magic' module.
1087 $basepath = Contact::getBasepath($contact['url']);
1089 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1090 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1092 // We have to check if the remote server does understand /magic without invoking something
1093 $serverret = Network::curl($basepath . '/magic');
1094 if ($serverret->isSuccess()) {
1095 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1096 System::externalRedirect($magic_path);
1102 * Set the visitor cookies (see remote_user()) for the given handle
1104 * @param string $handle Visitor handle
1105 * @return array Visitor contact array
1107 public static function addVisitorCookieForHandle($handle)
1111 // Try to find the public contact entry of the visitor.
1112 $cid = Contact::getIdForURL($handle);
1114 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1118 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1120 // Authenticate the visitor.
1121 $_SESSION['authenticated'] = 1;
1122 $_SESSION['visitor_id'] = $visitor['id'];
1123 $_SESSION['visitor_handle'] = $visitor['addr'];
1124 $_SESSION['visitor_home'] = $visitor['url'];
1125 $_SESSION['my_url'] = $visitor['url'];
1127 Session::setVisitorsContacts();
1129 $a->contact = $visitor;
1131 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1137 * OpenWebAuth authentication.
1139 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1141 * @param string $token
1142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 * @throws \ImagickException
1145 public static function openWebAuthInit($token)
1149 // Clean old OpenWebAuthToken entries.
1150 OpenWebAuthToken::purge('owt', '3 MINUTE');
1152 // Check if the token we got is the same one
1153 // we have stored in the database.
1154 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1156 if ($visitor_handle === false) {
1160 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1161 if (empty($visitor)) {
1166 'visitor' => $visitor,
1167 'url' => DI::args()->getQueryString()
1170 * @hooks magic_auth_success
1171 * Called when a magic-auth was successful.
1172 * * \e array \b visitor
1173 * * \e string \b url
1175 Hook::callAll('magic_auth_success', $arr);
1177 $a->contact = $arr['visitor'];
1179 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1181 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1184 public static function zrl($s, $force = false)
1189 if (!strpos($s, '/profile/') && !$force) {
1192 if ($force && substr($s, -1, 1) !== '/') {
1195 $achar = strpos($s, '?') ? '&' : '?';
1196 $mine = self::getMyURL();
1197 if ($mine && !Strings::compareLink($mine, $s)) {
1198 return $s . $achar . 'zrl=' . urlencode($mine);
1204 * Get the user ID of the page owner.
1206 * Used from within PCSS themes to set theme parameters. If there's a
1207 * profile_uid variable set in App, that is the "page owner" and normally their theme
1208 * settings take precedence; unless a local user sets the "always_my_theme"
1209 * system pconfig, which means they don't want to see anybody else's theme
1210 * settings except their own while on this site.
1212 * @brief Get the user ID of the page owner
1213 * @return int user ID
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1218 public static function getThemeUid(App $a)
1220 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1221 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1222 return local_user();
1229 * search for Profiles
1233 * @param null $search
1235 * @return array [ 'total' => 123, 'entries' => [...] ];
1237 * @throws \Exception
1239 public static function searchProfiles($start = 0, $count = 100, $search = null)
1241 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1244 if (!empty($search)) {
1245 $searchTerm = '%' . $search . '%';
1246 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1248 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1249 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1250 AND ((`profile`.`name` LIKE ?) OR
1251 (`user`.`nickname` LIKE ?) OR
1252 (`profile`.`pdesc` LIKE ?) OR
1253 (`profile`.`locality` LIKE ?) OR
1254 (`profile`.`region` LIKE ?) OR
1255 (`profile`.`country-name` LIKE ?) OR
1256 (`profile`.`gender` LIKE ?) OR
1257 (`profile`.`marital` LIKE ?) OR
1258 (`profile`.`sexual` LIKE ?) OR
1259 (`profile`.`about` LIKE ?) OR
1260 (`profile`.`romance` LIKE ?) OR
1261 (`profile`.`work` LIKE ?) OR
1262 (`profile`.`education` LIKE ?) OR
1263 (`profile`.`pub_keywords` LIKE ?) OR
1264 (`profile`.`prv_keywords` LIKE ?))",
1265 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1266 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1268 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1270 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1271 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1274 if (DBA::isResult($cnt)) {
1275 $total = $cnt['total'];
1278 $order = " ORDER BY `name` ASC ";
1281 // If nothing found, don't try to select details
1283 if (!empty($search)) {
1284 $searchTerm = '%' . $search . '%';
1286 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1287 `contact`.`addr`, `contact`.`url` AS `profile_url`
1289 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1290 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1291 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1292 AND ((`profile`.`name` LIKE ?) OR
1293 (`user`.`nickname` LIKE ?) OR
1294 (`profile`.`pdesc` LIKE ?) OR
1295 (`profile`.`locality` LIKE ?) OR
1296 (`profile`.`region` LIKE ?) OR
1297 (`profile`.`country-name` LIKE ?) OR
1298 (`profile`.`gender` LIKE ?) OR
1299 (`profile`.`marital` LIKE ?) OR
1300 (`profile`.`sexual` LIKE ?) OR
1301 (`profile`.`about` LIKE ?) OR
1302 (`profile`.`romance` LIKE ?) OR
1303 (`profile`.`work` LIKE ?) OR
1304 (`profile`.`education` LIKE ?) OR
1305 (`profile`.`pub_keywords` LIKE ?) OR
1306 (`profile`.`prv_keywords` LIKE ?))
1308 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1309 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1313 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1314 `contact`.`addr`, `contact`.`url` AS `profile_url`
1316 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1317 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1318 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1325 if (DBA::isResult($profiles) && $total > 0) {
1328 'entries' => DBA::toArray($profiles),