3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
25 use Friendica\App\Mode;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Widget\ContactBlock;
28 use Friendica\Core\Cache\Enum\Duration;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\Search;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Network\HTTPException\InternalServerErrorException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Security\PermissionSet\Entity\PermissionSet;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
54 * Returns default profile for a given user id
56 * @param integer User ID
58 * @return array|bool Profile data or false on error
61 public static function getByUID(int $uid)
63 return DBA::selectFirst('profile', [], ['uid' => $uid]);
67 * Returns default profile for a given user ID and ID
69 * @param int $uid The contact ID
70 * @param int $id The contact owner ID
71 * @param array $fields The selected fields
73 * @return array|bool Profile data for the ID or false on error
76 public static function getById(int $uid, int $id, array $fields = [])
78 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
82 * Returns profile data for the contact owner
84 * @param int $uid The User ID
85 * @param array|bool $fields The fields to retrieve or false on error
87 * @return array Array of profile data
90 public static function getListByUser(int $uid, array $fields = [])
92 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
96 * Update a profile entry and distribute the changes if needed
98 * @param array $fields Profile fields to update
99 * @param integer $uid User id
101 * @return boolean Whether update was successful
104 public static function update(array $fields, int $uid): bool
106 $old_owner = User::getOwnerDataById($uid);
107 if (empty($old_owner)) {
111 if (!DBA::update('profile', $fields, ['uid' => $uid])) {
115 $update = Contact::updateSelfFromUserID($uid);
117 $owner = User::getOwnerDataById($uid);
122 $profile_fields = ['postal-code', 'dob', 'prv_keywords', 'homepage'];
123 foreach ($profile_fields as $field) {
124 if ($old_owner[$field] != $owner[$field]) {
130 self::publishUpdate($uid, ($old_owner['net-publish'] != $owner['net-publish']));
137 * Publish a changed profile
139 * @param int $uid User id
140 * @param bool $force Force publishing to the directory
144 public static function publishUpdate(int $uid, bool $force = false)
146 $owner = User::getOwnerDataById($uid);
151 if ($owner['net-publish'] || $force) {
152 // Update global directory in background
153 if (Search::getGlobalDirectory()) {
154 Worker::add(Worker::PRIORITY_LOW, 'Directory', $owner['url']);
158 Worker::add(Worker::PRIORITY_LOW, 'ProfileUpdate', $uid);
162 * Returns a formatted location string from the given profile array
164 * @param array $profile Profile array (Generated from the "profile" table)
166 * @return string Location string
168 public static function formatLocation(array $profile): string
172 if (!empty($profile['locality'])) {
173 $location .= $profile['locality'];
176 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
181 $location .= $profile['region'];
184 if (!empty($profile['country-name'])) {
189 $location .= $profile['country-name'];
196 * Loads a profile into the page sidebar.
198 * The function requires a writeable copy of the main App structure, and the nickname
199 * of a registered local account.
201 * If the viewer is an authenticated remote viewer, the profile displayed is the
202 * one that has been configured for his/her viewing in the Contact manager.
203 * Passing a non-zero profile ID can also allow a preview of a selected profile
206 * Profile information is placed in the App structure for later retrieval.
207 * Honours the owner's chosen theme for display.
209 * @attention Should only be run in the _init() functions of a module. That ensures that
210 * the theme is chosen before the _init() function of a theme is run, which will usually
211 * load a lot of theme-specific content
214 * @param string $nickname string
215 * @param bool $show_contacts
217 * @return array Profile
218 * @throws HTTPException\NotFoundException
219 * @throws HTTPException\InternalServerErrorException
220 * @throws \ImagickException
222 public static function load(App $a, string $nickname, bool $show_contacts = true): array
224 $profile = User::getOwnerDataByNick($nickname);
225 if (!isset($profile['account_removed']) || $profile['account_removed']) {
226 Logger::info('profile error: ' . DI::args()->getQueryString());
230 // System user, aborting
231 if ($profile['uid'] === 0) {
232 DI::logger()->warning('System user found in Profile::load', ['nickname' => $nickname]);
233 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
236 $a->setProfileOwner($profile['uid']);
238 DI::page()['title'] = $profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
240 if (!DI::userSession()->getLocalUserId()) {
241 $a->setCurrentTheme($profile['theme']);
242 $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme') ?? '');
246 * load/reload current theme info
249 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
251 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
252 if (file_exists($theme_info_file)) {
253 require_once $theme_info_file;
256 $block = (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated());
260 * By now, the contact block isn't shown, when a different profile is given
261 * But: When this profile was on the same server, then we could display the contacts
263 DI::page()['aside'] .= self::getVCardHtml($profile, $block, $show_contacts);
269 * Formats a profile for display in the sidebar.
271 * It is very difficult to templatise the HTML completely
272 * because of all the conditional logic.
274 * @param array $profile Profile array
275 * @param bool $block Block personal details
276 * @param bool $show_contacts Show contact block
278 * @return string HTML sidebar module
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 * @throws \ImagickException
282 * @note Returns empty string if passed $profile is wrong type or not populated
284 * @hooks 'profile_sidebar_enter'
285 * array $profile - profile data
286 * @hooks 'profile_sidebar'
289 public static function getVCardHtml(array $profile, bool $block, bool $show_contacts): string
294 $profile_contact = [];
296 if (DI::userSession()->getLocalUserId() && ($profile['uid'] ?? 0) != DI::userSession()->getLocalUserId()) {
297 $profile_contact = Contact::getByURL($profile['nurl'], null, [], DI::userSession()->getLocalUserId());
299 if (!empty($profile['cid']) && self::getMyURL()) {
300 $profile_contact = Contact::selectFirst([], ['id' => $profile['cid']]);
303 $profile['picdate'] = urlencode($profile['picdate']);
305 $profile['network_link'] = '';
307 Hook::callAll('profile_sidebar_enter', $profile);
309 $profile_url = $profile['url'];
311 $contact = Contact::selectFirst(['id'], ['uri-id' => $profile['uri-id'], 'uid' => 0]);
316 $cid = $contact['id'];
319 $unfollow_link = null;
320 $wallmessage_link = null;
322 // Who is the logged-in user to this profile?
323 $visitor_contact = [];
324 if (!empty($profile['uid']) && self::getMyURL()) {
325 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
328 $local_user_is_self = self::getMyURL() && ($profile['url'] == self::getMyURL());
329 $visitor_is_authenticated = (bool)self::getMyURL();
330 $visitor_is_following =
331 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
332 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
333 $visitor_is_followed =
334 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
335 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
336 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
338 if (!$local_user_is_self) {
339 if (!$visitor_is_authenticated) {
340 // Remote follow is only available for local profiles
341 if (!empty($profile['nickname']) && strpos($profile_url, (string)DI::baseUrl()) === 0) {
342 $follow_link = 'profile/' . $profile['nickname'] . '/remote_follow';
345 if ($visitor_is_following) {
346 $unfollow_link = $visitor_base_path . '/contact/unfollow?url=' . urlencode($profile_url) . '&auto=1';
348 $follow_link = $visitor_base_path . '/contact/follow?url=' . urlencode($profile_url) . '&auto=1';
352 if (Contact::canReceivePrivateMessages($profile_contact)) {
353 if ($visitor_is_followed || $visitor_is_following) {
354 $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
355 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
356 $wallmessage_link = 'profile/' . $profile['nickname'] . '/unkmail';
361 // show edit profile to yourself, but only if this is not meant to be
362 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
364 if (!isset($profile['self']) && $local_user_is_self) {
365 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
367 'chg_photo' => DI::l10n()->t('Change profile photo'),
373 // Fetch the account type
374 $account_type = Contact::getAccountType($profile['account-type']);
376 if (!empty($profile['address']) || !empty($profile['location'])) {
377 $location = DI::l10n()->t('Location:');
380 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
381 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
382 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
383 $matrix = !empty($profile['matrix']) ? DI::l10n()->t('Matrix:') : false;
385 if ((!empty($profile['hidewall']) || $block) && !DI::userSession()->isAuthenticated()) {
386 $location = $homepage = $about = false;
389 $split_name = Diaspora::splitName($profile['name']);
390 $firstname = $split_name['first'];
391 $lastname = $split_name['last'];
393 if (!empty($profile['guid'])) {
395 'guid' => $profile['guid'],
396 'podloc' => DI::baseUrl(),
397 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
398 'nickname' => $profile['nickname'],
399 'fullname' => $profile['name'],
400 'firstname' => $firstname,
401 'lastname' => $lastname,
402 'photo300' => $profile['photo'] ?? '',
403 'photo100' => $profile['thumb'] ?? '',
404 'photo50' => $profile['micro'] ?? '',
414 if (!empty($profile['last-item'])) {
415 $updated = date('c', strtotime($profile['last-item']));
418 if (!$block && $show_contacts) {
419 $contact_block = ContactBlock::getHTML($profile, DI::userSession()->getLocalUserId());
421 if (is_array($profile) && !$profile['hide-friends']) {
422 $contact_count = DBA::count('contact', [
423 'uid' => $profile['uid'],
430 'network' => Protocol::FEDERATED,
435 // Expected profile/vcard.tpl profile.* template variables
441 foreach ($profile as $k => $v) {
442 $k = str_replace('-', '_', $k);
446 if (isset($p['about'])) {
447 $p['about'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['about']);
450 if (isset($p['address'])) {
451 $p['address'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['address']);
454 $p['photo'] = Contact::getAvatarUrlForId($cid, Proxy::SIZE_SMALL);
456 $p['url'] = Contact::magicLinkById($cid, $profile['url']);
458 if (!isset($profile['hidewall'])) {
459 Logger::warning('Missing hidewall key in profile array', ['profile' => $profile]);
462 if ($profile['account-type'] == Contact::TYPE_COMMUNITY) {
463 $mention_label = DI::l10n()->t('Post to group');
464 $mention_url = 'compose/0?body=!' . $profile['addr'];
465 $network_label = DI::l10n()->t('View group');
466 $network_url = 'network/group/' . $cid;
468 $mention_label = DI::l10n()->t('Mention');
469 $mention_url = 'compose/0?body=@' . $profile['addr'];
470 $network_label = DI::l10n()->t('Network Posts');
471 $network_url = 'contact/' . $cid . '/conversations';
474 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
475 $o .= Renderer::replaceMacros($tpl, [
478 '$matrix' => $matrix,
479 '$follow' => DI::l10n()->t('Follow'),
480 '$follow_link' => $follow_link,
481 '$unfollow' => DI::l10n()->t('Unfollow'),
482 '$unfollow_link' => $unfollow_link,
483 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
484 '$subscribe_feed_link' => $profile['hidewall'] ?? 0 ? '' : $profile['poll'],
485 '$wallmessage' => DI::l10n()->t('Message'),
486 '$wallmessage_link' => $wallmessage_link,
487 '$account_type' => $account_type,
488 '$location' => $location,
489 '$homepage' => $homepage,
490 '$homepage_verified' => DI::l10n()->t('This website has been verified to belong to the same person.'),
492 '$network' => DI::l10n()->t('Network:'),
493 '$contacts' => $contact_count,
494 '$updated' => $updated,
495 '$diaspora' => $diaspora,
496 '$contact_block' => $contact_block,
497 '$mention_label' => $mention_label,
498 '$mention_url' => $mention_url,
499 '$network_label' => $network_label,
500 '$network_url' => $network_url,
503 $arr = ['profile' => &$profile, 'entry' => &$o];
505 Hook::callAll('profile_sidebar', $arr);
511 * Check if the event list should be displayed
513 * @param integer $uid
517 public static function shouldDisplayEventList(int $uid, Mode $mode): bool
519 if (empty($uid) || $mode->isMobile()) {
523 if (!DI::pConfig()->get($uid, 'system', 'display_eventlist', true)) {
527 return !DI::config()->get('theme', 'hide_eventlist');
531 * Returns the upcoming birthdays of contacts of the current user as HTML content
532 * @param int $uid User Id
534 * @return string The upcoming birthdays (HTML)
535 * @throws HTTPException\InternalServerErrorException
536 * @throws HTTPException\ServiceUnavailableException
537 * @throws \ImagickException
539 public static function getBirthdays(int $uid): string
541 $bd_short = DI::l10n()->t('F d');
543 $cacheKey = 'get_birthdays:' . $uid;
544 $events = DI::cache()->get($cacheKey);
545 if (is_null($events)) {
547 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
549 ON `contact`.`id` = `event`.`cid`
550 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
551 AND NOT `contact`.`pending`
552 AND NOT `contact`.`hidden`
553 AND NOT `contact`.`blocked`
554 AND NOT `contact`.`archive`
555 AND NOT `contact`.`deleted`
556 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
561 DateTimeFormat::utc('now + 6 days'),
562 DateTimeFormat::utcNow()
564 if (DBA::isResult($result)) {
565 $events = DBA::toArray($result);
566 DI::cache()->set($cacheKey, $events, Duration::HOUR);
573 if (DBA::isResult($events)) {
574 $now = strtotime('now');
578 foreach ($events as $event) {
579 if (strlen($event['name'])) {
582 if ((strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now)) {
586 $classToday = $isToday ? ' birthday-today ' : '';
588 foreach ($events as $event) {
589 if (!strlen($event['name'])) {
594 if (in_array($event['cid'], $cids)) {
597 $cids[] = $event['cid'];
599 $today = (strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now);
602 'id' => $event['id'],
603 'link' => Contact::magicLinkById($event['cid']),
604 'title' => $event['name'],
605 'date' => DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '')
610 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
611 return Renderer::replaceMacros($tpl, [
612 '$classtoday' => $classToday,
614 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
615 '$event_title' => DI::l10n()->t('Birthdays this week:'),
616 '$events' => $tpl_events,
617 '$lbr' => '{', // raw brackets mess up if/endif macro processing
623 * Renders HTML for event reminder (e.g. contact birthdays
624 * @param int $uid User Id
625 * @param int $pcid Public Contact Id
627 * @return string Rendered HTML
629 public static function getEventsReminderHTML(int $uid, int $pcid): string
631 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
634 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
635 $uid, DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
636 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
640 if (DBA::isResult($s)) {
644 while ($rr = DBA::fetch($s)) {
645 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => $pcid,
646 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
647 'visible' => true, 'deleted' => false];
648 if (!Post::exists($condition)) {
652 if (strlen($rr['summary'])) {
656 $strt = DateTimeFormat::local($rr['start'], 'Y-m-d');
657 if ($strt === DateTimeFormat::localNow('Y-m-d')) {
661 $title = BBCode::toPlaintext($rr['summary'], false);
663 if (strlen($title) > 35) {
664 $title = substr($title, 0, 32) . '... ';
667 $description = BBCode::toPlaintext($rr['desc'], false) . '... ';
669 $description = DI::l10n()->t('[No description]');
672 $strt = DateTimeFormat::local($rr['start']);
674 if (substr($strt, 0, 10) < DateTimeFormat::localNow('Y-m-d')) {
678 $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d');
680 $rr['title'] = $title;
681 $rr['description'] = $description;
682 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
683 $rr['startime'] = $strt;
684 $rr['today'] = $today;
689 $classtoday = (($istoday) ? 'event-today' : '');
691 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
692 return Renderer::replaceMacros($tpl, [
693 '$classtoday' => $classtoday,
694 '$count' => count($r),
695 '$event_reminders' => DI::l10n()->t('Event Reminders'),
696 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
702 * Retrieves the my_url session variable
705 * @deprecated since version 2022.12, please use UserSession->getMyUrl instead
707 public static function getMyURL(): string
709 return DI::userSession()->getMyUrl();
713 * Process the 'zrl' parameter and initiate the remote authentication.
715 * This method checks if the visitor has a public contact entry and
716 * redirects the visitor to his/her instance to start the magic auth (Authentication)
719 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
721 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
722 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
723 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
725 * It would be favourable to harmonize the two implementations.
727 * @param App $a Application instance.
730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731 * @throws \ImagickException
733 public static function zrlInit(App $a)
735 $my_url = self::getMyURL();
736 $my_url = Network::isUrlValid($my_url);
738 if (empty($my_url) || DI::userSession()->getLocalUserId()) {
742 $addr = $_GET['addr'] ?? $my_url;
744 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
745 Hook::callAll('zrl_init', $arr);
747 // Try to find the public contact entry of the visitor.
748 $cid = Contact::getIdForURL($my_url);
750 Logger::info('No contact record found for ' . $my_url);
754 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
756 if (DBA::isResult($contact) && DI::userSession()->getRemoteUserId() && DI::userSession()->getRemoteUserId() == $contact['id']) {
757 Logger::info('The visitor ' . $my_url . ' is already authenticated');
761 // Avoid endless loops
762 $cachekey = 'zrlInit:' . $my_url;
763 if (DI::cache()->get($cachekey)) {
764 Logger::info('URL ' . $my_url . ' already tried to authenticate.');
767 DI::cache()->set($cachekey, true, Duration::MINUTE);
770 Logger::info('Not authenticated. Invoking reverse magic-auth for ' . $my_url);
772 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
773 $addr_request = 'addr=' . urlencode($addr);
774 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
776 // The other instance needs to know where to redirect.
777 $dest = urlencode(DI::baseUrl() . '/' . $query);
779 // We need to extract the basebath from the profile url
780 // to redirect the visitors '/magic' module.
781 $basepath = Contact::getBasepath($contact['url']);
783 if ($basepath != DI::baseUrl() && !strstr($dest, '/magic')) {
784 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
786 // We have to check if the remote server does understand /magic without invoking something
787 $serverret = DI::httpClient()->head($basepath . '/magic', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::HTML]);
788 if ($serverret->isSuccess()) {
789 Logger::info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path);
790 System::externalRedirect($magic_path);
796 * Set the visitor cookies (see remote_user()) for the given handle
798 * @param string $handle Visitor handle
800 * @return array Visitor contact array
802 public static function addVisitorCookieForHandle(string $handle): array
806 // Try to find the public contact entry of the visitor.
807 $cid = Contact::getIdForURL($handle);
809 Logger::info('Handle not found', ['handle' => $handle]);
813 $visitor = Contact::getById($cid);
815 // Authenticate the visitor.
816 DI::userSession()->setMultiple([
817 'authenticated' => 1,
818 'visitor_id' => $visitor['id'],
819 'visitor_handle' => $visitor['addr'],
820 'visitor_home' => $visitor['url'],
821 'my_url' => $visitor['url'],
822 'remote_comment' => $visitor['subscribe'],
825 DI::userSession()->setVisitorsContacts($visitor['url']);
827 $a->setContactId($visitor['id']);
829 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
835 * Set the visitor cookies (see remote_user()) for signed HTTP requests
837 * @param array $server The content of the $_SERVER superglobal
838 * @return array Visitor contact array
839 * @throws InternalServerErrorException
841 public static function addVisitorCookieForHTTPSigner(array $server): array
843 $requester = HTTPSignature::getSigner('', $server);
844 if (empty($requester)) {
847 return Profile::addVisitorCookieForHandle($requester);
851 * OpenWebAuth authentication.
853 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
855 * @param string $token
858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859 * @throws \ImagickException
861 public static function openWebAuthInit(string $token)
865 // Clean old OpenWebAuthToken entries.
866 OpenWebAuthToken::purge('owt', '3 MINUTE');
868 // Check if the token we got is the same one
869 // we have stored in the database.
870 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
872 if ($visitor_handle === false) {
876 $visitor = self::addVisitorCookieForHandle($visitor_handle);
877 if (empty($visitor)) {
882 'visitor' => $visitor,
883 'url' => DI::args()->getQueryString()
886 * @hooks magic_auth_success
887 * Called when a magic-auth was successful.
888 * * \e array \b visitor
891 Hook::callAll('magic_auth_success', $arr);
893 $a->setContactId($arr['visitor']['id']);
895 DI::sysmsg()->addInfo(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHost(), $visitor['name']));
897 Logger::info('OpenWebAuth: auth success from ' . $visitor['addr']);
901 * Returns URL with URL-encoded zrl parameter
903 * @param string $url URL to enhance
904 * @param bool $force Either to force adding zrl parameter
906 * @return string URL with 'zrl' parameter or original URL in case of no Friendica profile URL
908 public static function zrl(string $url, bool $force = false): string
913 if (!strpos($url, '/profile/') && !$force) {
916 if ($force && substr($url, -1, 1) !== '/') {
920 $achar = strpos($url, '?') ? '&' : '?';
921 $mine = self::getMyURL();
923 if ($mine && !Strings::compareLink($mine, $url)) {
924 return $url . $achar . 'zrl=' . urlencode($mine);
931 * Get the user ID of the page owner.
933 * Used from within PCSS themes to set theme parameters. If there's a
934 * profile_uid variable set in App, that is the "page owner" and normally their theme
935 * settings take precedence; unless a local user is logged in which means they don't
936 * want to see anybody else's theme settings except their own while on this site.
940 * @return int user ID
942 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
944 public static function getThemeUid(App $a): int
946 return DI::userSession()->getLocalUserId() ?: $a->getProfileOwner();
950 * search for Profiles
952 * @param int $start Starting record (see LIMIT start,count)
953 * @param int $count Maximum records (see LIMIT start,count)
954 * @param string $search Optional search word (see LIKE %s?%s)
956 * @return array [ 'total' => 123, 'entries' => [...] ];
960 public static function searchProfiles(int $start = 0, int $count = 100, string $search = null): array
962 if (!empty($search)) {
963 $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
964 $searchTerm = '%' . $search . '%';
965 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`
967 AND ((`name` LIKE ?) OR
968 (`nickname` LIKE ?) OR
970 (`locality` LIKE ?) OR
972 (`country-name` LIKE ?) OR
973 (`pub_keywords` LIKE ?) OR
974 (`prv_keywords` LIKE ?))",
975 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
976 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
978 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
979 if (!DI::config()->get('system', 'publish_all')) {
980 $condition['publish'] = true;
984 $total = DBA::count('owner-view', $condition);
986 // If nothing found, don't try to select details
988 $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
993 return ['total' => $total, 'entries' => $profiles];
997 * Migrates a legacy profile to the new slimmer profile with extra custom fields.
998 * Multi profiles are converted to ACl-protected custom fields and deleted.
1000 * @param array $profile One profile array
1003 * @throws \Exception
1005 public static function migrate(array $profile)
1007 // Already processed, aborting
1008 if ($profile['is-default'] === null) {
1014 if (!$profile['is-default']) {
1015 $contacts = Contact::selectToArray(['id'], [
1016 'uid' => $profile['uid'],
1017 'profile-id' => $profile['id']
1019 if (!count($contacts)) {
1020 // No contact visibility selected defaults to user-only permission
1021 $contacts = Contact::selectToArray(['id'], ['uid' => $profile['uid'], 'self' => true]);
1025 $permissionSet = DI::permissionSet()->selectOrCreate(
1028 array_column($contacts, 'id') ?? []
1035 'hometown' => DI::l10n()->t('Hometown:'),
1036 'marital' => DI::l10n()->t('Marital Status:'),
1037 'with' => DI::l10n()->t('With:'),
1038 'howlong' => DI::l10n()->t('Since:'),
1039 'sexual' => DI::l10n()->t('Sexual Preference:'),
1040 'politic' => DI::l10n()->t('Political Views:'),
1041 'religion' => DI::l10n()->t('Religious Views:'),
1042 'likes' => DI::l10n()->t('Likes:'),
1043 'dislikes' => DI::l10n()->t('Dislikes:'),
1044 'pdesc' => DI::l10n()->t('Title/Description:'),
1045 'summary' => DI::l10n()->t('Summary'),
1046 'music' => DI::l10n()->t('Musical interests'),
1047 'book' => DI::l10n()->t('Books, literature'),
1048 'tv' => DI::l10n()->t('Television'),
1049 'film' => DI::l10n()->t('Film/dance/culture/entertainment'),
1050 'interest' => DI::l10n()->t('Hobbies/Interests'),
1051 'romance' => DI::l10n()->t('Love/romance'),
1052 'work' => DI::l10n()->t('Work/employment'),
1053 'education' => DI::l10n()->t('School/education'),
1054 'contact' => DI::l10n()->t('Contact information and Social Networks'),
1057 foreach ($custom_fields as $field => $label) {
1058 if (!empty($profile[$field]) && $profile[$field] > DBA::NULL_DATE && $profile[$field] > DBA::NULL_DATETIME) {
1059 DI::profileField()->save(DI::profileFieldFactory()->createFromValues(
1068 $profile[$field] = null;
1071 if ($profile['is-default']) {
1072 $profile['profile-name'] = null;
1073 $profile['is-default'] = null;
1074 DBA::update('profile', $profile, ['id' => $profile['id']]);
1075 } else if (!empty($profile['id'])) {
1076 DBA::delete('profile', ['id' => $profile['id']]);