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 default profile for a given user ID and ID
51 * @param int $uid The contact ID
52 * @param int $id The contact owner ID
53 * @param array $fields The selected fields
55 * @return array Profile data for the ID
58 public static function getById(int $uid, int $id, array $fields = [])
60 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
64 * @brief Returns profile data for the contact owner
66 * @param int $uid The User ID
67 * @param array $fields The fields to retrieve
69 * @return array Array of profile data
72 public static function getListByUser(int $uid, array $fields = [])
74 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
78 * @brief Returns a formatted location string from the given profile array
80 * @param array $profile Profile array (Generated from the "profile" table)
82 * @return string Location string
84 public static function formatLocation(array $profile)
88 if (!empty($profile['locality'])) {
89 $location .= $profile['locality'];
92 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
97 $location .= $profile['region'];
100 if (!empty($profile['country-name'])) {
105 $location .= $profile['country-name'];
113 * Loads a profile into the page sidebar.
115 * The function requires a writeable copy of the main App structure, and the nickname
116 * of a registered local account.
118 * If the viewer is an authenticated remote viewer, the profile displayed is the
119 * one that has been configured for his/her viewing in the Contact manager.
120 * Passing a non-zero profile ID can also allow a preview of a selected profile
123 * Profile information is placed in the App structure for later retrieval.
124 * Honours the owner's chosen theme for display.
126 * @attention Should only be run in the _init() functions of a module. That ensures that
127 * the theme is chosen before the _init() function of a theme is run, which will usually
128 * load a lot of theme-specific content
130 * @brief Loads a profile into the page sidebar.
132 * @param string $nickname string
133 * @param int $profile int
134 * @param array $profiledata array
135 * @param boolean $show_connect Show connect link
136 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
137 * @throws \ImagickException
139 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
141 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
143 if (!DBA::isResult($user) && empty($profiledata)) {
144 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
148 if (count($profiledata) > 0) {
149 // Ensure to have a "nickname" field
150 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
151 $profiledata['nickname'] = $profiledata['nick'];
154 // Add profile data to sidebar
155 $a->page['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
157 if (!DBA::isResult($user)) {
162 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
164 if (empty($pdata) && empty($profiledata)) {
165 Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
170 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
173 // fetch user tags if this isn't the default profile
175 if (!$pdata['is-default']) {
176 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
177 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
178 if (DBA::isResult($profile)) {
179 $pdata['pub_keywords'] = $profile['pub_keywords'];
183 $a->profile = $pdata;
184 $a->profile_uid = $pdata['profile_uid'];
186 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
187 $a->profile['network'] = Protocol::DFRN;
189 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
191 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
192 $_SESSION['theme'] = $a->profile['theme'];
195 $_SESSION['mobile-theme'] = $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 $a->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') && !local_user() && !remote_user()) ? 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 $a->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 (remote_user() && !empty($_SESSION['remote'])) {
252 foreach ($_SESSION['remote'] as $visitor) {
253 if ($visitor['uid'] == $uid) {
254 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
255 if (DBA::isResult($contact)) {
256 $profile_id = $contact['profile-id'];
266 $profile = DBA::fetchFirst(
267 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
268 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
269 `profile`.`uid` AS `profile_uid`, `profile`.*,
270 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
272 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
273 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
274 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
279 if (!DBA::isResult($profile)) {
280 $profile = DBA::fetchFirst(
281 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
282 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
283 `profile`.`uid` AS `profile_uid`, `profile`.*,
284 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
286 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
287 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
288 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
297 * Formats a profile for display in the sidebar.
299 * It is very difficult to templatise the HTML completely
300 * because of all the conditional logic.
302 * @brief Formats a profile for display in the sidebar.
303 * @param array $profile
305 * @param boolean $show_connect Show connect link
307 * @return string HTML sidebar module
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
311 * @note Returns empty string if passed $profile is wrong type or not populated
313 * @hooks 'profile_sidebar_enter'
314 * array $profile - profile data
315 * @hooks 'profile_sidebar'
318 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
323 // This function can also use contact information in $profile
324 $is_contact = !empty($profile['cid']);
326 if (!is_array($profile) && !count($profile)) {
330 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
332 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
333 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
335 $profile['network_link'] = '';
338 Hook::callAll('profile_sidebar_enter', $profile);
340 if (isset($profile['url'])) {
341 $profile_url = $profile['url'];
343 $profile_url = $a->getBaseURL() . '/profile/' . $profile['nickname'];
347 $unfollow_link = null;
348 $subscribe_feed_link = null;
349 $wallmessage_link = null;
353 $visitor_contact = [];
354 if (!empty($profile['uid']) && self::getMyURL()) {
355 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
358 $profile_contact = [];
359 if (!empty($profile['cid']) && self::getMyURL()) {
360 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
363 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
364 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
365 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
366 $visitor_is_authenticated = (bool)self::getMyURL();
367 $visitor_is_following =
368 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
369 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
370 $visitor_is_followed =
371 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
372 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
373 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
375 if (!$local_user_is_self && $show_connect) {
376 if (!$visitor_is_authenticated) {
377 $follow_link = 'dfrn_request/' . $profile['nickname'];
378 } elseif ($profile_is_native) {
379 if ($visitor_is_following) {
380 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
382 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
386 if ($profile_is_dfrn) {
387 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
390 if (Contact::canReceivePrivateMessages($profile)) {
391 if ($visitor_is_followed || $visitor_is_following) {
392 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode(defaults($profile, 'addr', ''));
393 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
394 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
399 // show edit profile to yourself
400 if (!$is_contact && $local_user_is_self) {
401 if (Feature::isEnabled(local_user(), 'multi_profiles')) {
402 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
404 "SELECT * FROM `profile` WHERE `uid` = %d",
409 'chg_photo' => L10n::t('Change profile photo'),
410 'cr_new' => L10n::t('Create New Profile'),
414 if (DBA::isResult($r)) {
415 foreach ($r as $rr) {
416 $profile['menu']['entries'][] = [
417 'photo' => $rr['thumb'],
419 'alt' => L10n::t('Profile Image'),
420 'profile_name' => $rr['profile-name'],
421 'isdefault' => $rr['is-default'],
422 'visibile_to_everybody' => L10n::t('visible to everybody'),
423 'edit_visibility' => L10n::t('Edit visibility'),
428 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
430 'chg_photo' => L10n::t('Change profile photo'),
437 // Fetch the account type
438 $account_type = Contact::getAccountType($profile);
440 if (!empty($profile['address'])
441 || !empty($profile['location'])
442 || !empty($profile['locality'])
443 || !empty($profile['region'])
444 || !empty($profile['postal-code'])
445 || !empty($profile['country-name'])
447 $location = L10n::t('Location:');
450 $gender = !empty($profile['gender']) ? L10n::t('Gender:') : false;
451 $marital = !empty($profile['marital']) ? L10n::t('Status:') : false;
452 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
453 $about = !empty($profile['about']) ? L10n::t('About:') : false;
454 $xmpp = !empty($profile['xmpp']) ? L10n::t('XMPP:') : false;
456 if ((!empty($profile['hidewall']) || $block) && !local_user() && !remote_user()) {
457 $location = $gender = $marital = $homepage = $about = false;
460 $split_name = Diaspora::splitName($profile['name']);
461 $firstname = $split_name['first'];
462 $lastname = $split_name['last'];
464 if (!empty($profile['guid'])) {
466 'guid' => $profile['guid'],
467 'podloc' => System::baseUrl(),
468 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
469 'nickname' => $profile['nickname'],
470 'fullname' => $profile['name'],
471 'firstname' => $firstname,
472 'lastname' => $lastname,
473 'photo300' => defaults($profile, 'contact_photo', ''),
474 'photo100' => defaults($profile, 'contact_thumb', ''),
475 'photo50' => defaults($profile, 'contact_micro', ''),
485 $contact_block = ContactBlock::getHTML($a->profile);
487 if (is_array($a->profile) && !$a->profile['hide-friends']) {
489 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
490 intval($a->profile['uid'])
492 if (DBA::isResult($r)) {
493 $updated = date('c', strtotime($r[0]['updated']));
496 $contact_count = DBA::count('contact', [
497 'uid' => $profile['uid'],
503 'network' => Protocol::FEDERATED,
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 '$follow' => L10n::t('Follow'),
537 '$follow_link' => $follow_link,
538 '$unfollow' => L10n::t('Unfollow'),
539 '$unfollow_link' => $unfollow_link,
540 '$subscribe_feed' => L10n::t('Atom feed'),
541 '$subscribe_feed_link' => $subscribe_feed_link,
542 '$wallmessage' => L10n::t('Message'),
543 '$wallmessage_link' => $wallmessage_link,
544 '$account_type' => $account_type,
545 '$location' => $location,
546 '$gender' => $gender,
547 '$marital' => $marital,
548 '$homepage' => $homepage,
550 '$network' => L10n::t('Network:'),
551 '$contacts' => $contact_count,
552 '$updated' => $updated,
553 '$diaspora' => $diaspora,
554 '$contact_block' => $contact_block,
557 $arr = ['profile' => &$profile, 'entry' => &$o];
559 Hook::callAll('profile_sidebar', $arr);
564 public static function getBirthdays()
569 if (!local_user() || $a->is_mobile || $a->is_tablet) {
574 * $mobile_detect = new Mobile_Detect();
575 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
580 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
581 $bd_short = L10n::t('F d');
583 $cachekey = 'get_birthdays:' . local_user();
584 $r = Cache::get($cachekey);
587 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
589 ON `contact`.`id` = `event`.`cid`
590 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
591 AND NOT `contact`.`pending`
592 AND NOT `contact`.`hidden`
593 AND NOT `contact`.`blocked`
594 AND NOT `contact`.`archive`
595 AND NOT `contact`.`deleted`
596 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
597 ORDER BY `start` ASC ",
601 DateTimeFormat::utc('now + 6 days'),
602 DateTimeFormat::utcNow()
604 if (DBA::isResult($s)) {
605 $r = DBA::toArray($s);
606 Cache::set($cachekey, $r, Cache::HOUR);
612 if (DBA::isResult($r)) {
613 $now = strtotime('now');
617 foreach ($r as $rr) {
618 if (strlen($rr['name'])) {
621 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
625 $classtoday = $istoday ? ' birthday-today ' : '';
627 foreach ($r as &$rr) {
628 if (!strlen($rr['name'])) {
634 if (in_array($rr['cid'], $cids)) {
637 $cids[] = $rr['cid'];
639 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
641 $rr['link'] = Contact::magicLink($rr['url']);
642 $rr['title'] = $rr['name'];
643 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
644 $rr['startime'] = null;
645 $rr['today'] = $today;
649 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
650 return Renderer::replaceMacros($tpl, [
651 '$classtoday' => $classtoday,
653 '$event_reminders' => L10n::t('Birthday Reminders'),
654 '$event_title' => L10n::t('Birthdays this week:'),
656 '$lbr' => '{', // raw brackets mess up if/endif macro processing
661 public static function getEventsReminderHTML()
666 if (!local_user() || $a->is_mobile || $a->is_tablet) {
671 * $mobile_detect = new Mobile_Detect();
672 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
677 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
680 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
681 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
682 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
686 if (DBA::isResult($s)) {
690 while ($rr = DBA::fetch($s)) {
691 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
692 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
693 'visible' => true, 'deleted' => false];
694 if (!Item::exists($condition)) {
698 if (strlen($rr['summary'])) {
702 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
703 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
707 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
709 if (strlen($title) > 35) {
710 $title = substr($title, 0, 32) . '... ';
713 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
715 $description = L10n::t('[No description]');
718 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
720 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
724 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
726 $rr['title'] = $title;
727 $rr['description'] = $description;
728 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
729 $rr['startime'] = $strt;
730 $rr['today'] = $today;
735 $classtoday = (($istoday) ? 'event-today' : '');
737 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
738 return Renderer::replaceMacros($tpl, [
739 '$classtoday' => $classtoday,
740 '$count' => count($r),
741 '$event_reminders' => L10n::t('Event Reminders'),
742 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
747 public static function getAdvanced(App $a)
749 $uid = intval($a->profile['uid']);
751 if ($a->profile['name']) {
752 $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
756 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
758 if (Feature::isEnabled($uid, 'profile_membersince')) {
759 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
762 if ($a->profile['gender']) {
763 $profile['gender'] = [L10n::t('Gender:'), L10n::t($a->profile['gender'])];
766 if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
767 $year_bd_format = L10n::t('j F, Y');
768 $short_bd_format = L10n::t('j F');
771 intval($a->profile['dob']) ?
772 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
773 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
776 $profile['birthday'] = [L10n::t('Birthday:'), $val];
779 if (!empty($a->profile['dob'])
780 && $a->profile['dob'] > DBA::NULL_DATE
781 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
783 $profile['age'] = [L10n::t('Age:'), $age];
786 if ($a->profile['marital']) {
787 $profile['marital'] = [L10n::t('Status:'), L10n::t($a->profile['marital'])];
790 /// @TODO Maybe use x() here, plus below?
791 if ($a->profile['with']) {
792 $profile['marital']['with'] = $a->profile['with'];
795 if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
796 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
799 if ($a->profile['sexual']) {
800 $profile['sexual'] = [L10n::t('Sexual Preference:'), L10n::t($a->profile['sexual'])];
803 if ($a->profile['homepage']) {
804 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
807 if ($a->profile['hometown']) {
808 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
811 if ($a->profile['pub_keywords']) {
812 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
815 if ($a->profile['politic']) {
816 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
819 if ($a->profile['religion']) {
820 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
823 if ($txt = prepare_text($a->profile['about'])) {
824 $profile['about'] = [L10n::t('About:'), $txt];
827 if ($txt = prepare_text($a->profile['interest'])) {
828 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
831 if ($txt = prepare_text($a->profile['likes'])) {
832 $profile['likes'] = [L10n::t('Likes:'), $txt];
835 if ($txt = prepare_text($a->profile['dislikes'])) {
836 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
839 if ($txt = prepare_text($a->profile['contact'])) {
840 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
843 if ($txt = prepare_text($a->profile['music'])) {
844 $profile['music'] = [L10n::t('Musical interests:'), $txt];
847 if ($txt = prepare_text($a->profile['book'])) {
848 $profile['book'] = [L10n::t('Books, literature:'), $txt];
851 if ($txt = prepare_text($a->profile['tv'])) {
852 $profile['tv'] = [L10n::t('Television:'), $txt];
855 if ($txt = prepare_text($a->profile['film'])) {
856 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
859 if ($txt = prepare_text($a->profile['romance'])) {
860 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
863 if ($txt = prepare_text($a->profile['work'])) {
864 $profile['work'] = [L10n::t('Work/employment:'), $txt];
867 if ($txt = prepare_text($a->profile['education'])) {
868 $profile['education'] = [L10n::t('School/education:'), $txt];
871 //show subcribed forum if it is enabled in the usersettings
872 if (Feature::isEnabled($uid, 'forumlist_profile')) {
873 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
876 if ($a->profile['uid'] == local_user()) {
877 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
880 return Renderer::replaceMacros($tpl, [
881 '$title' => L10n::t('Profile'),
882 '$basic' => L10n::t('Basic'),
883 '$advanced' => L10n::t('Advanced'),
884 '$profile' => $profile
893 * @param string $current
894 * @param bool $is_owner
895 * @param string $nickname
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
899 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
901 if (is_null($nickname)) {
902 $nickname = $a->user['nickname'];
905 $baseProfileUrl = System::baseUrl() . '/profile/' . $nickname;
909 'label' => L10n::t('Status'),
910 'url' => $baseProfileUrl,
911 'sel' => !$current ? 'active' : '',
912 'title' => L10n::t('Status Messages and Posts'),
913 'id' => 'status-tab',
917 'label' => L10n::t('Profile'),
918 'url' => $baseProfileUrl . '/?tab=profile',
919 'sel' => $current == 'profile' ? 'active' : '',
920 'title' => L10n::t('Profile Details'),
921 'id' => 'profile-tab',
925 'label' => L10n::t('Photos'),
926 'url' => System::baseUrl() . '/photos/' . $nickname,
927 'sel' => $current == 'photos' ? 'active' : '',
928 'title' => L10n::t('Photo Albums'),
933 'label' => L10n::t('Videos'),
934 'url' => System::baseUrl() . '/videos/' . $nickname,
935 'sel' => $current == 'videos' ? 'active' : '',
936 'title' => L10n::t('Videos'),
942 // the calendar link for the full featured events calendar
943 if ($is_owner && $a->theme_events_in_profile) {
945 'label' => L10n::t('Events'),
946 'url' => System::baseUrl() . '/events',
947 'sel' => $current == 'events' ? 'active' : '',
948 'title' => L10n::t('Events and Calendar'),
949 'id' => 'events-tab',
952 // if the user is not the owner of the calendar we only show a calendar
953 // with the public events of the calendar owner
954 } elseif (!$is_owner) {
956 'label' => L10n::t('Events'),
957 'url' => System::baseUrl() . '/cal/' . $nickname,
958 'sel' => $current == 'cal' ? 'active' : '',
959 'title' => L10n::t('Events and Calendar'),
960 'id' => 'events-tab',
967 'label' => L10n::t('Personal Notes'),
968 'url' => System::baseUrl() . '/notes',
969 'sel' => $current == 'notes' ? 'active' : '',
970 'title' => L10n::t('Only You Can See This'),
976 if (!empty($_SESSION['new_member']) && $is_owner) {
978 'label' => L10n::t('Tips for New Members'),
979 'url' => System::baseUrl() . '/newmember',
981 'title' => L10n::t('Tips for New Members'),
982 'id' => 'newmember-tab',
986 if ($is_owner || empty($a->profile['hide-friends'])) {
988 'label' => L10n::t('Contacts'),
989 'url' => $baseProfileUrl . '/contacts',
990 'sel' => $current == 'contacts' ? 'active' : '',
991 'title' => L10n::t('Contacts'),
992 'id' => 'viewcontacts-tab',
997 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
998 Hook::callAll('profile_tabs', $arr);
1000 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1002 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1006 * Retrieves the my_url session variable
1010 public static function getMyURL()
1012 return Session::get('my_url');
1016 * Process the 'zrl' parameter and initiate the remote authentication.
1018 * This method checks if the visitor has a public contact entry and
1019 * redirects the visitor to his/her instance to start the magic auth (Authentication)
1022 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1024 * @param App $a Application instance.
1025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1026 * @throws \ImagickException
1028 public static function zrlInit(App $a)
1030 $my_url = self::getMyURL();
1031 $my_url = Network::isUrlValid($my_url);
1033 if (empty($my_url) || local_user()) {
1037 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1038 Hook::callAll('zrl_init', $arr);
1040 // Try to find the public contact entry of the visitor.
1041 $cid = Contact::getIdForURL($my_url);
1043 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1047 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1049 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1050 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1054 // Avoid endless loops
1055 $cachekey = 'zrlInit:' . $my_url;
1056 if (Cache::get($cachekey)) {
1057 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1060 Cache::set($cachekey, true, Cache::MINUTE);
1063 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1065 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1067 // Try to avoid recursion - but send them home to do a proper magic auth.
1068 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1069 // The other instance needs to know where to redirect.
1070 $dest = urlencode($a->getBaseURL() . '/' . $query);
1072 // We need to extract the basebath from the profile url
1073 // to redirect the visitors '/magic' module.
1074 // Note: We should have the basepath of a contact also in the contact table.
1075 $urlarr = explode('/profile/', $contact['url']);
1076 $basepath = $urlarr[0];
1078 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1079 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1081 // We have to check if the remote server does understand /magic without invoking something
1082 $serverret = Network::curl($basepath . '/magic');
1083 if ($serverret->isSuccess()) {
1084 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1085 System::externalRedirect($magic_path);
1091 * Set the visitor cookies (see remote_user()) for the given handle
1093 * @param string $handle Visitor handle
1094 * @return array Visitor contact array
1096 public static function addVisitorCookieForHandle($handle)
1100 // Try to find the public contact entry of the visitor.
1101 $cid = Contact::getIdForURL($handle);
1103 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1107 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1109 // Authenticate the visitor.
1110 $_SESSION['authenticated'] = 1;
1111 $_SESSION['visitor_id'] = $visitor['id'];
1112 $_SESSION['visitor_handle'] = $visitor['addr'];
1113 $_SESSION['visitor_home'] = $visitor['url'];
1114 $_SESSION['my_url'] = $visitor['url'];
1116 /// @todo replace this and the query for this variable with some cleaner functionality
1117 $_SESSION['remote'] = [];
1119 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1120 while ($contact = DBA::fetch($remote_contacts)) {
1121 if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1125 $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
1128 $a->contact = $visitor;
1130 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1136 * OpenWebAuth authentication.
1138 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1140 * @param string $token
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function openWebAuthInit($token)
1148 // Clean old OpenWebAuthToken entries.
1149 OpenWebAuthToken::purge('owt', '3 MINUTE');
1151 // Check if the token we got is the same one
1152 // we have stored in the database.
1153 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1155 if ($visitor_handle === false) {
1159 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1160 if (empty($visitor)) {
1165 'visitor' => $visitor,
1166 'url' => $a->query_string
1169 * @hooks magic_auth_success
1170 * Called when a magic-auth was successful.
1171 * * \e array \b visitor
1172 * * \e string \b url
1174 Hook::callAll('magic_auth_success', $arr);
1176 $a->contact = $arr['visitor'];
1178 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1180 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1183 public static function zrl($s, $force = false)
1188 if ((!strpos($s, '/profile/')) && (!$force)) {
1191 if ($force && substr($s, -1, 1) !== '/') {
1194 $achar = strpos($s, '?') ? '&' : '?';
1195 $mine = self::getMyURL();
1196 if ($mine && !Strings::compareLink($mine, $s)) {
1197 return $s . $achar . 'zrl=' . urlencode($mine);
1203 * Get the user ID of the page owner.
1205 * Used from within PCSS themes to set theme parameters. If there's a
1206 * profile_uid variable set in App, that is the "page owner" and normally their theme
1207 * settings take precedence; unless a local user sets the "always_my_theme"
1208 * system pconfig, which means they don't want to see anybody else's theme
1209 * settings except their own while on this site.
1211 * @brief Get the user ID of the page owner
1212 * @return int user ID
1214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1215 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1217 public static function getThemeUid(App $a)
1219 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1220 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1221 return local_user();
1228 * Strip zrl parameter from a string.
1230 * @param string $s The input string.
1231 * @return string The zrl.
1233 public static function stripZrls($s)
1235 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1239 * Strip query parameter from a string.
1241 * @param string $s The input string.
1243 * @return string The query parameter.
1245 public static function stripQueryParam($s, $param)
1247 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1251 * search for Profiles
1255 * @param null $search
1257 * @return array [ 'total' => 123, 'entries' => [...] ];
1259 * @throws \Exception
1261 public static function searchProfiles($start = 0, $count = 100, $search = null)
1263 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1266 if (!empty($search)) {
1267 $searchTerm = '%' . $search . '%';
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`
1272 AND ((`profile`.`name` LIKE ?) OR
1273 (`user`.`nickname` LIKE ?) OR
1274 (`profile`.`pdesc` LIKE ?) OR
1275 (`profile`.`locality` LIKE ?) OR
1276 (`profile`.`region` LIKE ?) OR
1277 (`profile`.`country-name` LIKE ?) OR
1278 (`profile`.`gender` LIKE ?) OR
1279 (`profile`.`marital` LIKE ?) OR
1280 (`profile`.`sexual` LIKE ?) OR
1281 (`profile`.`about` LIKE ?) OR
1282 (`profile`.`romance` LIKE ?) OR
1283 (`profile`.`work` LIKE ?) OR
1284 (`profile`.`education` LIKE ?) OR
1285 (`profile`.`pub_keywords` LIKE ?) OR
1286 (`profile`.`prv_keywords` LIKE ?))",
1287 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1288 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1290 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1292 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1293 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1296 if (DBA::isResult($cnt)) {
1297 $total = $cnt['total'];
1300 $order = " ORDER BY `name` ASC ";
1303 // If nothing found, don't try to select details
1305 if (!empty($search)) {
1306 $searchTerm = '%' . $search . '%';
1308 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1309 `contact`.`addr`, `contact`.`url` AS `profile_url`
1311 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1312 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1313 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1314 AND ((`profile`.`name` LIKE ?) OR
1315 (`user`.`nickname` LIKE ?) OR
1316 (`profile`.`pdesc` LIKE ?) OR
1317 (`profile`.`locality` LIKE ?) OR
1318 (`profile`.`region` LIKE ?) OR
1319 (`profile`.`country-name` LIKE ?) OR
1320 (`profile`.`gender` LIKE ?) OR
1321 (`profile`.`marital` LIKE ?) OR
1322 (`profile`.`sexual` LIKE ?) OR
1323 (`profile`.`about` LIKE ?) OR
1324 (`profile`.`romance` LIKE ?) OR
1325 (`profile`.`work` LIKE ?) OR
1326 (`profile`.`education` LIKE ?) OR
1327 (`profile`.`pub_keywords` LIKE ?) OR
1328 (`profile`.`prv_keywords` LIKE ?))
1330 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1331 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1335 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1336 `contact`.`addr`, `contact`.`url` AS `profile_url`
1338 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1339 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1340 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1347 if (DBA::isResult($profiles) && $total > 0) {
1350 'entries' => DBA::toArray($profiles),