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\Core\Addon;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Temporal;
25 require_once 'include/dba.php';
26 require_once 'mod/proxy.php';
31 * @brief Returns a formatted location string from the given profile array
33 * @param array $profile Profile array (Generated from the "profile" table)
35 * @return string Location string
37 public static function formatLocation(array $profile)
41 if (!empty($profile['locality'])) {
42 $location .= $profile['locality'];
45 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
50 $location .= $profile['region'];
53 if (!empty($profile['country-name'])) {
58 $location .= $profile['country-name'];
66 * Loads a profile into the page sidebar.
68 * The function requires a writeable copy of the main App structure, and the nickname
69 * of a registered local account.
71 * If the viewer is an authenticated remote viewer, the profile displayed is the
72 * one that has been configured for his/her viewing in the Contact manager.
73 * Passing a non-zero profile ID can also allow a preview of a selected profile
76 * Profile information is placed in the App structure for later retrieval.
77 * Honours the owner's chosen theme for display.
79 * @attention Should only be run in the _init() functions of a module. That ensures that
80 * the theme is chosen before the _init() function of a theme is run, which will usually
81 * load a lot of theme-specific content
83 * @brief Loads a profile into the page sidebar.
84 * @param object $a App
85 * @param string $nickname string
86 * @param int $profile int
87 * @param array $profiledata array
88 * @param boolean $show_connect Show connect link
90 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
92 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
94 if (!DBA::isResult($user) && empty($profiledata)) {
95 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
96 notice(L10n::t('Requested account is not available.') . EOL);
101 if (count($profiledata) > 0) {
102 // Add profile data to sidebar
103 $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
105 if (!DBA::isResult($user)) {
110 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
112 if (empty($pdata) && empty($profiledata)) {
113 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
114 notice(L10n::t('Requested profile is not available.') . EOL);
119 // fetch user tags if this isn't the default profile
121 if (!$pdata['is-default']) {
123 "SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
124 intval($pdata['profile_uid'])
126 if ($x && count($x)) {
127 $pdata['pub_keywords'] = $x[0]['pub_keywords'];
131 $a->profile = $pdata;
132 $a->profile_uid = $pdata['profile_uid'];
134 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
135 $a->profile['network'] = NETWORK_DFRN;
137 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
139 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
140 $_SESSION['theme'] = $a->profile['theme'];
143 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
146 * load/reload current theme info
149 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
151 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
152 if (file_exists($theme_info_file)) {
153 require_once $theme_info_file;
156 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
157 $a->page['aside'] .= replace_macros(
158 get_markup_template('profile_edlink.tpl'),
160 '$editprofile' => L10n::t('Edit profile'),
161 '$profid' => $a->profile['id']
166 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
170 * By now, the contact block isn't shown, when a different profile is given
171 * But: When this profile was on the same server, then we could display the contacts
174 $a->page['aside'] .= self::sidebar($a->profile, $block, $show_connect);
181 * Get all profile data of a local user
183 * If the viewer is an authenticated remote viewer, the profile displayed is the
184 * one that has been configured for his/her viewing in the Contact manager.
185 * Passing a non-zero profile ID can also allow a preview of a selected profile
188 * Includes all available profile data
190 * @brief Get all profile data of a local user
191 * @param string $nickname nick
192 * @param int $uid uid
193 * @param int $profile_id ID of the profile
196 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
198 if (remote_user() && count($_SESSION['remote'])) {
199 foreach ($_SESSION['remote'] as $visitor) {
200 if ($visitor['uid'] == $uid) {
201 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
202 if (DBA::isResult($contact)) {
203 $profile_id = $contact['profile-id'];
213 $profile = DBA::fetchFirst(
214 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
215 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
216 `profile`.`uid` AS `profile_uid`, `profile`.*,
217 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
219 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
220 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
221 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
226 if (!DBA::isResult($profile)) {
227 $profile = DBA::fetchFirst(
228 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
229 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
230 `profile`.`uid` AS `profile_uid`, `profile`.*,
231 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
233 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
234 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
235 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
244 * Formats a profile for display in the sidebar.
246 * It is very difficult to templatise the HTML completely
247 * because of all the conditional logic.
249 * @brief Formats a profile for display in the sidebar.
250 * @param array $profile
252 * @param boolean $show_connect Show connect link
254 * @return string HTML sidebar module
256 * @note Returns empty string if passed $profile is wrong type or not populated
258 * @hooks 'profile_sidebar_enter'
259 * array $profile - profile data
260 * @hooks 'profile_sidebar'
263 private static function sidebar($profile, $block = 0, $show_connect = true)
270 // This function can also use contact information in $profile
271 $is_contact = x($profile, 'cid');
273 if (!is_array($profile) && !count($profile)) {
277 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
279 if (($profile['network'] != '') && ($profile['network'] != NETWORK_DFRN)) {
280 $profile['network_name'] = format_network_name($profile['network'], $profile['url']);
282 $profile['network_name'] = '';
285 Addon::callHooks('profile_sidebar_enter', $profile);
288 // don't show connect link to yourself
289 $connect = $profile['uid'] != local_user() ? L10n::t('Connect') : false;
291 // don't show connect link to authenticated visitors either
292 if (remote_user() && count($_SESSION['remote'])) {
293 foreach ($_SESSION['remote'] as $visitor) {
294 if ($visitor['uid'] == $profile['uid']) {
301 if (!$show_connect) {
307 // Is the local user already connected to that user?
308 if ($connect && local_user()) {
309 if (isset($profile['url'])) {
310 $profile_url = normalise_link($profile['url']);
312 $profile_url = normalise_link(System::baseUrl() . '/profile/' . $profile['nickname']);
315 if (DBA::exists('contact', ['pending' => false, 'uid' => local_user(), 'nurl' => $profile_url])) {
320 if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect'])) {
324 $remoteconnect = null;
325 if (isset($profile['remoteconnect'])) {
326 $remoteconnect = $profile['remoteconnect'];
329 if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect)) {
330 $subscribe_feed = L10n::t('Atom feed');
332 $subscribe_feed = false;
335 if (remote_user() || (self::getMyURL() && x($profile, 'unkmail') && ($profile['uid'] != local_user()))) {
336 $wallmessage = L10n::t('Message');
337 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
341 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
342 intval($profile['uid']),
343 intval(remote_user()),
344 intval(Contact::FRIEND)
348 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
349 intval($profile['uid']),
350 DBA::escape(normalise_link(self::getMyURL())),
351 intval(Contact::FRIEND)
355 $remote_url = $r[0]['url'];
356 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
357 $wallmessage_link = $message_path . base64_encode($profile['addr']);
360 $wallmessage = false;
361 $wallmessage_link = false;
364 // show edit profile to yourself
365 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
366 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
368 "SELECT * FROM `profile` WHERE `uid` = %d",
373 'chg_photo' => L10n::t('Change profile photo'),
374 'cr_new' => L10n::t('Create New Profile'),
378 if (DBA::isResult($r)) {
379 foreach ($r as $rr) {
380 $profile['menu']['entries'][] = [
381 'photo' => $rr['thumb'],
383 'alt' => L10n::t('Profile Image'),
384 'profile_name' => $rr['profile-name'],
385 'isdefault' => $rr['is-default'],
386 'visibile_to_everybody' => L10n::t('visible to everybody'),
387 'edit_visibility' => L10n::t('Edit visibility'),
392 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
393 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
395 'chg_photo' => L10n::t('Change profile photo'),
401 // Fetch the account type
402 $account_type = Contact::getAccountType($profile);
404 if (x($profile, 'address')
405 || x($profile, 'location')
406 || x($profile, 'locality')
407 || x($profile, 'region')
408 || x($profile, 'postal-code')
409 || x($profile, 'country-name')
411 $location = L10n::t('Location:');
414 $gender = x($profile, 'gender') ? L10n::t('Gender:') : false;
415 $marital = x($profile, 'marital') ? L10n::t('Status:') : false;
416 $homepage = x($profile, 'homepage') ? L10n::t('Homepage:') : false;
417 $about = x($profile, 'about') ? L10n::t('About:') : false;
418 $xmpp = x($profile, 'xmpp') ? L10n::t('XMPP:') : false;
420 if ((x($profile, 'hidewall') || $block) && !local_user() && !remote_user()) {
421 $location = $gender = $marital = $homepage = $about = false;
424 $split_name = Diaspora::splitName($profile['name']);
425 $firstname = $split_name['first'];
426 $lastname = $split_name['last'];
428 if (x($profile, 'guid')) {
430 'guid' => $profile['guid'],
431 'podloc' => System::baseUrl(),
432 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
433 'nickname' => $profile['nickname'],
434 'fullname' => $profile['name'],
435 'firstname' => $firstname,
436 'lastname' => $lastname,
437 'photo300' => defaults($profile, 'contact_photo', ''),
438 'photo100' => defaults($profile, 'contact_thumb', ''),
439 'photo50' => defaults($profile, 'contact_micro', ''),
449 $contact_block = contact_block();
451 if (is_array($a->profile) && !$a->profile['hide-friends']) {
453 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
454 intval($a->profile['uid'])
456 if (DBA::isResult($r)) {
457 $updated = date('c', strtotime($r[0]['updated']));
461 "SELECT COUNT(*) AS `total` FROM `contact`
463 AND NOT `self` AND NOT `blocked` AND NOT `pending`
464 AND NOT `hidden` AND NOT `archive`
465 AND `network` IN ('%s', '%s', '%s', '')",
466 intval($profile['uid']),
467 DBA::escape(NETWORK_DFRN),
468 DBA::escape(NETWORK_DIASPORA),
469 DBA::escape(NETWORK_OSTATUS)
471 if (DBA::isResult($r)) {
472 $contacts = intval($r[0]['total']);
478 foreach ($profile as $k => $v) {
479 $k = str_replace('-', '_', $k);
483 if (isset($p['about'])) {
484 $p['about'] = BBCode::convert($p['about']);
487 if (isset($p['address'])) {
488 $p['address'] = BBCode::convert($p['address']);
490 $p['address'] = BBCode::convert($p['location']);
493 if (isset($p['photo'])) {
494 $p['photo'] = proxy_url($p['photo'], false, PROXY_SIZE_SMALL);
497 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
499 $tpl = get_markup_template('profile_vcard.tpl');
500 $o .= replace_macros($tpl, [
503 '$connect' => $connect,
504 '$remoteconnect' => $remoteconnect,
505 '$subscribe_feed' => $subscribe_feed,
506 '$wallmessage' => $wallmessage,
507 '$wallmessage_link' => $wallmessage_link,
508 '$account_type' => $account_type,
509 '$location' => $location,
510 '$gender' => $gender,
511 '$marital' => $marital,
512 '$homepage' => $homepage,
514 '$network' => L10n::t('Network:'),
515 '$contacts' => $contacts,
516 '$updated' => $updated,
517 '$diaspora' => $diaspora,
518 '$contact_block' => $contact_block,
521 $arr = ['profile' => &$profile, 'entry' => &$o];
523 Addon::callHooks('profile_sidebar', $arr);
528 public static function getBirthdays()
533 if (!local_user() || $a->is_mobile || $a->is_tablet) {
538 * $mobile_detect = new Mobile_Detect();
539 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
544 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
545 $bd_short = L10n::t('F d');
547 $cachekey = 'get_birthdays:' . local_user();
548 $r = Cache::get($cachekey);
551 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
552 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
553 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
554 ORDER BY `start` ASC ",
556 DateTimeFormat::utc('now + 6 days'),
557 DateTimeFormat::utcNow()
559 if (DBA::isResult($s)) {
560 $r = DBA::toArray($s);
561 Cache::set($cachekey, $r, CACHE_HOUR);
567 if (DBA::isResult($r)) {
568 $now = strtotime('now');
572 foreach ($r as $rr) {
573 if (strlen($rr['name'])) {
576 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
580 $classtoday = $istoday ? ' birthday-today ' : '';
582 foreach ($r as &$rr) {
583 if (!strlen($rr['name'])) {
589 if (in_array($rr['cid'], $cids)) {
592 $cids[] = $rr['cid'];
594 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
596 $rr['link'] = Contact::magicLink($rr['url']);
597 $rr['title'] = $rr['name'];
598 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
599 $rr['startime'] = null;
600 $rr['today'] = $today;
604 $tpl = get_markup_template('birthdays_reminder.tpl');
605 return replace_macros($tpl, [
606 '$baseurl' => System::baseUrl(),
607 '$classtoday' => $classtoday,
609 '$event_reminders' => L10n::t('Birthday Reminders'),
610 '$event_title' => L10n::t('Birthdays this week:'),
612 '$lbr' => '{', // raw brackets mess up if/endif macro processing
617 public static function getEventsReminderHTML()
622 if (!local_user() || $a->is_mobile || $a->is_tablet) {
627 * $mobile_detect = new Mobile_Detect();
628 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
633 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
640 ON `item`.`uid` = `event`.`uid`
641 AND `item`.`parent-uri` = `event`.`uri`
642 WHERE `event`.`uid` = ?
643 AND `event`.`type` != 'birthday'
644 AND `event`.`start` < ?
645 AND `event`.`start` >= ?
646 AND `item`.`author-id` = ?
647 AND (`item`.`verb` = ? OR `item`.`verb` = ?)
649 AND NOT `item`.`deleted`
650 ORDER BY `event`.`start` ASC",
652 DateTimeFormat::utc('now + 7 days'),
653 DateTimeFormat::utc('now - 1 days'),
661 if (DBA::isResult($s)) {
664 while ($rr = DBA::fetch($s)) {
665 if (strlen($rr['name'])) {
669 $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
670 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
674 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
676 if (strlen($title) > 35) {
677 $title = substr($title, 0, 32) . '... ';
680 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
682 $description = L10n::t('[No description]');
685 $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC');
687 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
691 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
693 $rr['title'] = $title;
694 $rr['description'] = $description;
695 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
696 $rr['startime'] = $strt;
697 $rr['today'] = $today;
702 $classtoday = (($istoday) ? 'event-today' : '');
704 $tpl = get_markup_template('events_reminder.tpl');
705 return replace_macros($tpl, [
706 '$baseurl' => System::baseUrl(),
707 '$classtoday' => $classtoday,
708 '$count' => count($r),
709 '$event_reminders' => L10n::t('Event Reminders'),
710 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
715 public static function getAdvanced(App $a)
718 $uid = $a->profile['uid'];
720 $o .= replace_macros(
721 get_markup_template('section_title.tpl'),
722 ['$title' => L10n::t('Profile')]
725 if ($a->profile['name']) {
726 $tpl = get_markup_template('profile_advanced.tpl');
730 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
732 if (Feature::isEnabled($uid, 'profile_membersince')) {
733 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
736 if ($a->profile['gender']) {
737 $profile['gender'] = [L10n::t('Gender:'), $a->profile['gender']];
740 if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
741 $year_bd_format = L10n::t('j F, Y');
742 $short_bd_format = L10n::t('j F');
744 $val = day_translate(
745 intval($a->profile['dob']) ?
746 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
747 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
750 $profile['birthday'] = [L10n::t('Birthday:'), $val];
753 if (!empty($a->profile['dob'])
754 && $a->profile['dob'] > '0001-01-01'
755 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
757 $profile['age'] = [L10n::t('Age:'), $age];
760 if ($a->profile['marital']) {
761 $profile['marital'] = [L10n::t('Status:'), $a->profile['marital']];
764 /// @TODO Maybe use x() here, plus below?
765 if ($a->profile['with']) {
766 $profile['marital']['with'] = $a->profile['with'];
769 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
770 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
773 if ($a->profile['sexual']) {
774 $profile['sexual'] = [L10n::t('Sexual Preference:'), $a->profile['sexual']];
777 if ($a->profile['homepage']) {
778 $profile['homepage'] = [L10n::t('Homepage:'), linkify($a->profile['homepage'])];
781 if ($a->profile['hometown']) {
782 $profile['hometown'] = [L10n::t('Hometown:'), linkify($a->profile['hometown'])];
785 if ($a->profile['pub_keywords']) {
786 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
789 if ($a->profile['politic']) {
790 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
793 if ($a->profile['religion']) {
794 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
797 if ($txt = prepare_text($a->profile['about'])) {
798 $profile['about'] = [L10n::t('About:'), $txt];
801 if ($txt = prepare_text($a->profile['interest'])) {
802 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
805 if ($txt = prepare_text($a->profile['likes'])) {
806 $profile['likes'] = [L10n::t('Likes:'), $txt];
809 if ($txt = prepare_text($a->profile['dislikes'])) {
810 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
813 if ($txt = prepare_text($a->profile['contact'])) {
814 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
817 if ($txt = prepare_text($a->profile['music'])) {
818 $profile['music'] = [L10n::t('Musical interests:'), $txt];
821 if ($txt = prepare_text($a->profile['book'])) {
822 $profile['book'] = [L10n::t('Books, literature:'), $txt];
825 if ($txt = prepare_text($a->profile['tv'])) {
826 $profile['tv'] = [L10n::t('Television:'), $txt];
829 if ($txt = prepare_text($a->profile['film'])) {
830 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
833 if ($txt = prepare_text($a->profile['romance'])) {
834 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
837 if ($txt = prepare_text($a->profile['work'])) {
838 $profile['work'] = [L10n::t('Work/employment:'), $txt];
841 if ($txt = prepare_text($a->profile['education'])) {
842 $profile['education'] = [L10n::t('School/education:'), $txt];
845 //show subcribed forum if it is enabled in the usersettings
846 if (Feature::isEnabled($uid, 'forumlist_profile')) {
847 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
850 if ($a->profile['uid'] == local_user()) {
851 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
854 return replace_macros($tpl, [
855 '$title' => L10n::t('Profile'),
856 '$basic' => L10n::t('Basic'),
857 '$advanced' => L10n::t('Advanced'),
858 '$profile' => $profile
865 public static function getTabs($a, $is_owner = false, $nickname = null)
867 if (is_null($nickname)) {
868 $nickname = $a->user['nickname'];
872 if (x($_GET, 'tab')) {
873 $tab = notags(trim($_GET['tab']));
876 $url = System::baseUrl() . '/profile/' . $nickname;
880 'label' => L10n::t('Status'),
882 'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
883 'title' => L10n::t('Status Messages and Posts'),
884 'id' => 'status-tab',
888 'label' => L10n::t('Profile'),
889 'url' => $url . '/?tab=profile',
890 'sel' => $tab == 'profile' ? 'active' : '',
891 'title' => L10n::t('Profile Details'),
892 'id' => 'profile-tab',
896 'label' => L10n::t('Photos'),
897 'url' => System::baseUrl() . '/photos/' . $nickname,
898 'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
899 'title' => L10n::t('Photo Albums'),
904 'label' => L10n::t('Videos'),
905 'url' => System::baseUrl() . '/videos/' . $nickname,
906 'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
907 'title' => L10n::t('Videos'),
913 // the calendar link for the full featured events calendar
914 if ($is_owner && $a->theme_events_in_profile) {
916 'label' => L10n::t('Events'),
917 'url' => System::baseUrl() . '/events',
918 'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
919 'title' => L10n::t('Events and Calendar'),
920 'id' => 'events-tab',
923 // if the user is not the owner of the calendar we only show a calendar
924 // with the public events of the calendar owner
925 } elseif (!$is_owner) {
927 'label' => L10n::t('Events'),
928 'url' => System::baseUrl() . '/cal/' . $nickname,
929 'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
930 'title' => L10n::t('Events and Calendar'),
931 'id' => 'events-tab',
938 'label' => L10n::t('Personal Notes'),
939 'url' => System::baseUrl() . '/notes',
940 'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
941 'title' => L10n::t('Only You Can See This'),
947 if (!empty($_SESSION['new_member']) && $is_owner) {
949 'label' => L10n::t('Tips for New Members'),
950 'url' => System::baseUrl() . '/newmember',
952 'title' => L10n::t('Tips for New Members'),
953 'id' => 'newmember-tab',
957 if (!$is_owner && empty($a->profile['hide-friends'])) {
959 'label' => L10n::t('Contacts'),
960 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
961 'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
962 'title' => L10n::t('Contacts'),
963 'id' => 'viewcontacts-tab',
968 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
969 Addon::callHooks('profile_tabs', $arr);
971 $tpl = get_markup_template('common_tabs.tpl');
973 return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
977 * Retrieves the my_url session variable
981 public static function getMyURL()
983 if (x($_SESSION, 'my_url')) {
984 return $_SESSION['my_url'];
990 * Process the 'zrl' parameter and initiate the remote authentication.
992 * This method checks if the visitor has a public contact entry and
993 * redirects the visitor to his/her instance to start the magic auth (Authentication)
996 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
998 * @param App $a Application instance.
1000 public static function zrlInit(App $a)
1002 $my_url = self::getMyURL();
1003 $my_url = Network::isUrlValid($my_url);
1006 if (!local_user()) {
1007 // Is it a DDoS attempt?
1008 // The check fetches the cached value from gprobe to reduce the load for this system
1009 $urlparts = parse_url($my_url);
1011 $result = Cache::get('gprobe:' . $urlparts['host']);
1012 if ((!is_null($result)) && (in_array($result['network'], [NETWORK_FEED, NETWORK_PHANTOM]))) {
1013 logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
1017 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1018 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1019 Addon::callHooks('zrl_init', $arr);
1021 // Try to find the public contact entry of the visitor.
1022 $cid = Contact::getIdForURL($my_url);
1024 logger('No contact record found for ' . $my_url, LOGGER_DEBUG);
1028 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1030 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1031 // The visitor is already authenticated.
1035 logger('Not authenticated. Invoking reverse magic-auth for ' . $my_url, LOGGER_DEBUG);
1037 // Try to avoid recursion - but send them home to do a proper magic auth.
1038 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1039 // The other instance needs to know where to redirect.
1040 $dest = urlencode(System::baseUrl() . '/' . $query);
1042 // We need to extract the basebath from the profile url
1043 // to redirect the visitors '/magic' module.
1044 // Note: We should have the basepath of a contact also in the contact table.
1045 $urlarr = explode('/profile/', $contact['url']);
1046 $basepath = $urlarr[0];
1048 if ($basepath != System::baseUrl() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1049 goaway($basepath . '/magic' . '?f=&owa=1&dest=' . $dest);
1056 * OpenWebAuth authentication.
1058 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1060 * @param string $token
1062 public static function openWebAuthInit($token)
1066 // Clean old OpenWebAuthToken entries.
1067 OpenWebAuthToken::purge('owt', '3 MINUTE');
1069 // Check if the token we got is the same one
1070 // we have stored in the database.
1071 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1073 if($visitor_handle === false) {
1077 // Try to find the public contact entry of the visitor.
1078 $cid = Contact::getIdForURL($visitor_handle);
1080 logger('owt: unable to finger ' . $visitor_handle, LOGGER_DEBUG);
1084 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1086 // Authenticate the visitor.
1087 $_SESSION['authenticated'] = 1;
1088 $_SESSION['visitor_id'] = $visitor['id'];
1089 $_SESSION['visitor_handle'] = $visitor['addr'];
1090 $_SESSION['visitor_home'] = $visitor['url'];
1091 $_SESSION['my_url'] = $visitor['url'];
1094 'visitor' => $visitor,
1095 'url' => $a->query_string
1098 * @hooks magic_auth_success
1099 * Called when a magic-auth was successful.
1100 * * \e array \b visitor
1101 * * \e string \b url
1103 Addon::callHooks('magic_auth_success', $arr);
1105 $a->contact = $arr['visitor'];
1107 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->get_hostname(), $visitor['name']));
1109 logger('OpenWebAuth: auth success from ' . $visitor['addr'], LOGGER_DEBUG);
1112 public static function zrl($s, $force = false)
1117 if ((!strpos($s, '/profile/')) && (!$force)) {
1120 if ($force && substr($s, -1, 1) !== '/') {
1123 $achar = strpos($s, '?') ? '&' : '?';
1124 $mine = self::getMyURL();
1125 if ($mine && !link_compare($mine, $s)) {
1126 return $s . $achar . 'zrl=' . urlencode($mine);
1132 * Get the user ID of the page owner.
1134 * Used from within PCSS themes to set theme parameters. If there's a
1135 * puid request variable, that is the "page owner" and normally their theme
1136 * settings take precedence; unless a local user sets the "always_my_theme"
1137 * system pconfig, which means they don't want to see anybody else's theme
1138 * settings except their own while on this site.
1140 * @brief Get the user ID of the page owner
1141 * @return int user ID
1143 * @note Returns local_user instead of user ID if "always_my_theme"
1146 public static function getThemeUid()
1148 $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
1149 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1150 return local_user();
1157 * Stip zrl parameter from a string.
1159 * @param string $s The input string.
1160 * @return string The zrl.
1162 public static function stripZrls($s)
1164 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1168 * Stip query parameter from a string.
1170 * @param string $s The input string.
1171 * @return string The query parameter.
1173 public static function stripQueryParam($s, $param)
1175 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);