3 * @copyright Copyright (C) 2010-2021, 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\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\Protocol\Activity;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy as ProxyUtils;
43 use Friendica\Util\Strings;
48 * Returns default profile for a given user id
50 * @param integer User ID
52 * @return array Profile data
55 public static function getByUID($uid)
57 return DBA::selectFirst('profile', [], ['uid' => $uid]);
61 * Returns default profile for a given user ID and ID
63 * @param int $uid The contact ID
64 * @param int $id The contact owner ID
65 * @param array $fields The selected fields
67 * @return array Profile data for the ID
70 public static function getById(int $uid, int $id, array $fields = [])
72 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
76 * Returns profile data for the contact owner
78 * @param int $uid The User ID
79 * @param array $fields The fields to retrieve
81 * @return array Array of profile data
84 public static function getListByUser(int $uid, array $fields = [])
86 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
90 * Update a profile entry and distribute the changes if needed
92 * @param array $fields
96 public static function update(array $fields, int $uid): bool
98 $old_owner = User::getOwnerDataById($uid);
99 if (empty($old_owner)) {
103 if (!DBA::update('profile', $fields, ['uid' => $uid])) {
107 $update = Contact::updateSelfFromUserID($uid);
109 $owner = User::getOwnerDataById($uid);
114 if ($old_owner['name'] != $owner['name']) {
115 User::update(['username' => $owner['name']], $uid);
118 $profile_fields = ['postal-code', 'dob', 'prv_keywords', 'homepage'];
119 foreach ($profile_fields as $field) {
120 if ($old_owner[$field] != $owner[$field]) {
126 self::publishUpdate($uid, ($old_owner['net-publish'] != $owner['net-publish']));
133 * Publish a changed profile
135 * @param bool $force Force publishing to the directory
137 public static function publishUpdate(int $uid, bool $force = false)
139 $owner = User::getOwnerDataById($uid);
144 if ($owner['net-publish'] || $force) {
145 // Update global directory in background
146 if (Search::getGlobalDirectory()) {
147 Worker::add(PRIORITY_LOW, 'Directory', $owner['url']);
151 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $uid);
155 * Returns a formatted location string from the given profile array
157 * @param array $profile Profile array (Generated from the "profile" table)
159 * @return string Location string
161 public static function formatLocation(array $profile)
165 if (!empty($profile['locality'])) {
166 $location .= $profile['locality'];
169 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
174 $location .= $profile['region'];
177 if (!empty($profile['country-name'])) {
182 $location .= $profile['country-name'];
189 * Loads a profile into the page sidebar.
191 * The function requires a writeable copy of the main App structure, and the nickname
192 * of a registered local account.
194 * If the viewer is an authenticated remote viewer, the profile displayed is the
195 * one that has been configured for his/her viewing in the Contact manager.
196 * Passing a non-zero profile ID can also allow a preview of a selected profile
199 * Profile information is placed in the App structure for later retrieval.
200 * Honours the owner's chosen theme for display.
202 * @attention Should only be run in the _init() functions of a module. That ensures that
203 * the theme is chosen before the _init() function of a theme is run, which will usually
204 * load a lot of theme-specific content
207 * @param string $nickname string
208 * @param array $profiledata array
209 * @param boolean $show_connect Show connect link
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
211 * @throws \ImagickException
213 public static function load(App $a, $nickname, array $profiledata = [], $show_connect = true)
215 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
217 if (!DBA::isResult($user) && empty($profiledata)) {
218 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
222 if (count($profiledata) > 0) {
223 // Ensure to have a "nickname" field
224 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
225 $profiledata['nickname'] = $profiledata['nick'];
228 // Add profile data to sidebar
229 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
231 if (!DBA::isResult($user)) {
236 $profile = !empty($user['uid']) ? User::getOwnerDataById($user['uid'], false) : [];
238 if (empty($profile) && empty($profiledata)) {
239 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
243 if (empty($profile)) {
244 $profile = ['uid' => 0, 'name' => $nickname];
247 $a->profile = $profile;
248 $a->profile_uid = $profile['uid'];
250 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['uid'], 'system', 'mobile_theme');
251 $a->profile['network'] = Protocol::DFRN;
253 DI::page()['title'] = $a->profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
255 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
256 $a->setCurrentTheme($a->profile['theme']);
257 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
261 * load/reload current theme info
264 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
266 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
267 if (file_exists($theme_info_file)) {
268 require_once $theme_info_file;
271 $block = ((DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
275 * By now, the contact block isn't shown, when a different profile is given
276 * But: When this profile was on the same server, then we could display the contacts
279 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
286 * Get the profile for the given nick name
288 * Includes all available profile data
290 * @param string $nickname nick
294 public static function getByNickname($nickname)
296 $profile = DBA::selectFirst('owner-view', [], ['nickname' => $nickname]);
301 * Formats a profile for display in the sidebar.
303 * It is very difficult to templatise the HTML completely
304 * because of all the conditional logic.
306 * @param array $profile
308 * @param boolean $show_connect Show connect link
310 * @return string HTML sidebar module
312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313 * @throws \ImagickException
314 * @note Returns empty string if passed $profile is wrong type or not populated
316 * @hooks 'profile_sidebar_enter'
317 * array $profile - profile data
318 * @hooks 'profile_sidebar'
321 private static function sidebar(App $a, array $profile, $block = 0, $show_connect = true)
326 // This function can also use contact information in $profile, but the 'cid'
327 // value is going to be coming from 'owner-view', which means it's the wrong
328 // contact ID for the user viewing this page. Use 'nurl' to look up the
329 // correct contact table entry for the logged-in user.
330 $profile_contact = [];
332 if (!empty($profile['nurl'] ?? '')) {
333 if (local_user() && ($profile['uid'] ?? '') != local_user()) {
334 $profile_contact = Contact::getById(Contact::getIdForURL($profile['nurl'], local_user()));
336 if (!empty($profile['cid']) && self::getMyURL()) {
337 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
341 if (empty($profile['nickname'])) {
342 Logger::warning('Received profile with no nickname', ['profile' => $profile, 'callstack' => System::callstack(10)]);
346 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
348 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
349 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
351 $profile['network_link'] = '';
354 Hook::callAll('profile_sidebar_enter', $profile);
356 if (isset($profile['url'])) {
357 $profile_url = $profile['url'];
359 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
363 $unfollow_link = null;
364 $subscribe_feed_link = null;
365 $wallmessage_link = null;
367 // Who is the logged-in user to this profile?
368 $visitor_contact = [];
369 if (!empty($profile['uid']) && self::getMyURL()) {
370 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
373 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
374 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
375 $local_user_is_self = self::getMyURL() && ($profile['url'] == self::getMyURL());
376 $visitor_is_authenticated = (bool)self::getMyURL();
377 $visitor_is_following =
378 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
379 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
380 $visitor_is_followed =
381 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
382 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
383 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
385 if (!$local_user_is_self && $show_connect) {
386 if (!$visitor_is_authenticated) {
387 // Remote follow is only available for local profiles
388 if (!empty($profile['nickname']) && strpos($profile_url, DI::baseUrl()->get()) === 0) {
389 $follow_link = 'remote_follow/' . $profile['nickname'];
391 } elseif ($profile_is_native) {
392 if ($visitor_is_following) {
393 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url) . '&auto=1';
395 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url) . '&auto=1';
399 if ($profile_is_dfrn) {
400 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
403 if (Contact::canReceivePrivateMessages($profile_contact)) {
404 if ($visitor_is_followed || $visitor_is_following) {
405 $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
406 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
407 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
412 // show edit profile to yourself, but only if this is not meant to be
413 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
415 if (!isset($profile['self']) && $local_user_is_self) {
416 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
418 'chg_photo' => DI::l10n()->t('Change profile photo'),
424 // Fetch the account type
425 $account_type = Contact::getAccountType($profile);
427 if (!empty($profile['address']) || !empty($profile['location'])) {
428 $location = DI::l10n()->t('Location:');
431 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
432 $about = !empty($profile['about']) ? DI::l10n()->t('About:') : false;
433 $xmpp = !empty($profile['xmpp']) ? DI::l10n()->t('XMPP:') : false;
435 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
436 $location = $homepage = $about = false;
439 $split_name = Diaspora::splitName($profile['name']);
440 $firstname = $split_name['first'];
441 $lastname = $split_name['last'];
443 if (!empty($profile['guid'])) {
445 'guid' => $profile['guid'],
446 'podloc' => DI::baseUrl(),
447 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
448 'nickname' => $profile['nickname'],
449 'fullname' => $profile['name'],
450 'firstname' => $firstname,
451 'lastname' => $lastname,
452 'photo300' => $profile['photo'] ?? '',
453 'photo100' => $profile['thumb'] ?? '',
454 'photo50' => $profile['micro'] ?? '',
464 if (!empty($profile['last-item'])) {
465 $updated = date('c', strtotime($profile['last-item']));
469 $contact_block = ContactBlock::getHTML($a->profile);
471 if (is_array($a->profile) && !$a->profile['hide-friends']) {
472 $contact_count = DBA::count('contact', [
473 'uid' => $profile['uid'],
480 'network' => Protocol::FEDERATED,
485 // Expected profile/vcard.tpl profile.* template variables
491 foreach ($profile as $k => $v) {
492 $k = str_replace('-', '_', $k);
496 if (isset($p['about'])) {
497 $p['about'] = BBCode::convert($p['about']);
500 if (isset($p['address'])) {
501 $p['address'] = BBCode::convert($p['address']);
504 if (isset($p['photo'])) {
505 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
508 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
510 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
511 $o .= Renderer::replaceMacros($tpl, [
514 '$follow' => DI::l10n()->t('Follow'),
515 '$follow_link' => $follow_link,
516 '$unfollow' => DI::l10n()->t('Unfollow'),
517 '$unfollow_link' => $unfollow_link,
518 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
519 '$subscribe_feed_link' => $subscribe_feed_link,
520 '$wallmessage' => DI::l10n()->t('Message'),
521 '$wallmessage_link' => $wallmessage_link,
522 '$account_type' => $account_type,
523 '$location' => $location,
524 '$homepage' => $homepage,
526 '$network' => DI::l10n()->t('Network:'),
527 '$contacts' => $contact_count,
528 '$updated' => $updated,
529 '$diaspora' => $diaspora,
530 '$contact_block' => $contact_block,
533 $arr = ['profile' => &$profile, 'entry' => &$o];
535 Hook::callAll('profile_sidebar', $arr);
540 public static function getBirthdays()
545 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
550 * $mobile_detect = new Mobile_Detect();
551 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
556 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
557 $bd_short = DI::l10n()->t('F d');
559 $cachekey = 'get_birthdays:' . local_user();
560 $r = DI::cache()->get($cachekey);
563 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
565 ON `contact`.`id` = `event`.`cid`
566 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
567 AND NOT `contact`.`pending`
568 AND NOT `contact`.`hidden`
569 AND NOT `contact`.`blocked`
570 AND NOT `contact`.`archive`
571 AND NOT `contact`.`deleted`
572 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
573 ORDER BY `start` ASC ",
577 DateTimeFormat::utc('now + 6 days'),
578 DateTimeFormat::utcNow()
580 if (DBA::isResult($s)) {
581 $r = DBA::toArray($s);
582 DI::cache()->set($cachekey, $r, Duration::HOUR);
588 if (DBA::isResult($r)) {
589 $now = strtotime('now');
593 foreach ($r as $rr) {
594 if (strlen($rr['name'])) {
597 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
601 $classtoday = $istoday ? ' birthday-today ' : '';
603 foreach ($r as &$rr) {
604 if (!strlen($rr['name'])) {
610 if (in_array($rr['cid'], $cids)) {
613 $cids[] = $rr['cid'];
615 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
617 $rr['link'] = Contact::magicLinkById($rr['cid']);
618 $rr['title'] = $rr['name'];
619 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
620 $rr['startime'] = null;
621 $rr['today'] = $today;
625 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
626 return Renderer::replaceMacros($tpl, [
627 '$classtoday' => $classtoday,
629 '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
630 '$event_title' => DI::l10n()->t('Birthdays this week:'),
632 '$lbr' => '{', // raw brackets mess up if/endif macro processing
637 public static function getEventsReminderHTML()
642 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
647 * $mobile_detect = new Mobile_Detect();
648 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
653 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
656 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
657 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
658 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
662 if (DBA::isResult($s)) {
666 while ($rr = DBA::fetch($s)) {
667 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
668 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
669 'visible' => true, 'deleted' => false];
670 if (!Post::exists($condition)) {
674 if (strlen($rr['summary'])) {
678 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
679 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
683 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
685 if (strlen($title) > 35) {
686 $title = substr($title, 0, 32) . '... ';
689 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
691 $description = DI::l10n()->t('[No description]');
694 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
696 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
700 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
702 $rr['title'] = $title;
703 $rr['description'] = $description;
704 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
705 $rr['startime'] = $strt;
706 $rr['today'] = $today;
711 $classtoday = (($istoday) ? 'event-today' : '');
713 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
714 return Renderer::replaceMacros($tpl, [
715 '$classtoday' => $classtoday,
716 '$count' => count($r),
717 '$event_reminders' => DI::l10n()->t('Event Reminders'),
718 '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
724 * Retrieves the my_url session variable
728 public static function getMyURL()
730 return Session::get('my_url');
734 * Process the 'zrl' parameter and initiate the remote authentication.
736 * This method checks if the visitor has a public contact entry and
737 * redirects the visitor to his/her instance to start the magic auth (Authentication)
740 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
742 * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
743 * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
744 * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
746 * It would be favourable to harmonize the two implementations.
748 * @param App $a Application instance.
749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 * @throws \ImagickException
752 public static function zrlInit(App $a)
754 $my_url = self::getMyURL();
755 $my_url = Network::isUrlValid($my_url);
757 if (empty($my_url) || local_user()) {
761 $addr = $_GET['addr'] ?? $my_url;
763 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
764 Hook::callAll('zrl_init', $arr);
766 // Try to find the public contact entry of the visitor.
767 $cid = Contact::getIdForURL($my_url);
769 Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
773 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
775 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
776 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
780 // Avoid endless loops
781 $cachekey = 'zrlInit:' . $my_url;
782 if (DI::cache()->get($cachekey)) {
783 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
786 DI::cache()->set($cachekey, true, Duration::MINUTE);
789 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
791 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
792 $addr_request = 'addr=' . urlencode($addr);
793 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
795 // The other instance needs to know where to redirect.
796 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
798 // We need to extract the basebath from the profile url
799 // to redirect the visitors '/magic' module.
800 $basepath = Contact::getBasepath($contact['url']);
802 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
803 $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
805 // We have to check if the remote server does understand /magic without invoking something
806 $serverret = DI::httpRequest()->get($basepath . '/magic');
807 if ($serverret->isSuccess()) {
808 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
809 System::externalRedirect($magic_path);
815 * Set the visitor cookies (see remote_user()) for the given handle
817 * @param string $handle Visitor handle
818 * @return array Visitor contact array
820 public static function addVisitorCookieForHandle($handle)
824 // Try to find the public contact entry of the visitor.
825 $cid = Contact::getIdForURL($handle);
827 Logger::log('unable to finger ' . $handle, Logger::DEBUG);
831 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
833 // Authenticate the visitor.
834 $_SESSION['authenticated'] = 1;
835 $_SESSION['visitor_id'] = $visitor['id'];
836 $_SESSION['visitor_handle'] = $visitor['addr'];
837 $_SESSION['visitor_home'] = $visitor['url'];
838 $_SESSION['my_url'] = $visitor['url'];
839 $_SESSION['remote_comment'] = $visitor['subscribe'];
841 Session::setVisitorsContacts();
843 $a->contact = $visitor;
845 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
851 * OpenWebAuth authentication.
853 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
855 * @param string $token
856 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
857 * @throws \ImagickException
859 public static function openWebAuthInit($token)
863 // Clean old OpenWebAuthToken entries.
864 OpenWebAuthToken::purge('owt', '3 MINUTE');
866 // Check if the token we got is the same one
867 // we have stored in the database.
868 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
870 if ($visitor_handle === false) {
874 $visitor = self::addVisitorCookieForHandle($visitor_handle);
875 if (empty($visitor)) {
880 'visitor' => $visitor,
881 'url' => DI::args()->getQueryString()
884 * @hooks magic_auth_success
885 * Called when a magic-auth was successful.
886 * * \e array \b visitor
889 Hook::callAll('magic_auth_success', $arr);
891 $a->contact = $arr['visitor'];
893 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
895 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
898 public static function zrl($s, $force = false)
903 if (!strpos($s, '/profile/') && !$force) {
906 if ($force && substr($s, -1, 1) !== '/') {
909 $achar = strpos($s, '?') ? '&' : '?';
910 $mine = self::getMyURL();
911 if ($mine && !Strings::compareLink($mine, $s)) {
912 return $s . $achar . 'zrl=' . urlencode($mine);
918 * Get the user ID of the page owner.
920 * Used from within PCSS themes to set theme parameters. If there's a
921 * profile_uid variable set in App, that is the "page owner" and normally their theme
922 * settings take precedence; unless a local user sets the "always_my_theme"
923 * system pconfig, which means they don't want to see anybody else's theme
924 * settings except their own while on this site.
926 * @return int user ID
928 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
931 public static function getThemeUid(App $a)
933 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
934 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
942 * search for Profiles
946 * @param null $search
948 * @return array [ 'total' => 123, 'entries' => [...] ];
952 public static function searchProfiles($start = 0, $count = 100, $search = null)
954 if (!empty($search)) {
955 $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
956 $searchTerm = '%' . $search . '%';
957 $condition = ["NOT `blocked` AND NOT `account_removed`
959 AND ((`name` LIKE ?) OR
960 (`nickname` LIKE ?) OR
962 (`locality` LIKE ?) OR
964 (`country-name` LIKE ?) OR
965 (`pub_keywords` LIKE ?) OR
966 (`prv_keywords` LIKE ?))",
967 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
968 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
970 $condition = ['blocked' => false, 'account_removed' => false];
971 if (!DI::config()->get('system', 'publish_all')) {
972 $condition['publish'] = true;
976 $total = DBA::count('owner-view', $condition);
978 // If nothing found, don't try to select details
980 $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
985 return ['total' => $total, 'entries' => $profiles];