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\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\Proxy as ProxyUtils;
25 use Friendica\Util\Temporal;
27 require_once 'include/dba.php';
32 * @brief Returns a formatted location string from the given profile array
34 * @param array $profile Profile array (Generated from the "profile" table)
36 * @return string Location string
38 public static function formatLocation(array $profile)
42 if (!empty($profile['locality'])) {
43 $location .= $profile['locality'];
46 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
51 $location .= $profile['region'];
54 if (!empty($profile['country-name'])) {
59 $location .= $profile['country-name'];
67 * Loads a profile into the page sidebar.
69 * The function requires a writeable copy of the main App structure, and the nickname
70 * of a registered local account.
72 * If the viewer is an authenticated remote viewer, the profile displayed is the
73 * one that has been configured for his/her viewing in the Contact manager.
74 * Passing a non-zero profile ID can also allow a preview of a selected profile
77 * Profile information is placed in the App structure for later retrieval.
78 * Honours the owner's chosen theme for display.
80 * @attention Should only be run in the _init() functions of a module. That ensures that
81 * the theme is chosen before the _init() function of a theme is run, which will usually
82 * load a lot of theme-specific content
84 * @brief Loads a profile into the page sidebar.
85 * @param object $a App
86 * @param string $nickname string
87 * @param int $profile int
88 * @param array $profiledata array
89 * @param boolean $show_connect Show connect link
91 public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
93 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
95 if (!DBA::isResult($user) && empty($profiledata)) {
96 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
97 notice(L10n::t('Requested account is not available.') . EOL);
102 if (count($profiledata) > 0) {
103 // Add profile data to sidebar
104 $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
106 if (!DBA::isResult($user)) {
111 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
113 if (empty($pdata) && empty($profiledata)) {
114 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
115 notice(L10n::t('Requested profile is not available.') . EOL);
121 $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
124 // fetch user tags if this isn't the default profile
126 if (!$pdata['is-default']) {
127 $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
128 $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
129 if (DBA::isResult($profile)) {
130 $pdata['pub_keywords'] = $profile['pub_keywords'];
134 $a->profile = $pdata;
135 $a->profile_uid = $pdata['profile_uid'];
137 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
138 $a->profile['network'] = Protocol::DFRN;
140 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
142 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
143 $_SESSION['theme'] = $a->profile['theme'];
146 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
149 * load/reload current theme info
152 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
154 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
155 if (file_exists($theme_info_file)) {
156 require_once $theme_info_file;
159 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
160 $a->page['aside'] .= replace_macros(
161 get_markup_template('profile_edlink.tpl'),
163 '$editprofile' => L10n::t('Edit profile'),
164 '$profid' => $a->profile['id']
169 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
173 * By now, the contact block isn't shown, when a different profile is given
174 * But: When this profile was on the same server, then we could display the contacts
177 $a->page['aside'] .= self::sidebar($a->profile, $block, $show_connect);
184 * Get all profile data of a local user
186 * If the viewer is an authenticated remote viewer, the profile displayed is the
187 * one that has been configured for his/her viewing in the Contact manager.
188 * Passing a non-zero profile ID can also allow a preview of a selected profile
191 * Includes all available profile data
193 * @brief Get all profile data of a local user
194 * @param string $nickname nick
195 * @param int $uid uid
196 * @param int $profile_id ID of the profile
199 public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
201 if (remote_user() && !empty($_SESSION['remote'])) {
202 foreach ($_SESSION['remote'] as $visitor) {
203 if ($visitor['uid'] == $uid) {
204 $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
205 if (DBA::isResult($contact)) {
206 $profile_id = $contact['profile-id'];
216 $profile = DBA::fetchFirst(
217 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
218 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
219 `profile`.`uid` AS `profile_uid`, `profile`.*,
220 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
222 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
223 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
224 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
229 if (!DBA::isResult($profile)) {
230 $profile = DBA::fetchFirst(
231 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
232 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
233 `profile`.`uid` AS `profile_uid`, `profile`.*,
234 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
236 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
237 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
238 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
247 * Formats a profile for display in the sidebar.
249 * It is very difficult to templatise the HTML completely
250 * because of all the conditional logic.
252 * @brief Formats a profile for display in the sidebar.
253 * @param array $profile
255 * @param boolean $show_connect Show connect link
257 * @return string HTML sidebar module
259 * @note Returns empty string if passed $profile is wrong type or not populated
261 * @hooks 'profile_sidebar_enter'
262 * array $profile - profile data
263 * @hooks 'profile_sidebar'
266 private static function sidebar($profile, $block = 0, $show_connect = true)
273 // This function can also use contact information in $profile
274 $is_contact = x($profile, 'cid');
276 if (!is_array($profile) && !count($profile)) {
280 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
282 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
283 $profile['network_name'] = format_network_name($profile['network'], $profile['url']);
285 $profile['network_name'] = '';
288 Addon::callHooks('profile_sidebar_enter', $profile);
291 // don't show connect link to yourself
292 $connect = $profile['uid'] != local_user() ? L10n::t('Connect') : false;
294 // don't show connect link to authenticated visitors either
295 if (remote_user() && !empty($_SESSION['remote'])) {
296 foreach ($_SESSION['remote'] as $visitor) {
297 if ($visitor['uid'] == $profile['uid']) {
304 if (!$show_connect) {
310 // Is the local user already connected to that user?
311 if ($connect && local_user()) {
312 if (isset($profile['url'])) {
313 $profile_url = normalise_link($profile['url']);
315 $profile_url = normalise_link(System::baseUrl() . '/profile/' . $profile['nickname']);
318 if (DBA::exists('contact', ['pending' => false, 'uid' => local_user(), 'nurl' => $profile_url])) {
323 if ($connect && ($profile['network'] != Protocol::DFRN) && !isset($profile['remoteconnect'])) {
327 $remoteconnect = null;
328 if (isset($profile['remoteconnect'])) {
329 $remoteconnect = $profile['remoteconnect'];
332 if ($connect && ($profile['network'] == Protocol::DFRN) && !isset($remoteconnect)) {
333 $subscribe_feed = L10n::t('Atom feed');
335 $subscribe_feed = false;
338 $wallmessage = false;
339 $wallmessage_link = false;
341 // See issue https://github.com/friendica/friendica/issues/3838
342 // Either we remove the message link for remote users or we enable creating messages from remote users
343 if (remote_user() || (self::getMyURL() && x($profile, 'unkmail') && ($profile['uid'] != local_user()))) {
344 $wallmessage = L10n::t('Message');
348 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
349 intval($profile['uid']),
350 intval(remote_user()),
351 intval(Contact::FRIEND)
355 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
356 intval($profile['uid']),
357 DBA::escape(normalise_link(self::getMyURL())),
358 intval(Contact::FRIEND)
362 $remote_url = $r[0]['url'];
363 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
364 $wallmessage_link = $message_path . base64_encode(defaults($profile, 'addr', ''));
365 } else if (!empty($profile['nickname'])) {
366 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
370 // show edit profile to yourself
371 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
372 $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
374 "SELECT * FROM `profile` WHERE `uid` = %d",
379 'chg_photo' => L10n::t('Change profile photo'),
380 'cr_new' => L10n::t('Create New Profile'),
384 if (DBA::isResult($r)) {
385 foreach ($r as $rr) {
386 $profile['menu']['entries'][] = [
387 'photo' => $rr['thumb'],
389 'alt' => L10n::t('Profile Image'),
390 'profile_name' => $rr['profile-name'],
391 'isdefault' => $rr['is-default'],
392 'visibile_to_everybody' => L10n::t('visible to everybody'),
393 'edit_visibility' => L10n::t('Edit visibility'),
398 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
399 $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
401 'chg_photo' => L10n::t('Change profile photo'),
407 // Fetch the account type
408 $account_type = Contact::getAccountType($profile);
410 if (x($profile, 'address')
411 || x($profile, 'location')
412 || x($profile, 'locality')
413 || x($profile, 'region')
414 || x($profile, 'postal-code')
415 || x($profile, 'country-name')
417 $location = L10n::t('Location:');
420 $gender = x($profile, 'gender') ? L10n::t('Gender:') : false;
421 $marital = x($profile, 'marital') ? L10n::t('Status:') : false;
422 $homepage = x($profile, 'homepage') ? L10n::t('Homepage:') : false;
423 $about = x($profile, 'about') ? L10n::t('About:') : false;
424 $xmpp = x($profile, 'xmpp') ? L10n::t('XMPP:') : false;
426 if ((x($profile, 'hidewall') || $block) && !local_user() && !remote_user()) {
427 $location = $gender = $marital = $homepage = $about = false;
430 $split_name = Diaspora::splitName($profile['name']);
431 $firstname = $split_name['first'];
432 $lastname = $split_name['last'];
434 if (x($profile, 'guid')) {
436 'guid' => $profile['guid'],
437 'podloc' => System::baseUrl(),
438 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
439 'nickname' => $profile['nickname'],
440 'fullname' => $profile['name'],
441 'firstname' => $firstname,
442 'lastname' => $lastname,
443 'photo300' => defaults($profile, 'contact_photo', ''),
444 'photo100' => defaults($profile, 'contact_thumb', ''),
445 'photo50' => defaults($profile, 'contact_micro', ''),
455 $contact_block = contact_block();
457 if (is_array($a->profile) && !$a->profile['hide-friends']) {
459 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
460 intval($a->profile['uid'])
462 if (DBA::isResult($r)) {
463 $updated = date('c', strtotime($r[0]['updated']));
467 "SELECT COUNT(*) AS `total` FROM `contact`
469 AND NOT `self` AND NOT `blocked` AND NOT `pending`
470 AND NOT `hidden` AND NOT `archive`
471 AND `network` IN ('%s', '%s', '%s', '')",
472 intval($profile['uid']),
473 DBA::escape(Protocol::DFRN),
474 DBA::escape(Protocol::DIASPORA),
475 DBA::escape(Protocol::OSTATUS)
477 if (DBA::isResult($r)) {
478 $contacts = intval($r[0]['total']);
484 foreach ($profile as $k => $v) {
485 $k = str_replace('-', '_', $k);
489 if (isset($p['about'])) {
490 $p['about'] = BBCode::convert($p['about']);
493 if (isset($p['address'])) {
494 $p['address'] = BBCode::convert($p['address']);
495 } elseif (isset($p['location'])) {
496 $p['address'] = BBCode::convert($p['location']);
499 if (isset($p['photo'])) {
500 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
503 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
505 $tpl = get_markup_template('profile_vcard.tpl');
506 $o .= replace_macros($tpl, [
509 '$connect' => $connect,
510 '$remoteconnect' => $remoteconnect,
511 '$subscribe_feed' => $subscribe_feed,
512 '$wallmessage' => $wallmessage,
513 '$wallmessage_link' => $wallmessage_link,
514 '$account_type' => $account_type,
515 '$location' => $location,
516 '$gender' => $gender,
517 '$marital' => $marital,
518 '$homepage' => $homepage,
520 '$network' => L10n::t('Network:'),
521 '$contacts' => $contacts,
522 '$updated' => $updated,
523 '$diaspora' => $diaspora,
524 '$contact_block' => $contact_block,
527 $arr = ['profile' => &$profile, 'entry' => &$o];
529 Addon::callHooks('profile_sidebar', $arr);
534 public static function getBirthdays()
539 if (!local_user() || $a->is_mobile || $a->is_tablet) {
544 * $mobile_detect = new Mobile_Detect();
545 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
550 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
551 $bd_short = L10n::t('F d');
553 $cachekey = 'get_birthdays:' . local_user();
554 $r = Cache::get($cachekey);
557 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
558 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
559 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
560 ORDER BY `start` ASC ",
562 DateTimeFormat::utc('now + 6 days'),
563 DateTimeFormat::utcNow()
565 if (DBA::isResult($s)) {
566 $r = DBA::toArray($s);
567 Cache::set($cachekey, $r, CACHE_HOUR);
573 if (DBA::isResult($r)) {
574 $now = strtotime('now');
578 foreach ($r as $rr) {
579 if (strlen($rr['name'])) {
582 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
586 $classtoday = $istoday ? ' birthday-today ' : '';
588 foreach ($r as &$rr) {
589 if (!strlen($rr['name'])) {
595 if (in_array($rr['cid'], $cids)) {
598 $cids[] = $rr['cid'];
600 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
602 $rr['link'] = Contact::magicLink($rr['url']);
603 $rr['title'] = $rr['name'];
604 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
605 $rr['startime'] = null;
606 $rr['today'] = $today;
610 $tpl = get_markup_template('birthdays_reminder.tpl');
611 return replace_macros($tpl, [
612 '$baseurl' => System::baseUrl(),
613 '$classtoday' => $classtoday,
615 '$event_reminders' => L10n::t('Birthday Reminders'),
616 '$event_title' => L10n::t('Birthdays this week:'),
618 '$lbr' => '{', // raw brackets mess up if/endif macro processing
623 public static function getEventsReminderHTML()
628 if (!local_user() || $a->is_mobile || $a->is_tablet) {
633 * $mobile_detect = new Mobile_Detect();
634 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
639 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
642 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
643 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
644 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
648 if (DBA::isResult($s)) {
652 while ($rr = DBA::fetch($s)) {
653 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
654 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
655 'visible' => true, 'deleted' => false];
656 if (!Item::exists($condition)) {
660 if (strlen($rr['summary'])) {
664 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
665 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
669 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
671 if (strlen($title) > 35) {
672 $title = substr($title, 0, 32) . '... ';
675 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
677 $description = L10n::t('[No description]');
680 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
682 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
686 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
688 $rr['title'] = $title;
689 $rr['description'] = $description;
690 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
691 $rr['startime'] = $strt;
692 $rr['today'] = $today;
697 $classtoday = (($istoday) ? 'event-today' : '');
699 $tpl = get_markup_template('events_reminder.tpl');
700 return replace_macros($tpl, [
701 '$baseurl' => System::baseUrl(),
702 '$classtoday' => $classtoday,
703 '$count' => count($r),
704 '$event_reminders' => L10n::t('Event Reminders'),
705 '$event_title' => L10n::t('Upcoming events the next 7 days:'),
710 public static function getAdvanced(App $a)
713 $uid = $a->profile['uid'];
715 $o .= replace_macros(
716 get_markup_template('section_title.tpl'),
717 ['$title' => L10n::t('Profile')]
720 if ($a->profile['name']) {
721 $tpl = get_markup_template('profile_advanced.tpl');
725 $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
727 if (Feature::isEnabled($uid, 'profile_membersince')) {
728 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
731 if ($a->profile['gender']) {
732 $profile['gender'] = [L10n::t('Gender:'), $a->profile['gender']];
735 if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
736 $year_bd_format = L10n::t('j F, Y');
737 $short_bd_format = L10n::t('j F');
739 $val = day_translate(
740 intval($a->profile['dob']) ?
741 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
742 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
745 $profile['birthday'] = [L10n::t('Birthday:'), $val];
748 if (!empty($a->profile['dob'])
749 && $a->profile['dob'] > '0001-01-01'
750 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
752 $profile['age'] = [L10n::t('Age:'), $age];
755 if ($a->profile['marital']) {
756 $profile['marital'] = [L10n::t('Status:'), $a->profile['marital']];
759 /// @TODO Maybe use x() here, plus below?
760 if ($a->profile['with']) {
761 $profile['marital']['with'] = $a->profile['with'];
764 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
765 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
768 if ($a->profile['sexual']) {
769 $profile['sexual'] = [L10n::t('Sexual Preference:'), $a->profile['sexual']];
772 if ($a->profile['homepage']) {
773 $profile['homepage'] = [L10n::t('Homepage:'), linkify($a->profile['homepage'])];
776 if ($a->profile['hometown']) {
777 $profile['hometown'] = [L10n::t('Hometown:'), linkify($a->profile['hometown'])];
780 if ($a->profile['pub_keywords']) {
781 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
784 if ($a->profile['politic']) {
785 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
788 if ($a->profile['religion']) {
789 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
792 if ($txt = prepare_text($a->profile['about'])) {
793 $profile['about'] = [L10n::t('About:'), $txt];
796 if ($txt = prepare_text($a->profile['interest'])) {
797 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
800 if ($txt = prepare_text($a->profile['likes'])) {
801 $profile['likes'] = [L10n::t('Likes:'), $txt];
804 if ($txt = prepare_text($a->profile['dislikes'])) {
805 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
808 if ($txt = prepare_text($a->profile['contact'])) {
809 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
812 if ($txt = prepare_text($a->profile['music'])) {
813 $profile['music'] = [L10n::t('Musical interests:'), $txt];
816 if ($txt = prepare_text($a->profile['book'])) {
817 $profile['book'] = [L10n::t('Books, literature:'), $txt];
820 if ($txt = prepare_text($a->profile['tv'])) {
821 $profile['tv'] = [L10n::t('Television:'), $txt];
824 if ($txt = prepare_text($a->profile['film'])) {
825 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
828 if ($txt = prepare_text($a->profile['romance'])) {
829 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
832 if ($txt = prepare_text($a->profile['work'])) {
833 $profile['work'] = [L10n::t('Work/employment:'), $txt];
836 if ($txt = prepare_text($a->profile['education'])) {
837 $profile['education'] = [L10n::t('School/education:'), $txt];
840 //show subcribed forum if it is enabled in the usersettings
841 if (Feature::isEnabled($uid, 'forumlist_profile')) {
842 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
845 if ($a->profile['uid'] == local_user()) {
846 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
849 return replace_macros($tpl, [
850 '$title' => L10n::t('Profile'),
851 '$basic' => L10n::t('Basic'),
852 '$advanced' => L10n::t('Advanced'),
853 '$profile' => $profile
860 public static function getTabs($a, $is_owner = false, $nickname = null)
862 if (is_null($nickname)) {
863 $nickname = $a->user['nickname'];
867 if (x($_GET, 'tab')) {
868 $tab = notags(trim($_GET['tab']));
871 $url = System::baseUrl() . '/profile/' . $nickname;
875 'label' => L10n::t('Status'),
877 'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
878 'title' => L10n::t('Status Messages and Posts'),
879 'id' => 'status-tab',
883 'label' => L10n::t('Profile'),
884 'url' => $url . '/?tab=profile',
885 'sel' => $tab == 'profile' ? 'active' : '',
886 'title' => L10n::t('Profile Details'),
887 'id' => 'profile-tab',
891 'label' => L10n::t('Photos'),
892 'url' => System::baseUrl() . '/photos/' . $nickname,
893 'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
894 'title' => L10n::t('Photo Albums'),
899 'label' => L10n::t('Videos'),
900 'url' => System::baseUrl() . '/videos/' . $nickname,
901 'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
902 'title' => L10n::t('Videos'),
908 // the calendar link for the full featured events calendar
909 if ($is_owner && $a->theme_events_in_profile) {
911 'label' => L10n::t('Events'),
912 'url' => System::baseUrl() . '/events',
913 'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
914 'title' => L10n::t('Events and Calendar'),
915 'id' => 'events-tab',
918 // if the user is not the owner of the calendar we only show a calendar
919 // with the public events of the calendar owner
920 } elseif (!$is_owner) {
922 'label' => L10n::t('Events'),
923 'url' => System::baseUrl() . '/cal/' . $nickname,
924 'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
925 'title' => L10n::t('Events and Calendar'),
926 'id' => 'events-tab',
933 'label' => L10n::t('Personal Notes'),
934 'url' => System::baseUrl() . '/notes',
935 'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
936 'title' => L10n::t('Only You Can See This'),
942 if (!empty($_SESSION['new_member']) && $is_owner) {
944 'label' => L10n::t('Tips for New Members'),
945 'url' => System::baseUrl() . '/newmember',
947 'title' => L10n::t('Tips for New Members'),
948 'id' => 'newmember-tab',
952 if (!$is_owner && empty($a->profile['hide-friends'])) {
954 'label' => L10n::t('Contacts'),
955 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
956 'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
957 'title' => L10n::t('Contacts'),
958 'id' => 'viewcontacts-tab',
963 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
964 Addon::callHooks('profile_tabs', $arr);
966 $tpl = get_markup_template('common_tabs.tpl');
968 return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
972 * Retrieves the my_url session variable
976 public static function getMyURL()
978 if (x($_SESSION, 'my_url')) {
979 return $_SESSION['my_url'];
985 * Process the 'zrl' parameter and initiate the remote authentication.
987 * This method checks if the visitor has a public contact entry and
988 * redirects the visitor to his/her instance to start the magic auth (Authentication)
991 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
993 * @param App $a Application instance.
995 public static function zrlInit(App $a)
997 $my_url = self::getMyURL();
998 $my_url = Network::isUrlValid($my_url);
1001 if (!local_user()) {
1002 // Is it a DDoS attempt?
1003 // The check fetches the cached value from gprobe to reduce the load for this system
1004 $urlparts = parse_url($my_url);
1006 $result = Cache::get('gprobe:' . $urlparts['host']);
1007 if ((!is_null($result)) && (in_array($result['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1008 logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
1012 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1013 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1014 Addon::callHooks('zrl_init', $arr);
1016 // Try to find the public contact entry of the visitor.
1017 $cid = Contact::getIdForURL($my_url);
1019 logger('No contact record found for ' . $my_url, LOGGER_DEBUG);
1023 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1025 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1026 // The visitor is already authenticated.
1030 logger('Not authenticated. Invoking reverse magic-auth for ' . $my_url, LOGGER_DEBUG);
1032 // Try to avoid recursion - but send them home to do a proper magic auth.
1033 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1034 // The other instance needs to know where to redirect.
1035 $dest = urlencode(System::baseUrl() . '/' . $query);
1037 // We need to extract the basebath from the profile url
1038 // to redirect the visitors '/magic' module.
1039 // Note: We should have the basepath of a contact also in the contact table.
1040 $urlarr = explode('/profile/', $contact['url']);
1041 $basepath = $urlarr[0];
1043 if ($basepath != System::baseUrl() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1044 $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1045 $serverret = Network::curl($magic_path);
1046 if (!empty($serverret['success'])) {
1047 goaway($magic_path);
1055 * OpenWebAuth authentication.
1057 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1059 * @param string $token
1061 public static function openWebAuthInit($token)
1065 // Clean old OpenWebAuthToken entries.
1066 OpenWebAuthToken::purge('owt', '3 MINUTE');
1068 // Check if the token we got is the same one
1069 // we have stored in the database.
1070 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1072 if($visitor_handle === false) {
1076 // Try to find the public contact entry of the visitor.
1077 $cid = Contact::getIdForURL($visitor_handle);
1079 logger('owt: unable to finger ' . $visitor_handle, LOGGER_DEBUG);
1083 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1085 // Authenticate the visitor.
1086 $_SESSION['authenticated'] = 1;
1087 $_SESSION['visitor_id'] = $visitor['id'];
1088 $_SESSION['visitor_handle'] = $visitor['addr'];
1089 $_SESSION['visitor_home'] = $visitor['url'];
1090 $_SESSION['my_url'] = $visitor['url'];
1093 'visitor' => $visitor,
1094 'url' => $a->query_string
1097 * @hooks magic_auth_success
1098 * Called when a magic-auth was successful.
1099 * * \e array \b visitor
1100 * * \e string \b url
1102 Addon::callHooks('magic_auth_success', $arr);
1104 $a->contact = $arr['visitor'];
1106 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->get_hostname(), $visitor['name']));
1108 logger('OpenWebAuth: auth success from ' . $visitor['addr'], LOGGER_DEBUG);
1111 public static function zrl($s, $force = false)
1116 if ((!strpos($s, '/profile/')) && (!$force)) {
1119 if ($force && substr($s, -1, 1) !== '/') {
1122 $achar = strpos($s, '?') ? '&' : '?';
1123 $mine = self::getMyURL();
1124 if ($mine && !link_compare($mine, $s)) {
1125 return $s . $achar . 'zrl=' . urlencode($mine);
1131 * Get the user ID of the page owner.
1133 * Used from within PCSS themes to set theme parameters. If there's a
1134 * puid request variable, that is the "page owner" and normally their theme
1135 * settings take precedence; unless a local user sets the "always_my_theme"
1136 * system pconfig, which means they don't want to see anybody else's theme
1137 * settings except their own while on this site.
1139 * @brief Get the user ID of the page owner
1140 * @return int user ID
1142 * @note Returns local_user instead of user ID if "always_my_theme"
1145 public static function getThemeUid()
1147 $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
1148 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1149 return local_user();
1156 * Stip zrl parameter from a string.
1158 * @param string $s The input string.
1159 * @return string The zrl.
1161 public static function stripZrls($s)
1163 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1167 * Stip query parameter from a string.
1169 * @param string $s The input string.
1170 * @return string The query parameter.
1172 public static function stripQueryParam($s, $param)
1174 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);