3 * @file src/Model/Profile.php
5 namespace Friendica\Model;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Content\Widget\ContactBlock;
10 use Friendica\Core\Cache\Duration;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
19 use Friendica\Protocol\Activity;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Proxy as ProxyUtils;
24 use Friendica\Util\Strings;
29 * Returns default profile for a given user id
31 * @param integer User ID
33 * @return array Profile data
36 public static function getByUID($uid)
38 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
43 * Returns default profile for a given user ID and ID
45 * @param int $uid The contact ID
46 * @param int $id The contact owner ID
47 * @param array $fields The selected fields
49 * @return array Profile data for the ID
52 public static function getById(int $uid, int $id, array $fields = [])
54 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
58 * Returns profile data for the contact owner
60 * @param int $uid The User ID
61 * @param array $fields The fields to retrieve
63 * @return array Array of profile data
66 public static function getListByUser(int $uid, array $fields = [])
68 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
72 * Returns a formatted location string from the given profile array
74 * @param array $profile Profile array (Generated from the "profile" table)
76 * @return string Location string
78 public static function formatLocation(array $profile)
82 if (!empty($profile['locality'])) {
83 $location .= $profile['locality'];
86 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
91 $location .= $profile['region'];
94 if (!empty($profile['country-name'])) {
99 $location .= $profile['country-name'];
106 * Loads a profile into the page sidebar.
108 * The function requires a writeable copy of the main App structure, and the nickname
109 * of a registered local account.
111 * If the viewer is an authenticated remote viewer, the profile displayed is the
112 * one that has been configured for his/her viewing in the Contact manager.
113 * Passing a non-zero profile ID can also allow a preview of a selected profile
116 * Profile information is placed in the App structure for later retrieval.
117 * Honours the owner's chosen theme for display.
119 * @attention Should only be run in the _init() functions of a module. That ensures that
120 * the theme is chosen before the _init() function of a theme is run, which will usually
121 * load a lot of theme-specific content
124 * @param string $nickname string
125 * @param int $profile_id int
126 * @param array $profiledata array
127 * @param boolean $show_connect Show connect link
128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 * @throws \ImagickException
131 public static function load(App $a, $nickname, $profile_id = 0, array $profiledata = [], $show_connect = true)
133 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
135 if (!DBA::isResult($user) && empty($profiledata)) {
136 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
140 if (count($profiledata) > 0) {
141 // Ensure to have a "nickname" field
142 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
143 $profiledata['nickname'] = $profiledata['nick'];
146 // Add profile data to sidebar
147 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
149 if (!DBA::isResult($user)) {
154 $profile = self::getByNickname($nickname, $user['uid'], $profile_id);
156 if (empty($profile) && empty($profiledata)) {
157 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
161 if (empty($profile)) {
162 $profile = ['uid' => 0, 'is-default' => false,'name' => $nickname];
165 // fetch user tags if this isn't the default profile
167 if (!$profile['is-default']) {
168 $condition = ['uid' => $profile['uid'], 'is-default' => true];
169 $profile_id = DBA::selectFirst('profile', ['pub_keywords'], $condition);
170 if (DBA::isResult($profile_id)) {
171 $profile['pub_keywords'] = $profile_id['pub_keywords'];
175 $a->profile = $profile;
176 $a->profile_uid = $profile['uid'];
178 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['uid'], 'system', 'mobile_theme');
179 $a->profile['network'] = Protocol::DFRN;
181 DI::page()['title'] = $a->profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
183 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
184 $a->setCurrentTheme($a->profile['theme']);
185 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
189 * load/reload current theme info
192 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
194 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
195 if (file_exists($theme_info_file)) {
196 require_once $theme_info_file;
199 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
200 DI::page()['aside'] .= Renderer::replaceMacros(
201 Renderer::getMarkupTemplate('settings/profile/link.tpl'),
203 '$editprofile' => DI::l10n()->t('Edit profile'),
204 '$profid' => $a->profile['id']
209 $block = ((DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
213 * By now, the contact block isn't shown, when a different profile is given
214 * But: When this profile was on the same server, then we could display the contacts
217 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
224 * Get all profile data of a local user
226 * If the viewer is an authenticated remote viewer, the profile displayed is the
227 * one that has been configured for his/her viewing in the Contact manager.
228 * Passing a non-zero profile ID can also allow a preview of a selected profile
231 * Includes all available profile data
233 * @param string $nickname nick
234 * @param int $uid uid
235 * @param int $profile_id ID of the profile
239 public static function getByNickname($nickname, $uid = 0)
241 $profile = DBA::fetchFirst(
242 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
243 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
245 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
247 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
248 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
249 WHERE `user`.`nickname` = ? AND `profile`.`uid` = ? LIMIT 1",
258 * Formats a profile for display in the sidebar.
260 * It is very difficult to templatise the HTML completely
261 * because of all the conditional logic.
263 * @param array $profile
265 * @param boolean $show_connect Show connect link
267 * @return string HTML sidebar module
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 * @throws \ImagickException
271 * @note Returns empty string if passed $profile is wrong type or not populated
273 * @hooks 'profile_sidebar_enter'
274 * array $profile - profile data
275 * @hooks 'profile_sidebar'
278 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
283 // This function can also use contact information in $profile
284 $is_contact = !empty($profile['cid']);
286 if (!is_array($profile) && !count($profile)) {
290 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
292 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
293 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
295 $profile['network_link'] = '';
298 Hook::callAll('profile_sidebar_enter', $profile);
300 if (isset($profile['url'])) {
301 $profile_url = $profile['url'];
303 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
307 $unfollow_link = null;
308 $subscribe_feed_link = null;
309 $wallmessage_link = null;
313 $visitor_contact = [];
314 if (!empty($profile['uid']) && self::getMyURL()) {
315 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
318 $profile_contact = [];
319 if (!empty($profile['cid']) && self::getMyURL()) {
320 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
323 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
324 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
325 $local_user_is_self = local_user() && local_user() == ($profile['uid'] ?? 0);
326 $visitor_is_authenticated = (bool)self::getMyURL();
327 $visitor_is_following =
328 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
329 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
330 $visitor_is_followed =
331 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
332 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
333 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
335 if (!$local_user_is_self && $show_connect) {
336 if (!$visitor_is_authenticated) {
337 if (!empty($profile['nickname'])) {
338 $follow_link = 'dfrn_request/' . $profile['nickname'];
340 } elseif ($profile_is_native) {
341 if ($visitor_is_following) {
342 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
344 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
348 if ($profile_is_dfrn) {
349 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
352 if (Contact::canReceivePrivateMessages($profile)) {
353 if ($visitor_is_followed || $visitor_is_following) {
354 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
355 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
356 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
361 // show edit profile to yourself
362 if (!$is_contact && $local_user_is_self) {
363 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
365 'chg_photo' => DI::l10n()->t('Change profile photo'),
371 // Fetch the account type
372 $account_type = Contact::getAccountType($profile);
374 if (!empty($profile['address'])
375 || !empty($profile['location'])
376 || !empty($profile['locality'])
377 || !empty($profile['region'])
378 || !empty($profile['postal-code'])
379 || !empty($profile['country-name'])
381 $location = DI::l10n()->t('Location:');
384 $gender = !empty($profile['gender']) ? DI::l10n()->t('Gender:') : false;
385 $marital = !empty($profile['marital']) ? DI::l10n()->t('Status:') : false;
386 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
387 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
388 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
390 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
391 $location = $gender = $marital = $homepage = $about = false;
394 $split_name = Diaspora::splitName($profile['name']);
395 $firstname = $split_name['first'];
396 $lastname = $split_name['last'];
398 if (!empty($profile['guid'])) {
400 'guid' => $profile['guid'],
401 'podloc' => DI::baseUrl(),
402 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
403 'nickname' => $profile['nickname'],
404 'fullname' => $profile['name'],
405 'firstname' => $firstname,
406 'lastname' => $lastname,
407 'photo300' => $profile['contact_photo'] ?? '',
408 'photo100' => $profile['contact_thumb'] ?? '',
409 'photo50' => $profile['contact_micro'] ?? '',
419 $contact_block = ContactBlock::getHTML($a->profile);
421 if (is_array($a->profile) && !$a->profile['hide-friends']) {
423 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
424 intval($a->profile['uid'])
426 if (DBA::isResult($r)) {
427 $updated = date('c', strtotime($r[0]['updated']));
430 $contact_count = DBA::count('contact', [
431 'uid' => $profile['uid'],
437 'network' => Protocol::FEDERATED,
443 foreach ($profile as $k => $v) {
444 $k = str_replace('-', '_', $k);
448 if (isset($p['about'])) {
449 $p['about'] = BBCode::convert($p['about']);
452 if (empty($p['address']) && !empty($p['location'])) {
453 $p['address'] = $p['location'];
456 if (isset($p['address'])) {
457 $p['address'] = BBCode::convert($p['address']);
460 if (isset($p['gender'])) {
461 $p['gender'] = DI::l10n()->t($p['gender']);
464 if (isset($p['marital'])) {
465 $p['marital'] = DI::l10n()->t($p['marital']);
468 if (isset($p['photo'])) {
469 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
472 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
474 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
475 $o .= Renderer::replaceMacros($tpl, [
478 '$follow' => DI::l10n()->t('Follow'),
479 '$follow_link' => $follow_link,
480 '$unfollow' => DI::l10n()->t('Unfollow'),
481 '$unfollow_link' => $unfollow_link,
482 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
483 '$subscribe_feed_link' => $subscribe_feed_link,
484 '$wallmessage' => DI::l10n()->t('Message'),
485 '$wallmessage_link' => $wallmessage_link,
486 '$account_type' => $account_type,
487 '$location' => $location,
488 '$gender' => $gender,
489 '$marital' => $marital,
490 '$homepage' => $homepage,
492 '$network' => DI::l10n()->t('Network:'),
493 '$contacts' => $contact_count,
494 '$updated' => $updated,
495 '$diaspora' => $diaspora,
496 '$contact_block' => $contact_block,
499 $arr = ['profile' => &$profile, 'entry' => &$o];
501 Hook::callAll('profile_sidebar', $arr);
506 public static function getBirthdays()
511 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
516 * $mobile_detect = new Mobile_Detect();
517 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
522 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
523 $bd_short = DI::l10n()->t('F d');
525 $cachekey = 'get_birthdays:' . local_user();
526 $r = DI::cache()->get($cachekey);
529 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
531 ON `contact`.`id` = `event`.`cid`
532 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
533 AND NOT `contact`.`pending`
534 AND NOT `contact`.`hidden`
535 AND NOT `contact`.`blocked`
536 AND NOT `contact`.`archive`
537 AND NOT `contact`.`deleted`
538 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
539 ORDER BY `start` ASC ",
543 DateTimeFormat::utc('now + 6 days'),
544 DateTimeFormat::utcNow()
546 if (DBA::isResult($s)) {
547 $r = DBA::toArray($s);
548 DI::cache()->set($cachekey, $r, Duration::HOUR);
554 if (DBA::isResult($r)) {
555 $now = strtotime('now');
559 foreach ($r as $rr) {
560 if (strlen($rr['name'])) {
563 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
567 $classtoday = $istoday ? ' birthday-today ' : '';
569 foreach ($r as &$rr) {
570 if (!strlen($rr['name'])) {
576 if (in_array($rr['cid'], $cids)) {
579 $cids[] = $rr['cid'];
581 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
583 $rr['link'] = Contact::magicLink($rr['url']);
584 $rr['title'] = $rr['name'];
585 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
586 $rr['startime'] = null;
587 $rr['today'] = $today;
591 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
592 return Renderer::replaceMacros($tpl, [
593 '$classtoday' => $classtoday,
595 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
596 '$event_title' => DI::l10n()->t('Birthdays this week:'),
598 '$lbr' => '{', // raw brackets mess up if/endif macro processing
603 public static function getEventsReminderHTML()
608 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
613 * $mobile_detect = new Mobile_Detect();
614 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
619 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
622 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
623 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
624 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
628 if (DBA::isResult($s)) {
632 while ($rr = DBA::fetch($s)) {
633 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
634 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
635 'visible' => true, 'deleted' => false];
636 if (!Item::exists($condition)) {
640 if (strlen($rr['summary'])) {
644 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
645 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
649 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
651 if (strlen($title) > 35) {
652 $title = substr($title, 0, 32) . '... ';
655 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
657 $description = DI::l10n()->t('[No description]');
660 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
662 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
666 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
668 $rr['title'] = $title;
669 $rr['description'] = $description;
670 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
671 $rr['startime'] = $strt;
672 $rr['today'] = $today;
677 $classtoday = (($istoday) ? 'event-today' : '');
679 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
680 return Renderer::replaceMacros($tpl, [
681 '$classtoday' => $classtoday,
682 '$count' => count($r),
683 '$event_reminders' => DI::l10n()->t('Event Reminders'),
684 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
691 * @param string $current
692 * @param bool $is_owner
693 * @param string $nickname
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
699 if (is_null($nickname)) {
700 $nickname = $a->user['nickname'];
703 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
707 'label' => DI::l10n()->t('Profile'),
708 'url' => $baseProfileUrl,
709 'sel' => $current == 'profile' ? 'active' : '',
710 'title' => DI::l10n()->t('Profile Details'),
711 'id' => 'profile-tab',
715 'label' => DI::l10n()->t('Status'),
716 'url' => $baseProfileUrl . '/status',
717 'sel' => $current == 'status' ? 'active' : '',
718 'title' => DI::l10n()->t('Status Messages and Posts'),
719 'id' => 'status-tab',
723 'label' => DI::l10n()->t('Photos'),
724 'url' => DI::baseUrl() . '/photos/' . $nickname,
725 'sel' => $current == 'photos' ? 'active' : '',
726 'title' => DI::l10n()->t('Photo Albums'),
731 'label' => DI::l10n()->t('Videos'),
732 'url' => DI::baseUrl() . '/videos/' . $nickname,
733 'sel' => $current == 'videos' ? 'active' : '',
734 'title' => DI::l10n()->t('Videos'),
740 // the calendar link for the full featured events calendar
741 if ($is_owner && $a->theme_events_in_profile) {
743 'label' => DI::l10n()->t('Events'),
744 'url' => DI::baseUrl() . '/events',
745 'sel' => $current == 'events' ? 'active' : '',
746 'title' => DI::l10n()->t('Events and Calendar'),
747 'id' => 'events-tab',
750 // if the user is not the owner of the calendar we only show a calendar
751 // with the public events of the calendar owner
752 } elseif (!$is_owner) {
754 'label' => DI::l10n()->t('Events'),
755 'url' => DI::baseUrl() . '/cal/' . $nickname,
756 'sel' => $current == 'cal' ? 'active' : '',
757 'title' => DI::l10n()->t('Events and Calendar'),
758 'id' => 'events-tab',
765 'label' => DI::l10n()->t('Personal Notes'),
766 'url' => DI::baseUrl() . '/notes',
767 'sel' => $current == 'notes' ? 'active' : '',
768 'title' => DI::l10n()->t('Only You Can See This'),
774 if (empty($a->profile['hide-friends'])) {
776 'label' => DI::l10n()->t('Contacts'),
777 'url' => $baseProfileUrl . '/contacts',
778 'sel' => $current == 'contacts' ? 'active' : '',
779 'title' => DI::l10n()->t('Contacts'),
780 'id' => 'viewcontacts-tab',
785 if (!empty($_SESSION['new_member']) && $is_owner) {
787 'label' => DI::l10n()->t('Tips for New Members'),
788 'url' => DI::baseUrl() . '/newmember',
790 'title' => DI::l10n()->t('Tips for New Members'),
791 'id' => 'newmember-tab',
795 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
797 Hook::callAll('profile_tabs', $arr);
799 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
801 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
805 * Retrieves the my_url session variable
809 public static function getMyURL()
811 return Session::get('my_url');
815 * Process the 'zrl' parameter and initiate the remote authentication.
817 * This method checks if the visitor has a public contact entry and
818 * redirects the visitor to his/her instance to start the magic auth (Authentication)
821 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
823 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
824 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
825 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
827 * It would be favourable to harmonize the two implementations.
829 * @param App $a Application instance.
830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831 * @throws \ImagickException
833 public static function zrlInit(App $a)
835 $my_url = self::getMyURL();
836 $my_url = Network::isUrlValid($my_url);
838 if (empty($my_url) || local_user()) {
842 $addr = $_GET['addr'] ?? $my_url;
844 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
845 Hook::callAll('zrl_init', $arr);
847 // Try to find the public contact entry of the visitor.
848 $cid = Contact::getIdForURL($my_url);
850 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
854 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
856 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
857 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
861 // Avoid endless loops
862 $cachekey = 'zrlInit:' . $my_url;
863 if (DI::cache()->get($cachekey)) {
864 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
867 DI::cache()->set($cachekey, true, Duration::MINUTE);
870 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
872 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
873 $addr_request = 'addr=' . urlencode($addr);
874 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
876 // The other instance needs to know where to redirect.
877 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
879 // We need to extract the basebath from the profile url
880 // to redirect the visitors '/magic' module.
881 $basepath = Contact::getBasepath($contact['url']);
883 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
884 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
886 // We have to check if the remote server does understand /magic without invoking something
887 $serverret = Network::curl($basepath . '/magic');
888 if ($serverret->isSuccess()) {
889 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
890 System::externalRedirect($magic_path);
896 * Set the visitor cookies (see remote_user()) for the given handle
898 * @param string $handle Visitor handle
899 * @return array Visitor contact array
901 public static function addVisitorCookieForHandle($handle)
905 // Try to find the public contact entry of the visitor.
906 $cid = Contact::getIdForURL($handle);
908 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
912 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
914 // Authenticate the visitor.
915 $_SESSION['authenticated'] = 1;
916 $_SESSION['visitor_id'] = $visitor['id'];
917 $_SESSION['visitor_handle'] = $visitor['addr'];
918 $_SESSION['visitor_home'] = $visitor['url'];
919 $_SESSION['my_url'] = $visitor['url'];
921 Session::setVisitorsContacts();
923 $a->contact = $visitor;
925 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
931 * OpenWebAuth authentication.
933 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
935 * @param string $token
936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
937 * @throws \ImagickException
939 public static function openWebAuthInit($token)
943 // Clean old OpenWebAuthToken entries.
944 OpenWebAuthToken::purge('owt', '3 MINUTE');
946 // Check if the token we got is the same one
947 // we have stored in the database.
948 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
950 if ($visitor_handle === false) {
954 $visitor = self::addVisitorCookieForHandle($visitor_handle);
955 if (empty($visitor)) {
960 'visitor' => $visitor,
961 'url' => DI::args()->getQueryString()
964 * @hooks magic_auth_success
965 * Called when a magic-auth was successful.
966 * * \e array \b visitor
969 Hook::callAll('magic_auth_success', $arr);
971 $a->contact = $arr['visitor'];
973 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
975 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
978 public static function zrl($s, $force = false)
983 if (!strpos($s, '/profile/') && !$force) {
986 if ($force && substr($s, -1, 1) !== '/') {
989 $achar = strpos($s, '?') ? '&' : '?';
990 $mine = self::getMyURL();
991 if ($mine && !Strings::compareLink($mine, $s)) {
992 return $s . $achar . 'zrl=' . urlencode($mine);
998 * Get the user ID of the page owner.
1000 * Used from within PCSS themes to set theme parameters. If there's a
1001 * profile_uid variable set in App, that is the "page owner" and normally their theme
1002 * settings take precedence; unless a local user sets the "always_my_theme"
1003 * system pconfig, which means they don't want to see anybody else's theme
1004 * settings except their own while on this site.
1006 * @return int user ID
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1011 public static function getThemeUid(App $a)
1013 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1014 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1015 return local_user();
1022 * search for Profiles
1026 * @param null $search
1028 * @return array [ 'total' => 123, 'entries' => [...] ];
1030 * @throws \Exception
1032 public static function searchProfiles($start = 0, $count = 100, $search = null)
1034 $publish = (DI::config()->get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1037 if (!empty($search)) {
1038 $searchTerm = '%' . $search . '%';
1039 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1041 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1042 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1043 AND ((`profile`.`name` LIKE ?) OR
1044 (`user`.`nickname` LIKE ?) OR
1045 (`profile`.`pdesc` LIKE ?) OR
1046 (`profile`.`locality` LIKE ?) OR
1047 (`profile`.`region` LIKE ?) OR
1048 (`profile`.`country-name` LIKE ?) OR
1049 (`profile`.`gender` LIKE ?) OR
1050 (`profile`.`marital` LIKE ?) OR
1051 (`profile`.`sexual` LIKE ?) OR
1052 (`profile`.`about` LIKE ?) OR
1053 (`profile`.`romance` LIKE ?) OR
1054 (`profile`.`work` LIKE ?) OR
1055 (`profile`.`education` LIKE ?) OR
1056 (`profile`.`pub_keywords` LIKE ?) OR
1057 (`profile`.`prv_keywords` LIKE ?))",
1058 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1059 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1061 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1063 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1064 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1067 if (DBA::isResult($cnt)) {
1068 $total = $cnt['total'];
1071 $order = " ORDER BY `name` ASC ";
1074 // If nothing found, don't try to select details
1076 if (!empty($search)) {
1077 $searchTerm = '%' . $search . '%';
1079 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1080 `contact`.`addr`, `contact`.`url` AS `profile_url`
1082 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1083 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1084 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1085 AND ((`profile`.`name` LIKE ?) OR
1086 (`user`.`nickname` LIKE ?) OR
1087 (`profile`.`pdesc` LIKE ?) OR
1088 (`profile`.`locality` LIKE ?) OR
1089 (`profile`.`region` LIKE ?) OR
1090 (`profile`.`country-name` LIKE ?) OR
1091 (`profile`.`gender` LIKE ?) OR
1092 (`profile`.`marital` LIKE ?) OR
1093 (`profile`.`sexual` LIKE ?) OR
1094 (`profile`.`about` LIKE ?) OR
1095 (`profile`.`romance` LIKE ?) OR
1096 (`profile`.`work` LIKE ?) OR
1097 (`profile`.`education` LIKE ?) OR
1098 (`profile`.`pub_keywords` LIKE ?) OR
1099 (`profile`.`prv_keywords` LIKE ?))
1101 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1102 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1106 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1107 `contact`.`addr`, `contact`.`url` AS `profile_url`
1109 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1110 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1111 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1118 if (DBA::isResult($profiles) && $total > 0) {
1121 'entries' => DBA::toArray($profiles),