]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Profile.php
Funkwhale context file moved
[friendica.git] / src / Model / Profile.php
index d81ecc239ec1ae63f04064abd634936277f61402..d27faaf5cd7d08fcfad4ae655f12a845277dcab1 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2021, the Friendica project
+ * @copyright Copyright (C) 2010-2022, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -24,7 +24,7 @@ namespace Friendica\Model;
 use Friendica\App;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Widget\ContactBlock;
-use Friendica\Core\Cache\Duration;
+use Friendica\Core\Cache\Enum\Duration;
 use Friendica\Core\Hook;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
@@ -35,12 +35,16 @@ use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\DI;
+use Friendica\Network\HTTPClient\Client\HttpClientAccept;
+use Friendica\Network\HTTPClient\Client\HttpClientOptions;
+use Friendica\Network\HTTPException;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\Diaspora;
+use Friendica\Security\PermissionSet\Entity\PermissionSet;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\HTTPSignature;
 use Friendica\Util\Network;
-use Friendica\Util\Proxy as ProxyUtils;
+use Friendica\Util\Proxy;
 use Friendica\Util\Strings;
 
 class Profile
@@ -50,10 +54,10 @@ class Profile
         *
         * @param integer User ID
         *
-        * @return array Profile data
+        * @return array|bool Profile data or false on error
         * @throws \Exception
         */
-       public static function getByUID($uid)
+       public static function getByUID(int $uid)
        {
                return DBA::selectFirst('profile', [], ['uid' => $uid]);
        }
@@ -65,7 +69,7 @@ class Profile
         * @param int $id The contact owner ID
         * @param array $fields The selected fields
         *
-        * @return array Profile data for the ID
+        * @return array|bool Profile data for the ID or false on error
         * @throws \Exception
         */
        public static function getById(int $uid, int $id, array $fields = [])
@@ -77,7 +81,7 @@ class Profile
         * Returns profile data for the contact owner
         *
         * @param int $uid The User ID
-        * @param array $fields The fields to retrieve
+        * @param array|bool $fields The fields to retrieve or false on error
         *
         * @return array Array of profile data
         * @throws \Exception
@@ -90,9 +94,9 @@ class Profile
        /**
         * Update a profile entry and distribute the changes if needed
         *
-        * @param array $fields
-        * @param integer $uid
-        * @return boolean
+        * @param array $fields Profile fields to update
+        * @param integer $uid User id
+        * @return boolean Whether update was successful
         */
        public static function update(array $fields, int $uid): bool
        {
@@ -132,8 +136,10 @@ class Profile
 
        /**
         * Publish a changed profile
-        * @param int  $uid
+        *
+        * @param int  $uid User id
         * @param bool $force Force publishing to the directory
+        * @return void
         */
        public static function publishUpdate(int $uid, bool $force = false)
        {
@@ -156,10 +162,9 @@ class Profile
         * Returns a formatted location string from the given profile array
         *
         * @param array $profile Profile array (Generated from the "profile" table)
-        *
         * @return string Location string
         */
-       public static function formatLocation(array $profile)
+       public static function formatLocation(array $profile): string
        {
                $location = '';
 
@@ -204,28 +209,36 @@ class Profile
         *      the theme is chosen before the _init() function of a theme is run, which will usually
         *      load a lot of theme-specific content
         *
-        * @param App     $a
-        * @param string  $nickname string
-        *
+        * @param App    $a
+        * @param string $nickname string
+        * @param bool   $show_contacts
         * @return array Profile
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        *
+        * @throws HTTPException\NotFoundException
+        * @throws HTTPException\InternalServerErrorException
         * @throws \ImagickException
         */
        public static function load(App $a, string $nickname, bool $show_contacts = true)
        {
                $profile = User::getOwnerDataByNick($nickname);
-               if (empty($profile)) {
-                       Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
+               if (!isset($profile['account_removed']) || $profile['account_removed']) {
+                       Logger::info('profile error: ' . DI::args()->getQueryString());
                        return [];
                }
 
-               $a->profile_owner = $profile['uid'];
+               // System user, aborting
+               if ($profile['uid'] === 0) {
+                       DI::logger()->warning('System user found in Profile::load', ['nickname' => $nickname, 'callstack' => System::callstack(20)]);
+                       throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
+               }
+
+               $a->setProfileOwner($profile['uid']);
 
                DI::page()['title'] = $profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
 
-               if (!DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
+               if (!local_user()) {
                        $a->setCurrentTheme($profile['theme']);
-                       $a->setCurrentMobileTheme(DI::pConfig()->get($a->profile_owner, 'system', 'mobile_theme'));
+                       $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme') ?? '');
                }
 
                /*
@@ -246,7 +259,7 @@ class Profile
                 * By now, the contact block isn't shown, when a different profile is given
                 * But: When this profile was on the same server, then we could display the contacts
                 */
-               DI::page()['aside'] .= self::sidebar($profile, $block, $show_contacts);
+               DI::page()['aside'] .= self::getVCardHtml($profile, $block, $show_contacts);
 
                return $profile;
        }
@@ -272,7 +285,7 @@ class Profile
         * @hooks 'profile_sidebar'
         *      array $arr
         */
-       private static function sidebar(array $profile, bool $block, bool $show_contacts)
+       public static function getVCardHtml(array $profile, bool $block, bool $show_contacts)
        {
                $o = '';
                $location = false;
@@ -352,7 +365,7 @@ class Profile
                }
 
                // Fetch the account type
-               $account_type = Contact::getAccountType($profile);
+               $account_type = Contact::getAccountType($profile['account-type']);
 
                if (!empty($profile['address']) || !empty($profile['location'])) {
                        $location = DI::l10n()->t('Location:');
@@ -361,6 +374,7 @@ class Profile
                $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
                $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
                $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
+               $matrix   = !empty($profile['matrix'])   ? DI::l10n()->t('Matrix:')   : false;
 
                if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
                        $location = $homepage = $about = false;
@@ -396,7 +410,7 @@ class Profile
                }
 
                if (!$block && $show_contacts) {
-                       $contact_block = ContactBlock::getHTML($profile);
+                       $contact_block = ContactBlock::getHTML($profile, local_user());
 
                        if (is_array($profile) && !$profile['hide-friends']) {
                                $contact_count = DBA::count('contact', [
@@ -431,7 +445,7 @@ class Profile
                        $p['address'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['address']);
                }
 
-               $p['photo'] = Contact::getAvatarUrlForId($cid, ProxyUtils::SIZE_SMALL);
+               $p['photo'] = Contact::getAvatarUrlForId($cid, Proxy::SIZE_SMALL);
 
                $p['url'] = Contact::magicLinkById($cid, $profile['url']);
 
@@ -439,6 +453,7 @@ class Profile
                $o .= Renderer::replaceMacros($tpl, [
                        '$profile' => $p,
                        '$xmpp' => $xmpp,
+                       '$matrix' => $matrix,
                        '$follow' => DI::l10n()->t('Follow'),
                        '$follow_link' => $follow_link,
                        '$unfollow' => DI::l10n()->t('Unfollow'),
@@ -465,13 +480,19 @@ class Profile
                return $o;
        }
 
-       public static function getBirthdays()
+       /**
+        * Returns the upcoming birthdays of contacts of the current user as HTML content
+        *
+        * @return string The upcoming birthdays (HTML)
+        *
+        * @throws HTTPException\InternalServerErrorException
+        * @throws HTTPException\ServiceUnavailableException
+        * @throws \ImagickException
+        */
+       public static function getBirthdays(): string
        {
-               $a = DI::app();
-               $o = '';
-
                if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
-                       return $o;
+                       return '';
                }
 
                /*
@@ -481,13 +502,12 @@ class Profile
                *                       return $o;
                */
 
-               $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
                $bd_short = DI::l10n()->t('F d');
 
-               $cachekey = 'get_birthdays:' . local_user();
-               $r = DI::cache()->get($cachekey);
-               if (is_null($r)) {
-                       $s = DBA::p(
+               $cacheKey = 'get_birthdays:' . local_user();
+               $events   = DI::cache()->get($cacheKey);
+               if (is_null($events)) {
+                       $result = DBA::p(
                                "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
                                INNER JOIN `contact`
                                        ON `contact`.`id` = `event`.`cid`
@@ -498,67 +518,68 @@ class Profile
                                        AND NOT `contact`.`archive`
                                        AND NOT `contact`.`deleted`
                                WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
-                               ORDER BY `start` ASC ",
+                               ORDER BY `start`",
                                Contact::SHARING,
                                Contact::FRIEND,
                                local_user(),
                                DateTimeFormat::utc('now + 6 days'),
                                DateTimeFormat::utcNow()
                        );
-                       if (DBA::isResult($s)) {
-                               $r = DBA::toArray($s);
-                               DI::cache()->set($cachekey, $r, Duration::HOUR);
+                       if (DBA::isResult($result)) {
+                               $events = DBA::toArray($result);
+                               DI::cache()->set($cacheKey, $events, Duration::HOUR);
                        }
                }
 
-               $total = 0;
-               $classtoday = '';
-               if (DBA::isResult($r)) {
-                       $now = strtotime('now');
+               $total      = 0;
+               $classToday = '';
+               $tpl_events = [];
+               if (DBA::isResult($events)) {
+                       $now  = strtotime('now');
                        $cids = [];
 
-                       $istoday = false;
-                       foreach ($r as $rr) {
-                               if (strlen($rr['name'])) {
-                                       $total ++;
+                       $isToday = false;
+                       foreach ($events as $event) {
+                               if (strlen($event['name'])) {
+                                       $total++;
                                }
-                               if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
-                                       $istoday = true;
+                               if ((strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now)) {
+                                       $isToday = true;
                                }
                        }
-                       $classtoday = $istoday ? ' birthday-today ' : '';
+                       $classToday = $isToday ? ' birthday-today ' : '';
                        if ($total) {
-                               foreach ($r as &$rr) {
-                                       if (!strlen($rr['name'])) {
+                               foreach ($events as $event) {
+                                       if (!strlen($event['name'])) {
                                                continue;
                                        }
 
                                        // avoid duplicates
-
-                                       if (in_array($rr['cid'], $cids)) {
+                                       if (in_array($event['cid'], $cids)) {
                                                continue;
                                        }
-                                       $cids[] = $rr['cid'];
+                                       $cids[] = $event['cid'];
 
-                                       $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
+                                       $today = (strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now);
 
-                                       $rr['link'] = Contact::magicLinkById($rr['cid']);
-                                       $rr['title'] = $rr['name'];
-                                       $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
-                                       $rr['startime'] = null;
-                                       $rr['today'] = $today;
+                                       $tpl_events[] = [
+                                               'id'    => $event['id'],
+                                               'link'  => Contact::magicLinkById($event['cid']),
+                                               'title' => $event['name'],
+                                               'date'  => DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '')
+                                       ];
                                }
                        }
                }
                $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
                return Renderer::replaceMacros($tpl, [
-                       '$classtoday' => $classtoday,
-                       '$count' => $total,
+                       '$classtoday'      => $classToday,
+                       '$count'           => $total,
                        '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
-                       '$event_title' => DI::l10n()->t('Birthdays this week:'),
-                       '$events' => $r,
-                       '$lbr' => '{', // raw brackets mess up if/endif macro processing
-                       '$rbr' => '}'
+                       '$event_title'     => DI::l10n()->t('Birthdays this week:'),
+                       '$events'          => $tpl_events,
+                       '$lbr'             => '{', // raw brackets mess up if/endif macro processing
+                       '$rbr'             => '}'
                ]);
        }
 
@@ -603,8 +624,8 @@ class Profile
                                        $total++;
                                }
 
-                               $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
-                               if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
+                               $strt = DateTimeFormat::local($rr['start'], 'Y-m-d');
+                               if ($strt === DateTimeFormat::localNow('Y-m-d')) {
                                        $istoday = true;
                                }
 
@@ -619,17 +640,17 @@ class Profile
                                        $description = DI::l10n()->t('[No description]');
                                }
 
-                               $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
+                               $strt = DateTimeFormat::local($rr['start']);
 
-                               if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
+                               if (substr($strt, 0, 10) < DateTimeFormat::localNow('Y-m-d')) {
                                        continue;
                                }
 
-                               $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
+                               $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d');
 
                                $rr['title'] = $title;
                                $rr['description'] = $description;
-                               $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
+                               $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
                                $rr['startime'] = $strt;
                                $rr['today'] = $today;
 
@@ -694,27 +715,27 @@ class Profile
                // Try to find the public contact entry of the visitor.
                $cid = Contact::getIdForURL($my_url);
                if (!$cid) {
-                       Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
+                       Logger::info('No contact record found for ' . $my_url);
                        return;
                }
 
                $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
 
                if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
-                       Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
+                       Logger::info('The visitor ' . $my_url . ' is already authenticated');
                        return;
                }
 
                // Avoid endless loops
                $cachekey = 'zrlInit:' . $my_url;
                if (DI::cache()->get($cachekey)) {
-                       Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
+                       Logger::info('URL ' . $my_url . ' already tried to authenticate.');
                        return;
                } else {
                        DI::cache()->set($cachekey, true, Duration::MINUTE);
                }
 
-               Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
+               Logger::info('Not authenticated. Invoking reverse magic-auth for ' . $my_url);
 
                // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
                $addr_request = 'addr=' . urlencode($addr);
@@ -731,9 +752,9 @@ class Profile
                        $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
 
                        // We have to check if the remote server does understand /magic without invoking something
-                       $serverret = DI::httpRequest()->get($basepath . '/magic');
+                       $serverret = DI::httpClient()->head($basepath . '/magic', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::HTML]);
                        if ($serverret->isSuccess()) {
-                               Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
+                               Logger::info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path);
                                System::externalRedirect($magic_path);
                        }
                }
@@ -768,7 +789,7 @@ class Profile
 
                Session::setVisitorsContacts();
 
-               $a->contact = $visitor;
+               $a->setContactId($visitor['id']);
 
                Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
 
@@ -829,11 +850,11 @@ class Profile
                 */
                Hook::callAll('magic_auth_success', $arr);
 
-               $a->contact = $arr['visitor'];
+               $a->setContactId($arr['visitor']['id']);
 
                info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
 
-               Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
+               Logger::info('OpenWebAuth: auth success from ' . $visitor['addr']);
        }
 
        public static function zrl($s, $force = false)
@@ -860,23 +881,17 @@ class Profile
         *
         * Used from within PCSS themes to set theme parameters. If there's a
         * profile_uid variable set in App, that is the "page owner" and normally their theme
-        * settings take precedence; unless a local user sets the "always_my_theme"
-        * system pconfig, which means they don't want to see anybody else's theme
-        * settings except their own while on this site.
+        * settings take precedence; unless a local user is logged in which means they don't
+        * want to see anybody else's theme settings except their own while on this site.
         *
+        * @param App $a
         * @return int user ID
         *
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         * @note Returns local_user instead of user ID if "always_my_theme" is set to true
         */
-       public static function getThemeUid(App $a)
+       public static function getThemeUid(App $a): int
        {
-               $uid = !empty($a->profile_owner) ? intval($a->profile_owner) : 0;
-               if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
-                       return local_user();
-               }
-
-               return $uid;
+               return local_user() ?: $a->getProfileOwner();
        }
 
        /**
@@ -925,4 +940,86 @@ class Profile
 
                return ['total' => $total, 'entries' => $profiles];
        }
+
+       /**
+        * Migrates a legacy profile to the new slimmer profile with extra custom fields.
+        * Multi profiles are converted to ACl-protected custom fields and deleted.
+        *
+        * @param array $profile One profile array
+        * @throws \Exception
+        */
+       public static function migrate(array $profile)
+       {
+               // Already processed, aborting
+               if ($profile['is-default'] === null) {
+                       return;
+               }
+
+               $contacts = [];
+
+               if (!$profile['is-default']) {
+                       $contacts = Contact::selectToArray(['id'], [
+                               'uid'        => $profile['uid'],
+                               'profile-id' => $profile['id']
+                       ]);
+                       if (!count($contacts)) {
+                               // No contact visibility selected defaults to user-only permission
+                               $contacts = Contact::selectToArray(['id'], ['uid' => $profile['uid'], 'self' => true]);
+                       }
+               }
+
+               $permissionSet = DI::permissionSet()->selectOrCreate(
+                       new PermissionSet(
+                               $profile['uid'],
+                               array_column($contacts, 'id') ?? []
+                       )
+               );
+
+               $order = 1;
+
+               $custom_fields = [
+                       'hometown'  => DI::l10n()->t('Hometown:'),
+                       'marital'   => DI::l10n()->t('Marital Status:'),
+                       'with'      => DI::l10n()->t('With:'),
+                       'howlong'   => DI::l10n()->t('Since:'),
+                       'sexual'    => DI::l10n()->t('Sexual Preference:'),
+                       'politic'   => DI::l10n()->t('Political Views:'),
+                       'religion'  => DI::l10n()->t('Religious Views:'),
+                       'likes'     => DI::l10n()->t('Likes:'),
+                       'dislikes'  => DI::l10n()->t('Dislikes:'),
+                       'pdesc'     => DI::l10n()->t('Title/Description:'),
+                       'summary'   => DI::l10n()->t('Summary'),
+                       'music'     => DI::l10n()->t('Musical interests'),
+                       'book'      => DI::l10n()->t('Books, literature'),
+                       'tv'        => DI::l10n()->t('Television'),
+                       'film'      => DI::l10n()->t('Film/dance/culture/entertainment'),
+                       'interest'  => DI::l10n()->t('Hobbies/Interests'),
+                       'romance'   => DI::l10n()->t('Love/romance'),
+                       'work'      => DI::l10n()->t('Work/employment'),
+                       'education' => DI::l10n()->t('School/education'),
+                       'contact'   => DI::l10n()->t('Contact information and Social Networks'),
+               ];
+
+               foreach ($custom_fields as $field => $label) {
+                       if (!empty($profile[$field]) && $profile[$field] > DBA::NULL_DATE && $profile[$field] > DBA::NULL_DATETIME) {
+                               DI::profileField()->save(DI::profileFieldFactory()->createFromValues(
+                                       $profile['uid'],
+                                       $order,
+                                       trim($label, ':'),
+                                       $profile[$field],
+                                       $permissionSet
+                               ));
+                       }
+
+                       $profile[$field] = null;
+               }
+
+               if ($profile['is-default']) {
+                       $profile['profile-name'] = null;
+                       $profile['is-default']   = null;
+                       DBA::update('profile', $profile, ['id' => $profile['id']]);
+               } else if (!empty($profile['id'])) {
+                       DBA::delete('profile', ['id' => $profile['id']]);
+               }
+       }
 }