3 * @copyright Copyright (C) 2010-2022, 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\Content\Text\BBCode;
26 use Friendica\Content\Widget\ContactBlock;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Search;
33 use Friendica\Core\Session;
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\HTTPException;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Security\PermissionSet\Entity\PermissionSet;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\HTTPSignature;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
52 * Returns default profile for a given user id
54 * @param integer User ID
56 * @return array Profile data
59 public static function getByUID($uid)
61 return DBA::selectFirst('profile', [], ['uid' => $uid]);
65 * Returns default profile for a given user ID and ID
67 * @param int $uid The contact ID
68 * @param int $id The contact owner ID
69 * @param array $fields The selected fields
71 * @return array Profile data for the ID
74 public static function getById(int $uid, int $id, array $fields = [])
76 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
80 * Returns profile data for the contact owner
82 * @param int $uid The User ID
83 * @param array $fields The fields to retrieve
85 * @return array Array of profile data
88 public static function getListByUser(int $uid, array $fields = [])
90 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
94 * Update a profile entry and distribute the changes if needed
96 * @param array $fields
100 public static function update(array $fields, int $uid): bool
102 $old_owner = User::getOwnerDataById($uid);
103 if (empty($old_owner)) {
107 if (!DBA::update('profile', $fields, ['uid' => $uid])) {
111 $update = Contact::updateSelfFromUserID($uid);
113 $owner = User::getOwnerDataById($uid);
118 if ($old_owner['name'] != $owner['name']) {
119 User::update(['username' => $owner['name']], $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 bool $force Force publishing to the directory
141 public static function publishUpdate(int $uid, bool $force = false)
143 $owner = User::getOwnerDataById($uid);
148 if ($owner['net-publish'] || $force) {
149 // Update global directory in background
150 if (Search::getGlobalDirectory()) {
151 Worker::add(PRIORITY_LOW, 'Directory', $owner['url']);
155 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $uid);
159 * Returns a formatted location string from the given profile array
161 * @param array $profile Profile array (Generated from the "profile" table)
163 * @return string Location string
165 public static function formatLocation(array $profile)
169 if (!empty($profile['locality'])) {
170 $location .= $profile['locality'];
173 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
178 $location .= $profile['region'];
181 if (!empty($profile['country-name'])) {
186 $location .= $profile['country-name'];
193 * Loads a profile into the page sidebar.
195 * The function requires a writeable copy of the main App structure, and the nickname
196 * of a registered local account.
198 * If the viewer is an authenticated remote viewer, the profile displayed is the
199 * one that has been configured for his/her viewing in the Contact manager.
200 * Passing a non-zero profile ID can also allow a preview of a selected profile
203 * Profile information is placed in the App structure for later retrieval.
204 * Honours the owner's chosen theme for display.
206 * @attention Should only be run in the _init() functions of a module. That ensures that
207 * the theme is chosen before the _init() function of a theme is run, which will usually
208 * load a lot of theme-specific content
211 * @param string $nickname string
212 * @param bool $show_contacts
213 * @return array Profile
215 * @throws HTTPException\NotFoundException
216 * @throws HTTPException\InternalServerErrorException
217 * @throws \ImagickException
219 public static function load(App $a, string $nickname, bool $show_contacts = true)
221 $profile = User::getOwnerDataByNick($nickname);
222 if (empty($profile)) {
223 Logger::info('profile error: ' . DI::args()->getQueryString());
227 // System user, aborting
228 if ($profile['uid'] === 0) {
229 DI::logger()->warning('System user found in Profile::load', ['nickname' => $nickname, 'callstack' => System::callstack(20)]);
230 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
233 $a->setProfileOwner($profile['uid']);
235 DI::page()['title'] = $profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
237 if (!DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
238 $a->setCurrentTheme($profile['theme']);
239 $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme'));
243 * load/reload current theme info
246 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
248 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
249 if (file_exists($theme_info_file)) {
250 require_once $theme_info_file;
253 $block = (DI::config()->get('system', 'block_public') && !Session::isAuthenticated());
257 * By now, the contact block isn't shown, when a different profile is given
258 * But: When this profile was on the same server, then we could display the contacts
260 DI::page()['aside'] .= self::getVCardHtml($profile, $block, $show_contacts);
266 * Formats a profile for display in the sidebar.
268 * It is very difficult to templatise the HTML completely
269 * because of all the conditional logic.
271 * @param array $profile Profile array
272 * @param bool $block Block personal details
273 * @param bool $show_contacts Show contact block
275 * @return string HTML sidebar module
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 * @throws \ImagickException
279 * @note Returns empty string if passed $profile is wrong type or not populated
281 * @hooks 'profile_sidebar_enter'
282 * array $profile - profile data
283 * @hooks 'profile_sidebar'
286 public static function getVCardHtml(array $profile, bool $block, bool $show_contacts)
291 $profile_contact = [];
293 if (local_user() && ($profile['uid'] ?? 0) != local_user()) {
294 $profile_contact = Contact::getByURL($profile['nurl'], null, [], local_user());
296 if (!empty($profile['cid']) && self::getMyURL()) {
297 $profile_contact = Contact::selectFirst([], ['id' => $profile['cid']]);
300 $profile['picdate'] = urlencode($profile['picdate']);
302 $profile['network_link'] = '';
304 Hook::callAll('profile_sidebar_enter', $profile);
306 $profile_url = $profile['url'];
308 $cid = $profile['id'];
311 $unfollow_link = null;
312 $wallmessage_link = null;
314 // Who is the logged-in user to this profile?
315 $visitor_contact = [];
316 if (!empty($profile['uid']) && self::getMyURL()) {
317 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
320 $local_user_is_self = self::getMyURL() && ($profile['url'] == self::getMyURL());
321 $visitor_is_authenticated = (bool)self::getMyURL();
322 $visitor_is_following =
323 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
324 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
325 $visitor_is_followed =
326 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
327 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
328 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
330 if (!$local_user_is_self) {
331 if (!$visitor_is_authenticated) {
332 // Remote follow is only available for local profiles
333 if (!empty($profile['nickname']) && strpos($profile_url, DI::baseUrl()->get()) === 0) {
334 $follow_link = 'remote_follow/' . $profile['nickname'];
337 if ($visitor_is_following) {
338 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url) . '&auto=1';
340 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url) . '&auto=1';
344 if (Contact::canReceivePrivateMessages($profile_contact)) {
345 if ($visitor_is_followed || $visitor_is_following) {
346 $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
347 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
348 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
353 // show edit profile to yourself, but only if this is not meant to be
354 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
356 if (!isset($profile['self']) && $local_user_is_self) {
357 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
359 'chg_photo' => DI::l10n()->t('Change profile photo'),
365 // Fetch the account type
366 $account_type = Contact::getAccountType($profile['account-type']);
368 if (!empty($profile['address']) || !empty($profile['location'])) {
369 $location = DI::l10n()->t('Location:');
372 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
373 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
374 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
375 $matrix = !empty($profile['matrix']) ? DI::l10n()->t('Matrix:') : false;
377 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
378 $location = $homepage = $about = false;
381 $split_name = Diaspora::splitName($profile['name']);
382 $firstname = $split_name['first'];
383 $lastname = $split_name['last'];
385 if (!empty($profile['guid'])) {
387 'guid' => $profile['guid'],
388 'podloc' => DI::baseUrl(),
389 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
390 'nickname' => $profile['nickname'],
391 'fullname' => $profile['name'],
392 'firstname' => $firstname,
393 'lastname' => $lastname,
394 'photo300' => $profile['photo'] ?? '',
395 'photo100' => $profile['thumb'] ?? '',
396 'photo50' => $profile['micro'] ?? '',
406 if (!empty($profile['last-item'])) {
407 $updated = date('c', strtotime($profile['last-item']));
410 if (!$block && $show_contacts) {
411 $contact_block = ContactBlock::getHTML($profile, local_user());
413 if (is_array($profile) && !$profile['hide-friends']) {
414 $contact_count = DBA::count('contact', [
415 'uid' => $profile['uid'],
422 'network' => Protocol::FEDERATED,
427 // Expected profile/vcard.tpl profile.* template variables
433 foreach ($profile as $k => $v) {
434 $k = str_replace('-', '_', $k);
438 if (isset($p['about'])) {
439 $p['about'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['about']);
442 if (isset($p['address'])) {
443 $p['address'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['address']);
446 $p['photo'] = Contact::getAvatarUrlForId($cid, Proxy::SIZE_SMALL);
448 $p['url'] = Contact::magicLinkById($cid, $profile['url']);
450 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
451 $o .= Renderer::replaceMacros($tpl, [
454 '$matrix' => $matrix,
455 '$follow' => DI::l10n()->t('Follow'),
456 '$follow_link' => $follow_link,
457 '$unfollow' => DI::l10n()->t('Unfollow'),
458 '$unfollow_link' => $unfollow_link,
459 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
460 '$subscribe_feed_link' => $profile['poll'],
461 '$wallmessage' => DI::l10n()->t('Message'),
462 '$wallmessage_link' => $wallmessage_link,
463 '$account_type' => $account_type,
464 '$location' => $location,
465 '$homepage' => $homepage,
467 '$network' => DI::l10n()->t('Network:'),
468 '$contacts' => $contact_count,
469 '$updated' => $updated,
470 '$diaspora' => $diaspora,
471 '$contact_block' => $contact_block,
474 $arr = ['profile' => &$profile, 'entry' => &$o];
476 Hook::callAll('profile_sidebar', $arr);
482 * Returns the upcoming birthdays of contacts of the current user as HTML content
484 * @return string The upcoming birthdays (HTML)
486 * @throws HTTPException\InternalServerErrorException
487 * @throws HTTPException\ServiceUnavailableException
488 * @throws \ImagickException
490 public static function getBirthdays(): string
492 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
497 * $mobile_detect = new Mobile_Detect();
498 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
503 $bd_short = DI::l10n()->t('F d');
505 $cacheKey = 'get_birthdays:' . local_user();
506 $events = DI::cache()->get($cacheKey);
507 if (is_null($events)) {
509 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
511 ON `contact`.`id` = `event`.`cid`
512 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
513 AND NOT `contact`.`pending`
514 AND NOT `contact`.`hidden`
515 AND NOT `contact`.`blocked`
516 AND NOT `contact`.`archive`
517 AND NOT `contact`.`deleted`
518 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
523 DateTimeFormat::utc('now + 6 days'),
524 DateTimeFormat::utcNow()
526 if (DBA::isResult($result)) {
527 $events = DBA::toArray($result);
528 DI::cache()->set($cacheKey, $events, Duration::HOUR);
535 if (DBA::isResult($events)) {
536 $now = strtotime('now');
540 foreach ($events as $event) {
541 if (strlen($event['name'])) {
544 if ((strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now)) {
548 $classToday = $isToday ? ' birthday-today ' : '';
550 foreach ($events as $event) {
551 if (!strlen($event['name'])) {
556 if (in_array($event['cid'], $cids)) {
559 $cids[] = $event['cid'];
561 $today = (strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now);
564 'id' => $event['id'],
565 'link' => Contact::magicLinkById($event['cid']),
566 'title' => $event['name'],
567 'date' => DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '')
572 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
573 return Renderer::replaceMacros($tpl, [
574 '$classtoday' => $classToday,
576 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
577 '$event_title' => DI::l10n()->t('Birthdays this week:'),
578 '$events' => $tpl_events,
579 '$lbr' => '{', // raw brackets mess up if/endif macro processing
584 public static function getEventsReminderHTML()
589 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
594 * $mobile_detect = new Mobile_Detect();
595 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
600 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
603 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
604 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
605 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
609 if (DBA::isResult($s)) {
613 while ($rr = DBA::fetch($s)) {
614 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
615 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
616 'visible' => true, 'deleted' => false];
617 if (!Post::exists($condition)) {
621 if (strlen($rr['summary'])) {
625 $strt = DateTimeFormat::local($rr['start'], 'Y-m-d');
626 if ($strt === DateTimeFormat::localNow('Y-m-d')) {
630 $title = strip_tags(html_entity_decode(BBCode::convertForUriId($rr['uri-id'], $rr['summary']), ENT_QUOTES, 'UTF-8'));
632 if (strlen($title) > 35) {
633 $title = substr($title, 0, 32) . '... ';
636 $description = substr(strip_tags(BBCode::convertForUriId($rr['uri-id'], $rr['desc'])), 0, 32) . '... ';
638 $description = DI::l10n()->t('[No description]');
641 $strt = DateTimeFormat::local($rr['start']);
643 if (substr($strt, 0, 10) < DateTimeFormat::localNow('Y-m-d')) {
647 $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d');
649 $rr['title'] = $title;
650 $rr['description'] = $description;
651 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
652 $rr['startime'] = $strt;
653 $rr['today'] = $today;
658 $classtoday = (($istoday) ? 'event-today' : '');
660 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
661 return Renderer::replaceMacros($tpl, [
662 '$classtoday' => $classtoday,
663 '$count' => count($r),
664 '$event_reminders' => DI::l10n()->t('Event Reminders'),
665 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
671 * Retrieves the my_url session variable
675 public static function getMyURL()
677 return Session::get('my_url');
681 * Process the 'zrl' parameter and initiate the remote authentication.
683 * This method checks if the visitor has a public contact entry and
684 * redirects the visitor to his/her instance to start the magic auth (Authentication)
687 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
689 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
690 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
691 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
693 * It would be favourable to harmonize the two implementations.
695 * @param App $a Application instance.
696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 * @throws \ImagickException
699 public static function zrlInit(App $a)
701 $my_url = self::getMyURL();
702 $my_url = Network::isUrlValid($my_url);
704 if (empty($my_url) || local_user()) {
708 $addr = $_GET['addr'] ?? $my_url;
710 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
711 Hook::callAll('zrl_init', $arr);
713 // Try to find the public contact entry of the visitor.
714 $cid = Contact::getIdForURL($my_url);
716 Logger::info('No contact record found for ' . $my_url);
720 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
722 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
723 Logger::info('The visitor ' . $my_url . ' is already authenticated');
727 // Avoid endless loops
728 $cachekey = 'zrlInit:' . $my_url;
729 if (DI::cache()->get($cachekey)) {
730 Logger::info('URL ' . $my_url . ' already tried to authenticate.');
733 DI::cache()->set($cachekey, true, Duration::MINUTE);
736 Logger::info('Not authenticated. Invoking reverse magic-auth for ' . $my_url);
738 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
739 $addr_request = 'addr=' . urlencode($addr);
740 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
742 // The other instance needs to know where to redirect.
743 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
745 // We need to extract the basebath from the profile url
746 // to redirect the visitors '/magic' module.
747 $basepath = Contact::getBasepath($contact['url']);
749 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
750 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
752 // We have to check if the remote server does understand /magic without invoking something
753 $serverret = DI::httpClient()->head($basepath . '/magic', HttpClientAccept::HTML);
754 if ($serverret->isSuccess()) {
755 Logger::info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path);
756 System::externalRedirect($magic_path);
762 * Set the visitor cookies (see remote_user()) for the given handle
764 * @param string $handle Visitor handle
765 * @return array Visitor contact array
767 public static function addVisitorCookieForHandle($handle)
771 // Try to find the public contact entry of the visitor.
772 $cid = Contact::getIdForURL($handle);
774 Logger::info('Handle not found', ['handle' => $handle]);
778 $visitor = Contact::getById($cid);
780 // Authenticate the visitor.
781 $_SESSION['authenticated'] = 1;
782 $_SESSION['visitor_id'] = $visitor['id'];
783 $_SESSION['visitor_handle'] = $visitor['addr'];
784 $_SESSION['visitor_home'] = $visitor['url'];
785 $_SESSION['my_url'] = $visitor['url'];
786 $_SESSION['remote_comment'] = $visitor['subscribe'];
788 Session::setVisitorsContacts();
790 $a->setContactId($visitor['id']);
792 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
798 * Set the visitor cookies (see remote_user()) for signed HTTP requests
799 * @return array Visitor contact array
801 public static function addVisitorCookieForHTTPSigner()
803 $requester = HTTPSignature::getSigner('', $_SERVER);
804 if (empty($requester)) {
807 return Profile::addVisitorCookieForHandle($requester);
811 * OpenWebAuth authentication.
813 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
815 * @param string $token
816 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817 * @throws \ImagickException
819 public static function openWebAuthInit($token)
823 // Clean old OpenWebAuthToken entries.
824 OpenWebAuthToken::purge('owt', '3 MINUTE');
826 // Check if the token we got is the same one
827 // we have stored in the database.
828 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
830 if ($visitor_handle === false) {
834 $visitor = self::addVisitorCookieForHandle($visitor_handle);
835 if (empty($visitor)) {
840 'visitor' => $visitor,
841 'url' => DI::args()->getQueryString()
844 * @hooks magic_auth_success
845 * Called when a magic-auth was successful.
846 * * \e array \b visitor
849 Hook::callAll('magic_auth_success', $arr);
851 $a->setContactId($arr['visitor']['id']);
853 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
855 Logger::info('OpenWebAuth: auth success from ' . $visitor['addr']);
858 public static function zrl($s, $force = false)
863 if (!strpos($s, '/profile/') && !$force) {
866 if ($force && substr($s, -1, 1) !== '/') {
869 $achar = strpos($s, '?') ? '&' : '?';
870 $mine = self::getMyURL();
871 if ($mine && !Strings::compareLink($mine, $s)) {
872 return $s . $achar . 'zrl=' . urlencode($mine);
878 * Get the user ID of the page owner.
880 * Used from within PCSS themes to set theme parameters. If there's a
881 * profile_uid variable set in App, that is the "page owner" and normally their theme
882 * settings take precedence; unless a local user sets the "always_my_theme"
883 * system pconfig, which means they don't want to see anybody else's theme
884 * settings except their own while on this site.
886 * @return int user ID
888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
889 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
891 public static function getThemeUid(App $a)
893 $uid = !empty($a->getProfileOwner()) ? intval($a->getProfileOwner()) : 0;
894 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
902 * search for Profiles
906 * @param null $search
908 * @return array [ 'total' => 123, 'entries' => [...] ];
912 public static function searchProfiles($start = 0, $count = 100, $search = null)
914 if (!empty($search)) {
915 $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
916 $searchTerm = '%' . $search . '%';
917 $condition = ["NOT `blocked` AND NOT `account_removed`
919 AND ((`name` LIKE ?) OR
920 (`nickname` LIKE ?) OR
922 (`locality` LIKE ?) OR
924 (`country-name` LIKE ?) OR
925 (`pub_keywords` LIKE ?) OR
926 (`prv_keywords` LIKE ?))",
927 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
928 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
930 $condition = ['blocked' => false, 'account_removed' => false];
931 if (!DI::config()->get('system', 'publish_all')) {
932 $condition['publish'] = true;
936 $total = DBA::count('owner-view', $condition);
938 // If nothing found, don't try to select details
940 $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
945 return ['total' => $total, 'entries' => $profiles];
949 * Migrates a legacy profile to the new slimmer profile with extra custom fields.
950 * Multi profiles are converted to ACl-protected custom fields and deleted.
952 * @param array $profile One profile array
955 public static function migrate(array $profile)
957 // Already processed, aborting
958 if ($profile['is-default'] === null) {
964 if (!$profile['is-default']) {
965 $contacts = Contact::selectToArray(['id'], [
966 'uid' => $profile['uid'],
967 'profile-id' => $profile['id']
969 if (!count($contacts)) {
970 // No contact visibility selected defaults to user-only permission
971 $contacts = Contact::selectToArray(['id'], ['uid' => $profile['uid'], 'self' => true]);
975 $permissionSet = DI::permissionSet()->selectOrCreate(
978 array_column($contacts, 'id') ?? []
985 'hometown' => DI::l10n()->t('Hometown:'),
986 'marital' => DI::l10n()->t('Marital Status:'),
987 'with' => DI::l10n()->t('With:'),
988 'howlong' => DI::l10n()->t('Since:'),
989 'sexual' => DI::l10n()->t('Sexual Preference:'),
990 'politic' => DI::l10n()->t('Political Views:'),
991 'religion' => DI::l10n()->t('Religious Views:'),
992 'likes' => DI::l10n()->t('Likes:'),
993 'dislikes' => DI::l10n()->t('Dislikes:'),
994 'pdesc' => DI::l10n()->t('Title/Description:'),
995 'summary' => DI::l10n()->t('Summary'),
996 'music' => DI::l10n()->t('Musical interests'),
997 'book' => DI::l10n()->t('Books, literature'),
998 'tv' => DI::l10n()->t('Television'),
999 'film' => DI::l10n()->t('Film/dance/culture/entertainment'),
1000 'interest' => DI::l10n()->t('Hobbies/Interests'),
1001 'romance' => DI::l10n()->t('Love/romance'),
1002 'work' => DI::l10n()->t('Work/employment'),
1003 'education' => DI::l10n()->t('School/education'),
1004 'contact' => DI::l10n()->t('Contact information and Social Networks'),
1007 foreach ($custom_fields as $field => $label) {
1008 if (!empty($profile[$field]) && $profile[$field] > DBA::NULL_DATE && $profile[$field] > DBA::NULL_DATETIME) {
1009 DI::profileField()->save(DI::profileFieldFactory()->createFromValues(
1018 $profile[$field] = null;
1021 if ($profile['is-default']) {
1022 $profile['profile-name'] = null;
1023 $profile['is-default'] = null;
1024 DBA::update('profile', $profile, ['id' => $profile['id']]);
1025 } else if (!empty($profile['id'])) {
1026 DBA::delete('profile', ['id' => $profile['id']]);