3 * @file src/Model/Profile.php
5 namespace Friendica\Model;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Content\Widget\ContactBlock;
10 use Friendica\Core\Cache\Duration;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
19 use Friendica\Protocol\Activity;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Proxy as ProxyUtils;
24 use Friendica\Util\Strings;
29 * Returns default profile for a given user id
31 * @param integer User ID
33 * @return array Profile data
36 public static function getByUID($uid)
38 return DBA::selectFirst('profile', [], ['uid' => $uid]);
42 * Returns default profile for a given user ID and ID
44 * @param int $uid The contact ID
45 * @param int $id The contact owner ID
46 * @param array $fields The selected fields
48 * @return array Profile data for the ID
51 public static function getById(int $uid, int $id, array $fields = [])
53 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
57 * Returns profile data for the contact owner
59 * @param int $uid The User ID
60 * @param array $fields The fields to retrieve
62 * @return array Array of profile data
65 public static function getListByUser(int $uid, array $fields = [])
67 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
71 * Returns a formatted location string from the given profile array
73 * @param array $profile Profile array (Generated from the "profile" table)
75 * @return string Location string
77 public static function formatLocation(array $profile)
81 if (!empty($profile['locality'])) {
82 $location .= $profile['locality'];
85 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
90 $location .= $profile['region'];
93 if (!empty($profile['country-name'])) {
98 $location .= $profile['country-name'];
105 * Loads a profile into the page sidebar.
107 * The function requires a writeable copy of the main App structure, and the nickname
108 * of a registered local account.
110 * If the viewer is an authenticated remote viewer, the profile displayed is the
111 * one that has been configured for his/her viewing in the Contact manager.
112 * Passing a non-zero profile ID can also allow a preview of a selected profile
115 * Profile information is placed in the App structure for later retrieval.
116 * Honours the owner's chosen theme for display.
118 * @attention Should only be run in the _init() functions of a module. That ensures that
119 * the theme is chosen before the _init() function of a theme is run, which will usually
120 * load a lot of theme-specific content
123 * @param string $nickname string
124 * @param array $profiledata array
125 * @param boolean $show_connect Show connect link
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127 * @throws \ImagickException
129 public static function load(App $a, $nickname, array $profiledata = [], $show_connect = true)
131 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
133 if (!DBA::isResult($user) && empty($profiledata)) {
134 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
138 if (count($profiledata) > 0) {
139 // Ensure to have a "nickname" field
140 if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
141 $profiledata['nickname'] = $profiledata['nick'];
144 // Add profile data to sidebar
145 DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
147 if (!DBA::isResult($user)) {
152 $profile = self::getByNickname($nickname, $user['uid']);
154 if (empty($profile) && empty($profiledata)) {
155 Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
159 if (empty($profile)) {
160 $profile = ['uid' => 0, 'name' => $nickname];
163 $a->profile = $profile;
164 $a->profile_uid = $profile['uid'];
166 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['uid'], 'system', 'mobile_theme');
167 $a->profile['network'] = Protocol::DFRN;
169 DI::page()['title'] = $a->profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
171 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
172 $a->setCurrentTheme($a->profile['theme']);
173 $a->setCurrentMobileTheme($a->profile['mobile-theme']);
177 * load/reload current theme info
180 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
182 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
183 if (file_exists($theme_info_file)) {
184 require_once $theme_info_file;
187 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
188 DI::page()['aside'] .= Renderer::replaceMacros(
189 Renderer::getMarkupTemplate('settings/profile/link.tpl'),
191 '$editprofile' => DI::l10n()->t('Edit profile'),
192 '$profid' => $a->profile['id']
197 $block = ((DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
201 * By now, the contact block isn't shown, when a different profile is given
202 * But: When this profile was on the same server, then we could display the contacts
205 DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
212 * Get all profile data of a local user
214 * If the viewer is an authenticated remote viewer, the profile displayed is the
215 * one that has been configured for his/her viewing in the Contact manager.
216 * Passing a non-zero profile ID can also allow a preview of a selected profile
219 * Includes all available profile data
221 * @param string $nickname nick
222 * @param int $uid uid
223 * @param int $profile_id ID of the profile
227 public static function getByNickname($nickname, $uid = 0)
229 $profile = DBA::fetchFirst(
230 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
231 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
233 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
235 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
236 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
237 WHERE `user`.`nickname` = ? AND `profile`.`uid` = ? LIMIT 1",
246 * Formats a profile for display in the sidebar.
248 * It is very difficult to templatise the HTML completely
249 * because of all the conditional logic.
251 * @param array $profile
253 * @param boolean $show_connect Show connect link
255 * @return string HTML sidebar module
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 * @throws \ImagickException
259 * @note Returns empty string if passed $profile is wrong type or not populated
261 * @hooks 'profile_sidebar_enter'
262 * array $profile - profile data
263 * @hooks 'profile_sidebar'
266 private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
271 // This function can also use contact information in $profile
272 $is_contact = !empty($profile['cid']);
274 if (!is_array($profile) && !count($profile)) {
278 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
280 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
281 $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
283 $profile['network_link'] = '';
286 Hook::callAll('profile_sidebar_enter', $profile);
288 if (isset($profile['url'])) {
289 $profile_url = $profile['url'];
291 $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
295 $unfollow_link = null;
296 $subscribe_feed_link = null;
297 $wallmessage_link = null;
301 $visitor_contact = [];
302 if (!empty($profile['uid']) && self::getMyURL()) {
303 $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
306 $profile_contact = [];
307 if (!empty($profile['cid']) && self::getMyURL()) {
308 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
311 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
312 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
313 $local_user_is_self = local_user() && local_user() == ($profile['uid'] ?? 0);
314 $visitor_is_authenticated = (bool)self::getMyURL();
315 $visitor_is_following =
316 in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
317 || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
318 $visitor_is_followed =
319 in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
320 || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
321 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
323 if (!$local_user_is_self && $show_connect) {
324 if (!$visitor_is_authenticated) {
325 if (!empty($profile['nickname'])) {
326 $follow_link = 'dfrn_request/' . $profile['nickname'];
328 } elseif ($profile_is_native) {
329 if ($visitor_is_following) {
330 $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
332 $follow_link = $visitor_base_path .'/follow?url=' . urlencode($profile_url);
336 if ($profile_is_dfrn) {
337 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
340 if (Contact::canReceivePrivateMessages($profile)) {
341 if ($visitor_is_followed || $visitor_is_following) {
342 $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
343 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
344 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
349 // show edit profile to yourself
350 if (!$is_contact && $local_user_is_self) {
351 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
353 'chg_photo' => DI::l10n()->t('Change profile photo'),
359 // Fetch the account type
360 $account_type = Contact::getAccountType($profile);
362 if (!empty($profile['address'])
363 || !empty($profile['location'])
364 || !empty($profile['locality'])
365 || !empty($profile['region'])
366 || !empty($profile['postal-code'])
367 || !empty($profile['country-name'])
369 $location = DI::l10n()->t('Location:');
372 $gender = !empty($profile['gender']) ? DI::l10n()->t('Gender:') : false;
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;
377 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
378 $location = $gender = $marital = $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['publish'] && $profile['net-publish']) ? 'true' : 'false'),
390 'nickname' => $profile['nickname'],
391 'fullname' => $profile['name'],
392 'firstname' => $firstname,
393 'lastname' => $lastname,
394 'photo300' => $profile['contact_photo'] ?? '',
395 'photo100' => $profile['contact_thumb'] ?? '',
396 'photo50' => $profile['contact_micro'] ?? '',
406 $contact_block = ContactBlock::getHTML($a->profile);
408 if (is_array($a->profile) && !$a->profile['hide-friends']) {
410 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
411 intval($a->profile['uid'])
413 if (DBA::isResult($r)) {
414 $updated = date('c', strtotime($r[0]['updated']));
417 $contact_count = DBA::count('contact', [
418 'uid' => $profile['uid'],
424 'network' => Protocol::FEDERATED,
430 foreach ($profile as $k => $v) {
431 $k = str_replace('-', '_', $k);
435 if (isset($p['about'])) {
436 $p['about'] = BBCode::convert($p['about']);
439 if (empty($p['address']) && !empty($p['location'])) {
440 $p['address'] = $p['location'];
443 if (isset($p['address'])) {
444 $p['address'] = BBCode::convert($p['address']);
447 if (isset($p['gender'])) {
448 $p['gender'] = DI::l10n()->t($p['gender']);
451 if (isset($p['photo'])) {
452 $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
455 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
457 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
458 $o .= Renderer::replaceMacros($tpl, [
461 '$follow' => DI::l10n()->t('Follow'),
462 '$follow_link' => $follow_link,
463 '$unfollow' => DI::l10n()->t('Unfollow'),
464 '$unfollow_link' => $unfollow_link,
465 '$subscribe_feed' => DI::l10n()->t('Atom feed'),
466 '$subscribe_feed_link' => $subscribe_feed_link,
467 '$wallmessage' => DI::l10n()->t('Message'),
468 '$wallmessage_link' => $wallmessage_link,
469 '$account_type' => $account_type,
470 '$location' => $location,
471 '$gender' => $gender,
472 '$homepage' => $homepage,
474 '$network' => DI::l10n()->t('Network:'),
475 '$contacts' => $contact_count,
476 '$updated' => $updated,
477 '$diaspora' => $diaspora,
478 '$contact_block' => $contact_block,
481 $arr = ['profile' => &$profile, 'entry' => &$o];
483 Hook::callAll('profile_sidebar', $arr);
488 public static function getBirthdays()
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_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
505 $bd_short = DI::l10n()->t('F d');
507 $cachekey = 'get_birthdays:' . local_user();
508 $r = DI::cache()->get($cachekey);
511 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
513 ON `contact`.`id` = `event`.`cid`
514 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
515 AND NOT `contact`.`pending`
516 AND NOT `contact`.`hidden`
517 AND NOT `contact`.`blocked`
518 AND NOT `contact`.`archive`
519 AND NOT `contact`.`deleted`
520 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
521 ORDER BY `start` ASC ",
525 DateTimeFormat::utc('now + 6 days'),
526 DateTimeFormat::utcNow()
528 if (DBA::isResult($s)) {
529 $r = DBA::toArray($s);
530 DI::cache()->set($cachekey, $r, Duration::HOUR);
536 if (DBA::isResult($r)) {
537 $now = strtotime('now');
541 foreach ($r as $rr) {
542 if (strlen($rr['name'])) {
545 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
549 $classtoday = $istoday ? ' birthday-today ' : '';
551 foreach ($r as &$rr) {
552 if (!strlen($rr['name'])) {
558 if (in_array($rr['cid'], $cids)) {
561 $cids[] = $rr['cid'];
563 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
565 $rr['link'] = Contact::magicLink($rr['url']);
566 $rr['title'] = $rr['name'];
567 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
568 $rr['startime'] = null;
569 $rr['today'] = $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:'),
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 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
617 'visible' => true, 'deleted' => false];
618 if (!Item::exists($condition)) {
622 if (strlen($rr['summary'])) {
626 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
627 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
631 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
633 if (strlen($title) > 35) {
634 $title = substr($title, 0, 32) . '... ';
637 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
639 $description = DI::l10n()->t('[No description]');
642 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
644 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
648 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
650 $rr['title'] = $title;
651 $rr['description'] = $description;
652 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $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::log('No contact record found for ' . $my_url, Logger::DEBUG);
721 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
723 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
724 Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
728 // Avoid endless loops
729 $cachekey = 'zrlInit:' . $my_url;
730 if (DI::cache()->get($cachekey)) {
731 Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
734 DI::cache()->set($cachekey, true, Duration::MINUTE);
737 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
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 = Network::curl($basepath . '/magic');
755 if ($serverret->isSuccess()) {
756 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
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::log('unable to finger ' . $handle, Logger::DEBUG);
779 $visitor = DBA::selectFirst('contact', [], ['id' => $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'];
788 Session::setVisitorsContacts();
790 $a->contact = $visitor;
792 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
798 * OpenWebAuth authentication.
800 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
802 * @param string $token
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 * @throws \ImagickException
806 public static function openWebAuthInit($token)
810 // Clean old OpenWebAuthToken entries.
811 OpenWebAuthToken::purge('owt', '3 MINUTE');
813 // Check if the token we got is the same one
814 // we have stored in the database.
815 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
817 if ($visitor_handle === false) {
821 $visitor = self::addVisitorCookieForHandle($visitor_handle);
822 if (empty($visitor)) {
827 'visitor' => $visitor,
828 'url' => DI::args()->getQueryString()
831 * @hooks magic_auth_success
832 * Called when a magic-auth was successful.
833 * * \e array \b visitor
836 Hook::callAll('magic_auth_success', $arr);
838 $a->contact = $arr['visitor'];
840 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
842 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
845 public static function zrl($s, $force = false)
850 if (!strpos($s, '/profile/') && !$force) {
853 if ($force && substr($s, -1, 1) !== '/') {
856 $achar = strpos($s, '?') ? '&' : '?';
857 $mine = self::getMyURL();
858 if ($mine && !Strings::compareLink($mine, $s)) {
859 return $s . $achar . 'zrl=' . urlencode($mine);
865 * Get the user ID of the page owner.
867 * Used from within PCSS themes to set theme parameters. If there's a
868 * profile_uid variable set in App, that is the "page owner" and normally their theme
869 * settings take precedence; unless a local user sets the "always_my_theme"
870 * system pconfig, which means they don't want to see anybody else's theme
871 * settings except their own while on this site.
873 * @return int user ID
875 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
876 * @note Returns local_user instead of user ID if "always_my_theme" is set to true
878 public static function getThemeUid(App $a)
880 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
881 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
889 * search for Profiles
893 * @param null $search
895 * @return array [ 'total' => 123, 'entries' => [...] ];
899 public static function searchProfiles($start = 0, $count = 100, $search = null)
901 $publish = (DI::config()->get('system', 'publish_all') ? '' : "`publish` = 1");
904 if (!empty($search)) {
905 $searchTerm = '%' . $search . '%';
906 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
908 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
909 WHERE $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
910 AND ((`profile`.`name` LIKE ?) OR
911 (`user`.`nickname` LIKE ?) OR
912 (`profile`.`pdesc` LIKE ?) OR
913 (`profile`.`locality` LIKE ?) OR
914 (`profile`.`region` LIKE ?) OR
915 (`profile`.`country-name` LIKE ?) OR
916 (`profile`.`pub_keywords` LIKE ?) OR
917 (`profile`.`prv_keywords` LIKE ?))",
918 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
919 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
921 $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
923 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
924 WHERE $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
927 if (DBA::isResult($cnt)) {
928 $total = $cnt['total'];
931 $order = " ORDER BY `name` ASC ";
934 // If nothing found, don't try to select details
936 if (!empty($search)) {
937 $searchTerm = '%' . $search . '%';
939 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
940 `contact`.`addr`, `contact`.`url` AS `profile_url`
942 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
943 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
944 WHERE $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
945 AND ((`profile`.`name` LIKE ?) OR
946 (`user`.`nickname` LIKE ?) OR
947 (`profile`.`pdesc` LIKE ?) OR
948 (`profile`.`locality` LIKE ?) OR
949 (`profile`.`region` LIKE ?) OR
950 (`profile`.`country-name` LIKE ?) OR
951 (`profile`.`pub_keywords` LIKE ?) OR
952 (`profile`.`prv_keywords` LIKE ?))
954 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
955 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
959 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
960 `contact`.`addr`, `contact`.`url` AS `profile_url`
962 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
963 LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
964 WHERE $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
971 if (DBA::isResult($profiles) && $total > 0) {
974 'entries' => DBA::toArray($profiles),