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\HttpClient;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Security\PermissionSet\Entity\PermissionSet;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
53 * Returns default profile for a given user id
55 * @param integer User ID
57 * @return array Profile data
60 public static function getByUID($uid)
62 return DBA::selectFirst('profile', [], ['uid' => $uid]);
66 * Returns default profile for a given user ID and ID
68 * @param int $uid The contact ID
69 * @param int $id The contact owner ID
70 * @param array $fields The selected fields
72 * @return array Profile data for the ID
75 public static function getById(int $uid, int $id, array $fields = [])
77 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
81 * Returns profile data for the contact owner
83 * @param int $uid The User ID
84 * @param array $fields The fields to retrieve
86 * @return array Array of profile data
89 public static function getListByUser(int $uid, array $fields = [])
91 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
95 * Update a profile entry and distribute the changes if needed
97 * @param array $fields
101 public static function update(array $fields, int $uid): bool
103 $old_owner = User::getOwnerDataById($uid);
104 if (empty($old_owner)) {
108 if (!DBA::update('profile', $fields, ['uid' => $uid])) {
112 $update = Contact::updateSelfFromUserID($uid);
114 $owner = User::getOwnerDataById($uid);
119 if ($old_owner['name'] != $owner['name']) {
120 User::update(['username' => $owner['name']], $uid);
123 $profile_fields = ['postal-code', 'dob', 'prv_keywords', 'homepage'];
124 foreach ($profile_fields as $field) {
125 if ($old_owner[$field] != $owner[$field]) {
131 self::publishUpdate($uid, ($old_owner['net-publish'] != $owner['net-publish']));
138 * Publish a changed profile
140 * @param bool $force Force publishing to the directory
142 public static function publishUpdate(int $uid, bool $force = false)
144 $owner = User::getOwnerDataById($uid);
149 if ($owner['net-publish'] || $force) {
150 // Update global directory in background
151 if (Search::getGlobalDirectory()) {
152 Worker::add(PRIORITY_LOW, 'Directory', $owner['url']);
156 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $uid);
160 * Returns a formatted location string from the given profile array
162 * @param array $profile Profile array (Generated from the "profile" table)
164 * @return string Location string
166 public static function formatLocation(array $profile)
170 if (!empty($profile['locality'])) {
171 $location .= $profile['locality'];
174 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
179 $location .= $profile['region'];
182 if (!empty($profile['country-name'])) {
187 $location .= $profile['country-name'];
194 * Loads a profile into the page sidebar.
196 * The function requires a writeable copy of the main App structure, and the nickname
197 * of a registered local account.
199 * If the viewer is an authenticated remote viewer, the profile displayed is the
200 * one that has been configured for his/her viewing in the Contact manager.
201 * Passing a non-zero profile ID can also allow a preview of a selected profile
204 * Profile information is placed in the App structure for later retrieval.
205 * Honours the owner's chosen theme for display.
207 * @attention Should only be run in the _init() functions of a module. That ensures that
208 * the theme is chosen before the _init() function of a theme is run, which will usually
209 * load a lot of theme-specific content
212 * @param string $nickname string
213 * @param bool $show_contacts
214 * @return array Profile
216 * @throws HTTPException\NotFoundException
217 * @throws HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 public static function load(App $a, string $nickname, bool $show_contacts = true)
222 $profile = User::getOwnerDataByNick($nickname);
223 if (empty($profile)) {
224 Logger::info('profile error: ' . DI::args()->getQueryString());
228 // System user, aborting
229 if ($profile['uid'] === 0) {
230 DI::logger()->warning('System user found in Profile::load', ['nickname' => $nickname, 'callstack' => System::callstack(20)]);
231 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
234 $a->setProfileOwner($profile['uid']);
236 DI::page()['title'] = $profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
238 if (!DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
239 $a->setCurrentTheme($profile['theme']);
240 $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme'));
244 * load/reload current theme info
247 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
249 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
250 if (file_exists($theme_info_file)) {
251 require_once $theme_info_file;
254 $block = (DI::config()->get('system', 'block_public') && !Session::isAuthenticated());
258 * By now, the contact block isn't shown, when a different profile is given
259 * But: When this profile was on the same server, then we could display the contacts
261 DI::page()['aside'] .= self::getVCardHtml($profile, $block, $show_contacts);
267 * Formats a profile for display in the sidebar.
269 * It is very difficult to templatise the HTML completely
270 * because of all the conditional logic.
272 * @param array $profile Profile array
273 * @param bool $block Block personal details
274 * @param bool $show_contacts Show contact block
276 * @return string HTML sidebar module
278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 * @throws \ImagickException
280 * @note Returns empty string if passed $profile is wrong type or not populated
282 * @hooks 'profile_sidebar_enter'
283 * array $profile - profile data
284 * @hooks 'profile_sidebar'
287 public static function getVCardHtml(array $profile, bool $block, bool $show_contacts)
292 $profile_contact = [];
294 if (local_user() && ($profile['uid'] ?? 0) != local_user()) {
295 $profile_contact = Contact::getByURL($profile['nurl'], null, [], local_user());
297 if (!empty($profile['cid']) && self::getMyURL()) {
298 $profile_contact = Contact::selectFirst([], ['id' => $profile['cid']]);
301 $profile['picdate'] = urlencode($profile['picdate']);
303 $profile['network_link'] = '';
305 Hook::callAll('profile_sidebar_enter', $profile);
307 $profile_url = $profile['url'];
309 $cid = $profile['id'];
312 $unfollow_link = null;
313 $wallmessage_link = null;
315 // Who is the logged-in user to this profile?
316 $visitor_contact = [];
317 if (!empty($profile['uid']) && self::getMyURL()) {
318 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
321 $local_user_is_self = self::getMyURL() && ($profile['url'] == self::getMyURL());
322 $visitor_is_authenticated = (bool)self::getMyURL();
323 $visitor_is_following =
324 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
325 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
326 $visitor_is_followed =
327 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
328 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
329 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
331 if (!$local_user_is_self) {
332 if (!$visitor_is_authenticated) {
333 // Remote follow is only available for local profiles
334 if (!empty($profile['nickname']) && strpos($profile_url, DI::baseUrl()->get()) === 0) {
335 $follow_link = 'remote_follow/' . $profile['nickname'];
338 if ($visitor_is_following) {
339 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url) . '&auto=1';
341 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url) . '&auto=1';
345 if (Contact::canReceivePrivateMessages($profile_contact)) {
346 if ($visitor_is_followed || $visitor_is_following) {
347 $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
348 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
349 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
354 // show edit profile to yourself, but only if this is not meant to be
355 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
357 if (!isset($profile['self']) && $local_user_is_self) {
358 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
360 'chg_photo' => DI::l10n()->t('Change profile photo'),
366 // Fetch the account type
367 $account_type = Contact::getAccountType($profile['account-type']);
369 if (!empty($profile['address']) || !empty($profile['location'])) {
370 $location = DI::l10n()->t('Location:');
373 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
374 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
375 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
376 $matrix = !empty($profile['matrix']) ? DI::l10n()->t('Matrix:') : false;
378 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
379 $location = $homepage = $about = false;
382 $split_name = Diaspora::splitName($profile['name']);
383 $firstname = $split_name['first'];
384 $lastname = $split_name['last'];
386 if (!empty($profile['guid'])) {
388 'guid' => $profile['guid'],
389 'podloc' => DI::baseUrl(),
390 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
391 'nickname' => $profile['nickname'],
392 'fullname' => $profile['name'],
393 'firstname' => $firstname,
394 'lastname' => $lastname,
395 'photo300' => $profile['photo'] ?? '',
396 'photo100' => $profile['thumb'] ?? '',
397 'photo50' => $profile['micro'] ?? '',
407 if (!empty($profile['last-item'])) {
408 $updated = date('c', strtotime($profile['last-item']));
411 if (!$block && $show_contacts) {
412 $contact_block = ContactBlock::getHTML($profile, local_user());
414 if (is_array($profile) && !$profile['hide-friends']) {
415 $contact_count = DBA::count('contact', [
416 'uid' => $profile['uid'],
423 'network' => Protocol::FEDERATED,
428 // Expected profile/vcard.tpl profile.* template variables
434 foreach ($profile as $k => $v) {
435 $k = str_replace('-', '_', $k);
439 if (isset($p['about'])) {
440 $p['about'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['about']);
443 if (isset($p['address'])) {
444 $p['address'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['address']);
447 $p['photo'] = Contact::getAvatarUrlForId($cid, Proxy::SIZE_SMALL);
449 $p['url'] = Contact::magicLinkById($cid, $profile['url']);
451 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
452 $o .= Renderer::replaceMacros($tpl, [
455 '$matrix' => $matrix,
456 '$follow' => DI::l10n()->t('Follow'),
457 '$follow_link' => $follow_link,
458 '$unfollow' => DI::l10n()->t('Unfollow'),
459 '$unfollow_link' => $unfollow_link,
460 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
461 '$subscribe_feed_link' => $profile['poll'],
462 '$wallmessage' => DI::l10n()->t('Message'),
463 '$wallmessage_link' => $wallmessage_link,
464 '$account_type' => $account_type,
465 '$location' => $location,
466 '$homepage' => $homepage,
468 '$network' => DI::l10n()->t('Network:'),
469 '$contacts' => $contact_count,
470 '$updated' => $updated,
471 '$diaspora' => $diaspora,
472 '$contact_block' => $contact_block,
475 $arr = ['profile' => &$profile, 'entry' => &$o];
477 Hook::callAll('profile_sidebar', $arr);
483 * Returns the upcoming birthdays of contacts of the current user as HTML content
485 * @return string The upcoming birthdays (HTML)
487 * @throws HTTPException\InternalServerErrorException
488 * @throws HTTPException\ServiceUnavailableException
489 * @throws \ImagickException
491 public static function getBirthdays(): string
493 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
498 * $mobile_detect = new Mobile_Detect();
499 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
504 $bd_short = DI::l10n()->t('F d');
506 $cacheKey = 'get_birthdays:' . local_user();
507 $events = DI::cache()->get($cacheKey);
508 if (is_null($events)) {
510 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
512 ON `contact`.`id` = `event`.`cid`
513 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
514 AND NOT `contact`.`pending`
515 AND NOT `contact`.`hidden`
516 AND NOT `contact`.`blocked`
517 AND NOT `contact`.`archive`
518 AND NOT `contact`.`deleted`
519 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
524 DateTimeFormat::utc('now + 6 days'),
525 DateTimeFormat::utcNow()
527 if (DBA::isResult($result)) {
528 $events = DBA::toArray($result);
529 DI::cache()->set($cacheKey, $events, Duration::HOUR);
536 if (DBA::isResult($events)) {
537 $now = strtotime('now');
541 foreach ($events as $event) {
542 if (strlen($event['name'])) {
545 if ((strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now)) {
549 $classToday = $isToday ? ' birthday-today ' : '';
551 foreach ($events as $event) {
552 if (!strlen($event['name'])) {
557 if (in_array($event['cid'], $cids)) {
560 $cids[] = $event['cid'];
562 $today = (strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now);
565 'id' => $event['id'],
566 'link' => Contact::magicLinkById($event['cid']),
567 'title' => $event['name'],
568 'date' => DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '')
573 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
574 return Renderer::replaceMacros($tpl, [
575 '$classtoday' => $classToday,
577 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
578 '$event_title' => DI::l10n()->t('Birthdays this week:'),
579 '$events' => $tpl_events,
580 '$lbr' => '{', // raw brackets mess up if/endif macro processing
585 public static function getEventsReminderHTML()
590 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
595 * $mobile_detect = new Mobile_Detect();
596 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
601 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
604 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
605 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
606 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
610 if (DBA::isResult($s)) {
614 while ($rr = DBA::fetch($s)) {
615 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
616 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
617 'visible' => true, 'deleted' => false];
618 if (!Post::exists($condition)) {
622 if (strlen($rr['summary'])) {
626 $strt = DateTimeFormat::local($rr['start'], 'Y-m-d');
627 if ($strt === DateTimeFormat::localNow('Y-m-d')) {
631 $title = strip_tags(html_entity_decode(BBCode::convertForUriId($rr['uri-id'], $rr['summary']), ENT_QUOTES, 'UTF-8'));
633 if (strlen($title) > 35) {
634 $title = substr($title, 0, 32) . '... ';
637 $description = substr(strip_tags(BBCode::convertForUriId($rr['uri-id'], $rr['desc'])), 0, 32) . '... ';
639 $description = DI::l10n()->t('[No description]');
642 $strt = DateTimeFormat::local($rr['start']);
644 if (substr($strt, 0, 10) < DateTimeFormat::localNow('Y-m-d')) {
648 $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d');
650 $rr['title'] = $title;
651 $rr['description'] = $description;
652 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
653 $rr['startime'] = $strt;
654 $rr['today'] = $today;
659 $classtoday = (($istoday) ? 'event-today' : '');
661 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
662 return Renderer::replaceMacros($tpl, [
663 '$classtoday' => $classtoday,
664 '$count' => count($r),
665 '$event_reminders' => DI::l10n()->t('Event Reminders'),
666 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
672 * Retrieves the my_url session variable
676 public static function getMyURL()
678 return Session::get('my_url');
682 * Process the 'zrl' parameter and initiate the remote authentication.
684 * This method checks if the visitor has a public contact entry and
685 * redirects the visitor to his/her instance to start the magic auth (Authentication)
688 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
690 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
691 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
692 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
694 * It would be favourable to harmonize the two implementations.
696 * @param App $a Application instance.
697 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
698 * @throws \ImagickException
700 public static function zrlInit(App $a)
702 $my_url = self::getMyURL();
703 $my_url = Network::isUrlValid($my_url);
705 if (empty($my_url) || local_user()) {
709 $addr = $_GET['addr'] ?? $my_url;
711 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
712 Hook::callAll('zrl_init', $arr);
714 // Try to find the public contact entry of the visitor.
715 $cid = Contact::getIdForURL($my_url);
717 Logger::info('No contact record found for ' . $my_url);
721 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
723 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
724 Logger::info('The visitor ' . $my_url . ' is already authenticated');
728 // Avoid endless loops
729 $cachekey = 'zrlInit:' . $my_url;
730 if (DI::cache()->get($cachekey)) {
731 Logger::info('URL ' . $my_url . ' already tried to authenticate.');
734 DI::cache()->set($cachekey, true, Duration::MINUTE);
737 Logger::info('Not authenticated. Invoking reverse magic-auth for ' . $my_url);
739 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
740 $addr_request = 'addr=' . urlencode($addr);
741 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
743 // The other instance needs to know where to redirect.
744 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
746 // We need to extract the basebath from the profile url
747 // to redirect the visitors '/magic' module.
748 $basepath = Contact::getBasepath($contact['url']);
750 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
751 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
753 // We have to check if the remote server does understand /magic without invoking something
754 $serverret = DI::httpClient()->head($basepath . '/magic', [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_HTML]);
755 if ($serverret->isSuccess()) {
756 Logger::info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path);
757 System::externalRedirect($magic_path);
763 * Set the visitor cookies (see remote_user()) for the given handle
765 * @param string $handle Visitor handle
766 * @return array Visitor contact array
768 public static function addVisitorCookieForHandle($handle)
772 // Try to find the public contact entry of the visitor.
773 $cid = Contact::getIdForURL($handle);
775 Logger::info('Handle not found', ['handle' => $handle]);
779 $visitor = Contact::getById($cid);
781 // Authenticate the visitor.
782 $_SESSION['authenticated'] = 1;
783 $_SESSION['visitor_id'] = $visitor['id'];
784 $_SESSION['visitor_handle'] = $visitor['addr'];
785 $_SESSION['visitor_home'] = $visitor['url'];
786 $_SESSION['my_url'] = $visitor['url'];
787 $_SESSION['remote_comment'] = $visitor['subscribe'];
789 Session::setVisitorsContacts();
791 $a->setContactId($visitor['id']);
793 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
799 * Set the visitor cookies (see remote_user()) for signed HTTP requests
800 * @return array Visitor contact array
802 public static function addVisitorCookieForHTTPSigner()
804 $requester = HTTPSignature::getSigner('', $_SERVER);
805 if (empty($requester)) {
808 return Profile::addVisitorCookieForHandle($requester);
812 * OpenWebAuth authentication.
814 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
816 * @param string $token
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 public static function openWebAuthInit($token)
824 // Clean old OpenWebAuthToken entries.
825 OpenWebAuthToken::purge('owt', '3 MINUTE');
827 // Check if the token we got is the same one
828 // we have stored in the database.
829 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
831 if ($visitor_handle === false) {
835 $visitor = self::addVisitorCookieForHandle($visitor_handle);
836 if (empty($visitor)) {
841 'visitor' => $visitor,
842 'url' => DI::args()->getQueryString()
845 * @hooks magic_auth_success
846 * Called when a magic-auth was successful.
847 * * \e array \b visitor
850 Hook::callAll('magic_auth_success', $arr);
852 $a->setContactId($arr['visitor']['id']);
854 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
856 Logger::info('OpenWebAuth: auth success from ' . $visitor['addr']);
859 public static function zrl($s, $force = false)
864 if (!strpos($s, '/profile/') && !$force) {
867 if ($force && substr($s, -1, 1) !== '/') {
870 $achar = strpos($s, '?') ? '&' : '?';
871 $mine = self::getMyURL();
872 if ($mine && !Strings::compareLink($mine, $s)) {
873 return $s . $achar . 'zrl=' . urlencode($mine);
879 * Get the user ID of the page owner.
881 * Used from within PCSS themes to set theme parameters. If there's a
882 * profile_uid variable set in App, that is the "page owner" and normally their theme
883 * settings take precedence; unless a local user sets the "always_my_theme"
884 * system pconfig, which means they don't want to see anybody else's theme
885 * settings except their own while on this site.
887 * @return int user ID
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
892 public static function getThemeUid(App $a)
894 $uid = !empty($a->getProfileOwner()) ? intval($a->getProfileOwner()) : 0;
895 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
903 * search for Profiles
907 * @param null $search
909 * @return array [ 'total' => 123, 'entries' => [...] ];
913 public static function searchProfiles($start = 0, $count = 100, $search = null)
915 if (!empty($search)) {
916 $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
917 $searchTerm = '%' . $search . '%';
918 $condition = ["NOT `blocked` AND NOT `account_removed`
920 AND ((`name` LIKE ?) OR
921 (`nickname` LIKE ?) OR
923 (`locality` LIKE ?) OR
925 (`country-name` LIKE ?) OR
926 (`pub_keywords` LIKE ?) OR
927 (`prv_keywords` LIKE ?))",
928 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
929 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
931 $condition = ['blocked' => false, 'account_removed' => false];
932 if (!DI::config()->get('system', 'publish_all')) {
933 $condition['publish'] = true;
937 $total = DBA::count('owner-view', $condition);
939 // If nothing found, don't try to select details
941 $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
946 return ['total' => $total, 'entries' => $profiles];
950 * Migrates a legacy profile to the new slimmer profile with extra custom fields.
951 * Multi profiles are converted to ACl-protected custom fields and deleted.
953 * @param array $profile One profile array
956 public static function migrate(array $profile)
958 // Already processed, aborting
959 if ($profile['is-default'] === null) {
965 if (!$profile['is-default']) {
966 $contacts = Contact::selectToArray(['id'], [
967 'uid' => $profile['uid'],
968 'profile-id' => $profile['id']
970 if (!count($contacts)) {
971 // No contact visibility selected defaults to user-only permission
972 $contacts = Contact::selectToArray(['id'], ['uid' => $profile['uid'], 'self' => true]);
976 $permissionSet = DI::permissionSet()->selectOrCreate(
979 array_column($contacts, 'id') ?? []
986 'hometown' => DI::l10n()->t('Hometown:'),
987 'marital' => DI::l10n()->t('Marital Status:'),
988 'with' => DI::l10n()->t('With:'),
989 'howlong' => DI::l10n()->t('Since:'),
990 'sexual' => DI::l10n()->t('Sexual Preference:'),
991 'politic' => DI::l10n()->t('Political Views:'),
992 'religion' => DI::l10n()->t('Religious Views:'),
993 'likes' => DI::l10n()->t('Likes:'),
994 'dislikes' => DI::l10n()->t('Dislikes:'),
995 'pdesc' => DI::l10n()->t('Title/Description:'),
996 'summary' => DI::l10n()->t('Summary'),
997 'music' => DI::l10n()->t('Musical interests'),
998 'book' => DI::l10n()->t('Books, literature'),
999 'tv' => DI::l10n()->t('Television'),
1000 'film' => DI::l10n()->t('Film/dance/culture/entertainment'),
1001 'interest' => DI::l10n()->t('Hobbies/Interests'),
1002 'romance' => DI::l10n()->t('Love/romance'),
1003 'work' => DI::l10n()->t('Work/employment'),
1004 'education' => DI::l10n()->t('School/education'),
1005 'contact' => DI::l10n()->t('Contact information and Social Networks'),
1008 foreach ($custom_fields as $field => $label) {
1009 if (!empty($profile[$field]) && $profile[$field] > DBA::NULL_DATE && $profile[$field] > DBA::NULL_DATETIME) {
1010 DI::profileField()->save(DI::profileFieldFactory()->createFromValues(
1019 $profile[$field] = null;
1022 if ($profile['is-default']) {
1023 $profile['profile-name'] = null;
1024 $profile['is-default'] = null;
1025 DBA::update('profile', $profile, ['id' => $profile['id']]);
1026 } else if (!empty($profile['id'])) {
1027 DBA::delete('profile', ['id' => $profile['id']]);