]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Contact.php
Fix: Images must not be removed on preview
[friendica.git] / src / Model / Contact.php
index a035d0021d9e3b3dece6a38cc499db3c2ea77112..8f9cb4d051c76832e52a4c9641fcf4a09f766ceb 100644 (file)
@@ -29,18 +29,20 @@ use Friendica\Core\Hook;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
 use Friendica\Core\Renderer;
-use Friendica\Core\Session;
 use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\Database;
 use Friendica\Database\DBA;
 use Friendica\DI;
-use Friendica\Module\NoScrape;
+use Friendica\Network\HTTPClient\Client\HttpClientAccept;
+use Friendica\Network\HTTPClient\Client\HttpClientOptions;
 use Friendica\Network\HTTPException;
 use Friendica\Network\Probe;
+use Friendica\Object\Image;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\ActivityPub;
 use Friendica\Util\DateTimeFormat;
+use Friendica\Util\HTTPSignature;
 use Friendica\Util\Images;
 use Friendica\Util\Network;
 use Friendica\Util\Proxy;
@@ -98,17 +100,17 @@ class Contact
         * Relationship types
         * @{
         */
-       const NOTHING  = 0;
-       const FOLLOWER = 1;
-       const SHARING  = 2;
-       const FRIEND   = 3;
-       const SELF     = 4;
+       const NOTHING  = 0; // There is no relationship between the contact and the user
+       const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
+       const SHARING  = 2; // The contact shares their content with this user (the user is the subscriber)
+       const FRIEND   = 3; // There is a mutual relationship between the contact and the user
+       const SELF     = 4; // This is the user theirself
        /**
         * @}
         */
 
         const MIRROR_DEACTIVATED = 0;
-        const MIRROR_FORWARDED = 1;
+        const MIRROR_FORWARDED = 1; // Deprecated, now does the same like MIRROR_OWN_POST
         const MIRROR_OWN_POST = 2;
         const MIRROR_NATIVE_RESHARE = 3;
 
@@ -138,6 +140,30 @@ class Contact
                return $contact;
        }
 
+       /**
+        * @param array $fields    Array of selected fields, empty for all
+        * @param array $condition Array of fields for condition
+        * @param array $params    Array of several parameters
+        * @return array
+        * @throws \Exception
+        */
+       public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
+       {
+               return DBA::selectToArray('account-user-view', $fields, $condition, $params);
+       }
+
+       /**
+        * @param array $fields    Array of selected fields, empty for all
+        * @param array $condition Array of fields for condition
+        * @param array $params    Array of several parameters
+        * @return array|bool
+        * @throws \Exception
+        */
+       public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
+       {
+               return DBA::selectFirst('account-view', $fields, $condition, $params);
+       }
+
        /**
         * Insert a row into the contact table
         * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
@@ -250,6 +276,32 @@ class Contact
                return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
        }
 
+       /**
+        * Fetch all remote contacts for a given contact url
+        *
+        * @param string $url The URL of the contact
+        * @param array  $fields The wanted fields
+        *
+        * @return array all remote contacts
+        *
+        * @throws \Exception
+        */
+       public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
+       {
+               $remote = [];
+
+               $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
+               while ($contact = DBA::fetch($remote_contacts)) {
+                       if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
+                               continue;
+                       }
+                       $remote[$contact['uid']] = $contact['id'];
+               }
+               DBA::close($remote_contacts);
+
+               return $remote;
+       }
+
        /**
         * Fetches a contact by a given url
         *
@@ -308,7 +360,7 @@ class Contact
 
                // Update the contact in the background if needed
                if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
-                       Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+                       Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
                }
 
                // Remove the internal fields
@@ -350,6 +402,18 @@ class Contact
                return $contact;
        }
 
+       /**
+        * Checks if a contact uses a specific platform
+        *
+        * @param string $url
+        * @param string $platform
+        * @return boolean
+        */
+       public static function isPlatform(string $url, string $platform): bool
+       {
+               return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
+       }
+
        /**
         * Tests if the given contact is a follower
         *
@@ -681,7 +745,6 @@ class Contact
                        'notify'      => DI::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
                        'poll'        => DI::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
                        'confirm'     => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
-                       'poco'        => DI::baseUrl() . '/poco/'         . $user['nickname'],
                        'name-date'   => DateTimeFormat::utcNow(),
                        'uri-date'    => DateTimeFormat::utcNow(),
                        'avatar-date' => DateTimeFormat::utcNow(),
@@ -763,7 +826,6 @@ class Contact
                        'notify'       => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
                        'poll'         => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
                        'confirm'      => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
-                       'poco'         => DI::baseUrl() . '/poco/' . $user['nickname'],
                ];
 
 
@@ -854,14 +916,14 @@ class Contact
                self::clearFollowerFollowingEndpointCache($contact['uid']);
 
                // Archive the contact
-               self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
+               self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
 
                if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
                        Avatar::deleteCache($contact);
                }
 
                // Delete it in the background
-               Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
+               Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
        }
 
        /**
@@ -885,7 +947,7 @@ class Contact
                if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
                        $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
                        if (!empty($cdata['public'])) {
-                               Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
+                               Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
                        }
                }
 
@@ -915,7 +977,7 @@ class Contact
                if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
                        $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
                        if (!empty($cdata['public'])) {
-                               Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
+                               Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
                        }
                }
 
@@ -943,11 +1005,11 @@ class Contact
                $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
 
                if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
-                       Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
+                       Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
                }
 
                if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
-                       Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
+                       Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
                }
 
                self::remove($contact['id']);
@@ -1080,7 +1142,7 @@ class Contact
                $photos_link = '';
 
                if ($uid == 0) {
-                       $uid = local_user();
+                       $uid = DI::userSession()->getLocalUserId();
                }
 
                if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
@@ -1101,7 +1163,7 @@ class Contact
                $sparkle = false;
                if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
                        $sparkle = true;
-                       $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
+                       $profile_link = 'contact/redir/' . $contact['id'];
                } else {
                        $profile_link = $contact['url'];
                }
@@ -1112,25 +1174,25 @@ class Contact
 
                if ($sparkle) {
                        $status_link = $profile_link . '/status';
-                       $photos_link = str_replace('/profile/', '/photos/', $profile_link);
+                       $photos_link = $profile_link . '/photos';
                        $profile_link = $profile_link . '/profile';
                }
 
                if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
-                       $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
+                       $pm_url = 'message/new/' . $contact['id'];
                }
 
-               $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
+               $contact_url = 'contact/' . $contact['id'];
 
-               $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
+               $posts_link = 'contact/' . $contact['id'] . '/conversations';
 
                $follow_link = '';
                $unfollow_link = '';
                if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
                        if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
-                               $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
+                               $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
                        } elseif(!$contact['pending']) {
-                               $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
+                               $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
                        }
                }
 
@@ -1144,7 +1206,7 @@ class Contact
                                'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
                                'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
                                'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
-                               'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
+                               'unfollow'=> [DI::l10n()->t('Unfollow')      , $unfollow_link, true],
                        ];
                } else {
                        $menu = [
@@ -1155,7 +1217,7 @@ class Contact
                                'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
                                'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
                                'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
-                               'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
+                               'unfollow'=> [DI::l10n()->t('Unfollow')      , $unfollow_link    , true],
                        ];
 
                        if (!empty($contact['pending'])) {
@@ -1225,7 +1287,7 @@ class Contact
                        $contact_id = $contact['id'];
 
                        if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
-                               Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+                               Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
                        }
 
                        if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
@@ -1311,9 +1373,10 @@ class Contact
                                'writable'  => 1,
                                'blocked'   => 0,
                                'readonly'  => 0,
-                               'pending'   => 0];
+                               'pending'   => 0,
+                       ];
 
-                       $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
+                       $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
 
                        // Before inserting we do check if the entry does exist now.
                        $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
@@ -1336,7 +1399,17 @@ class Contact
                }
 
                if ($data['network'] == Protocol::DIASPORA) {
-                       FContact::updateFromProbeArray($data);
+                       try {
+                               DI::dsprContact()->updateFromProbeArray($data);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::error($e->getMessage(), ['url' => $url, 'data' => $data]);
+                       }
+               } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
+                       try {
+                               DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::error($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
+                       }
                }
 
                self::updateFromProbeArray($contact_id, $data);
@@ -1482,11 +1555,11 @@ class Contact
                $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
 
                if ($thread_mode) {
-                       $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
-                               $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
+                       $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
+                               $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
                } else {
                        $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
-                               $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
+                               $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
                }
 
                if (!empty($parent)) {
@@ -1504,10 +1577,10 @@ class Contact
                }
 
                if (DI::mode()->isMobile()) {
-                       $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
+                       $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
                                DI::config()->get('system', 'itemspage_network_mobile'));
                } else {
-                       $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
+                       $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
                                DI::config()->get('system', 'itemspage_network'));
                }
 
@@ -1515,7 +1588,7 @@ class Contact
 
                $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
 
-               if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
+               if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
                        $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
                        $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
                } else {
@@ -1524,27 +1597,27 @@ class Contact
 
                if ($thread_mode) {
                        $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
-                       $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
+                       $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
 
                        if ($pager->getStart() == 0) {
-                               $cdata = self::getPublicAndUserContactID($cid, local_user());
+                               $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
                                if (!empty($cdata['public'])) {
                                        $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
                                        $items = array_merge($items, $pinned);
                                }
                        }
 
-                       $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
+                       $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
                } else {
                        $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
-                       $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
+                       $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
 
                        if ($pager->getStart() == 0) {
-                               $cdata = self::getPublicAndUserContactID($cid, local_user());
+                               $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
                                if (!empty($cdata['public'])) {
                                        $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
                                                $cdata['public'], Post\Collection::FEATURED];
-                                       $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
+                                       $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
                                        $items = array_merge($pinned, $items);
                                }
                        }
@@ -1553,7 +1626,7 @@ class Contact
                }
 
                if (!$update) {
-                       if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
+                       if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
                                $o .= HTML::scrollLoader();
                        } else {
                                $o .= $pager->renderMinimal(count($items));
@@ -1657,11 +1730,9 @@ class Contact
        /**
         * Return the photo path for a given contact array in the given size
         *
-        * @param array $contact    contact array
-        * @param string $field     Fieldname of the photo in the contact array
+        * @param array  $contact   contact array
         * @param string $size      Size of the avatar picture
-        * @param string $avatar    Avatar path that is displayed when no photo had been found
-        * @param bool  $no_update Don't perfom an update if no cached avatar was found
+        * @param bool   $no_update Don't perfom an update if no cached avatar was found
         * @return string photo path
         */
        private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
@@ -1688,7 +1759,7 @@ class Contact
                        }
                }
 
-               return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
+               return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
        }
 
        /**
@@ -2000,9 +2071,10 @@ class Contact
         * @param integer $cid     contact id
         * @param string  $size    One of the Proxy::SIZE_* constants
         * @param string  $updated Contact update date
+        * @param bool    $static  If "true" a parameter is added to convert the avatar to a static one
         * @return string avatar link
         */
-       public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
+       public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
        {
                // We have to fetch the "updated" variable when it wasn't provided
                // The parameter can be provided to improve performance
@@ -2032,7 +2104,15 @@ class Contact
                                $url .= Proxy::PIXEL_LARGE . '/';
                                break;
                }
-               return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
+               $query_params = [];
+               if ($updated) {
+                       $query_params['ts'] = strtotime($updated);
+               }
+               if ($static) {
+                       $query_params['static'] = true;
+               }
+
+               return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
        }
 
        /**
@@ -2057,9 +2137,10 @@ class Contact
         * @param integer $cid     contact id
         * @param string  $size    One of the Proxy::SIZE_* constants
         * @param string  $updated Contact update date
+        * @param bool    $static  If "true" a parameter is added to convert the header to a static one
         * @return string header link
         */
-       public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
+       public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
        {
                // We have to fetch the "updated" variable when it wasn't provided
                // The parameter can be provided to improve performance
@@ -2090,7 +2171,15 @@ class Contact
                                break;
                }
 
-               return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
+               $query_params = [];
+               if ($updated) {
+                       $query_params['ts'] = strtotime($updated);
+               }
+               if ($static) {
+                       $query_params['static'] = true;
+               }
+
+               return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
        }
 
        /**
@@ -2108,7 +2197,7 @@ class Contact
         */
        public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
        {
-               $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
+               $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
                        ['id' => $cid, 'self' => false]);
                if (!DBA::isResult($contact)) {
                        return;
@@ -2118,8 +2207,19 @@ class Contact
 
                // Only update the cached photo links of public contacts when they already are cached
                if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
-                       if ($contact['avatar'] != $avatar) {
-                               self::update(['avatar' => $avatar], ['id' => $cid]);
+                       if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
+                               $update_fields = ['avatar' => $avatar];
+                               $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
+
+                               $img_str = $fetchResult->getBody();
+                               if (!empty($img_str)) {
+                                       $image = new Image($img_str, Images::getMimeTypeByData($img_str));
+                                       if ($image->isValid()) {
+                                               $update_fields['blurhash'] = $image->getBlurHash();
+                                       }
+                               }
+
+                               self::update($update_fields, ['id' => $cid]);
                                Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
                        }
                        return;
@@ -2190,7 +2290,7 @@ class Contact
                                if ($update) {
                                        $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
                                        if ($photos) {
-                                               $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
+                                               $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
                                                $update = !empty($fields);
                                                Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
                                        } else {
@@ -2344,7 +2444,7 @@ class Contact
                                return;
                        }
                        Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
-                       Worker::add(PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
+                       Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
                } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
                        Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
                } else {
@@ -2385,7 +2485,7 @@ class Contact
                                continue;
                        }
 
-                       Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
+                       Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
                }
                DBA::close($duplicates);
                Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
@@ -2408,13 +2508,23 @@ class Contact
                        return false;
                }
 
-               $ret = Probe::uri($contact['url'], $network, $contact['uid']);
+               $data = Probe::uri($contact['url'], $network, $contact['uid']);
 
-               if ($ret['network'] == Protocol::DIASPORA) {
-                       FContact::updateFromProbeArray($ret);
+               if ($data['network'] == Protocol::DIASPORA) {
+                       try {
+                               DI::dsprContact()->updateFromProbeArray($data);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::error($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+                       }
+               } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
+                       try {
+                               DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::error($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+                       }
                }
 
-               return self::updateFromProbeArray($id, $ret);
+               return self::updateFromProbeArray($id, $data);
        }
 
        /**
@@ -2587,7 +2697,7 @@ class Contact
                        if ($ret['network'] == Protocol::ACTIVITYPUB) {
                                $apcontact = APContact::getByURL($ret['url'], false);
                                if (!empty($apcontact['featured'])) {
-                                       Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
+                                       Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
                                }
                        }
 
@@ -2596,7 +2706,7 @@ class Contact
                }
 
                $update = false;
-               $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
+               $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url']);
 
                // make sure to not overwrite existing values with blank entries except some technical fields
                $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
@@ -2628,7 +2738,7 @@ class Contact
                        self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
 
                        if (Contact\Relation::isDiscoverable($ret['url'])) {
-                               Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
+                               Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
                        }
 
                        // Update the public contact
@@ -2672,7 +2782,7 @@ class Contact
                self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
 
                if (Contact\Relation::isDiscoverable($ret['url'])) {
-                       Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
+                       Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
                }
 
                return true;
@@ -2832,30 +2942,30 @@ class Contact
 
                // do we have enough information?
                if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
-                       $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
+                       $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
                        if (empty($ret['poll'])) {
-                               $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
+                               $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
                        }
                        if (empty($ret['name'])) {
-                               $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
+                               $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
                        }
                        if (empty($ret['url'])) {
-                               $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
+                               $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
                        }
                        if (strpos($ret['url'], '@') !== false) {
-                               $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
-                               $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
+                               $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
+                               $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
                        }
                        return $result;
                }
 
                if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
-                       $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
+                       $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
                        $ret['notify'] = '';
                }
 
                if (!$ret['notify']) {
-                       $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
+                       $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
                }
 
                $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
@@ -2914,7 +3024,7 @@ class Contact
 
                $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
                if (!DBA::isResult($contact)) {
-                       $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
+                       $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
                        return $result;
                }
 
@@ -2928,13 +3038,13 @@ class Contact
 
                // pull feed and consume it, which should subscribe to the hub.
                if ($contact['network'] == Protocol::OSTATUS) {
-                       Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
+                       Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
                }
 
                if ($probed) {
                        self::updateFromProbeArray($contact_id, $ret);
                } else {
-                       Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
+                       Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
                }
 
                $result['success'] = Protocol::follow($uid, $contact, $protocol);
@@ -3109,11 +3219,14 @@ class Contact
                        return;
                }
 
+               Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
+
                self::clearFollowerFollowingEndpointCache($contact['uid']);
 
                $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
-
-               DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
+               if (!empty($cdata['public'])) {
+                       DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
+               }
        }
 
        /**
@@ -3132,6 +3245,8 @@ class Contact
                } else {
                        self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
                }
+
+               Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
        }
 
        /**
@@ -3210,7 +3325,7 @@ class Contact
         */
        public static function magicLink(string $contact_url, string $url = ''): string
        {
-               if (!Session::isAuthenticated()) {
+               if (!DI::userSession()->isAuthenticated()) {
                        return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
                }
 
@@ -3256,7 +3371,7 @@ class Contact
        {
                $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
 
-               if (!Session::isAuthenticated()) {
+               if (!DI::userSession()->isAuthenticated()) {
                        return $destination;
                }
 
@@ -3265,7 +3380,7 @@ class Contact
                        return $url;
                }
 
-               if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
+               if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
                        return 'contact/' . $contact['id'] . '/conversations';
                }
 
@@ -3277,7 +3392,7 @@ class Contact
                        return $destination;
                }
 
-               $redirect = 'redir/' . $contact['id'];
+               $redirect = 'contact/redir/' . $contact['id'];
 
                if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
                        $redirect .= '?url=' . $url;
@@ -3326,11 +3441,13 @@ class Contact
         * @param string $search Name or nick
         * @param string $mode   Search mode (e.g. "community")
         * @param int    $uid    User ID
+        * @param int    $limit  Maximum amount of returned values
+        * @param int    $offset Limit offset
         *
         * @return array with search results
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public static function searchByName(string $search, string $mode = '', int $uid = 0): array
+       public static function searchByName(string $search, string $mode = '', int $uid = 0, int $limit = 0, int $offset = 0): array
        {
                if (empty($search)) {
                        return [];
@@ -3350,6 +3467,8 @@ class Contact
 
                if ($uid == 0) {
                        $condition['blocked'] = false;
+               } else {
+                       $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
                }
 
                // check if we search only communities or every contact
@@ -3359,12 +3478,19 @@ class Contact
 
                $search .= '%';
 
+               $params = [];
+
+               if (!empty($limit) && !empty($offset)) {
+                       $params['limit'] = [$offset, $limit];
+               } elseif (!empty($limit)) {
+                       $params['limit'] = $limit;
+               }
+
                $condition = DBA::mergeConditions($condition,
                        ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
                        AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
 
-               $contacts = self::selectToArray([], $condition);
-               return $contacts;
+               return self::selectToArray([], $condition, $params);
        }
 
        /**
@@ -3386,10 +3512,10 @@ class Contact
                        }
                        $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
                        if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
-                               Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
+                               Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
                                ++$added;
                        } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
-                               Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+                               Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
                                ++$updated;
                        } else {
                                ++$unchanged;
@@ -3419,4 +3545,17 @@ class Contact
 
                return [];
        }
+
+       /**
+        * Checks, if contacts with the given condition exists
+        *
+        * @param array $condition
+        *
+        * @return bool
+        * @throws \Exception
+        */
+       public static function exists(array $condition): bool
+       {
+               return DBA::exists('contact', $condition);
+       }
 }