]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Contact.php
Merge pull request #12228 from MrPetovan/task/4090-move-mod-photos
[friendica.git] / src / Model / Contact.php
index 6a57693991127be745e836acf043a08ecec04ed9..ce392217dd4d127bc66b894325c71b012d3a59fc 100644 (file)
@@ -29,13 +29,11 @@ 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\HTTPException;
 use Friendica\Network\Probe;
 use Friendica\Protocol\Activity;
@@ -98,11 +96,11 @@ 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
        /**
         * @}
         */
@@ -138,6 +136,18 @@ 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|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.
@@ -169,16 +179,41 @@ class Contact
                        return 0;
                }
 
-               Contact\User::insertForContactArray($contact);
-
-               // Search for duplicated contacts and get rid of them
-               if (!$contact['self']) {
-                       self::removeDuplicates($contact['nurl'], $contact['uid']);
+               $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
+               DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
+               $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
+               if (empty($account_user['id'])) {
+                       Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
+               } elseif ($account_user['id'] != $contact['id']) {
+                       $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
+                       if (!empty($duplicate['id'])) {
+                               $ret = Contact::deleteById($contact['id']);
+                               Logger::notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]);
+                               $contact = $duplicate;
+                       } else {
+                               $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
+                               Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
+                       }
                }
 
+               Contact\User::insertForContactArray($contact);
+
                return $contact['id'];
        }
 
+       /**
+        * Delete contact by id
+        *
+        * @param integer $id
+        * @return boolean
+        */
+       public static function deleteById(int $id): bool
+       {
+               Logger::debug('Delete contact', ['id' => $id]);
+               DBA::delete('account-user', ['id' => $id]);
+               return DBA::delete('contact', ['id' => $id]);
+       }
+
        /**
         * Updates rows in the contact table
         *
@@ -225,6 +260,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
         *
@@ -252,7 +313,7 @@ class Contact
                // Add internal fields
                $removal = [];
                if (!empty($fields)) {
-                       foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
+                       foreach (['id', 'next-update', 'network'] as $internal) {
                                if (!in_array($internal, $fields)) {
                                        $fields[] = $internal;
                                        $removal[] = $internal;
@@ -282,9 +343,8 @@ class Contact
                }
 
                // Update the contact in the background if needed
-               $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
-               if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
-                       Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
+               if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                       Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
                }
 
                // Remove the internal fields
@@ -326,6 +386,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
         *
@@ -657,7 +729,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(),
@@ -739,7 +810,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'],
                ];
 
 
@@ -825,17 +895,19 @@ class Contact
                        return;
                }
 
+               DBA::delete('account-user', ['id' => $id]);
+
                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);
        }
 
        /**
@@ -859,7 +931,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']);
                        }
                }
 
@@ -889,7 +961,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']);
                        }
                }
 
@@ -917,11 +989,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']);
@@ -935,7 +1007,6 @@ class Contact
 
                DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
                DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
-               DI::cache()->delete(NoScrape::CACHEKEY . $uid);
        }
 
        /**
@@ -1055,7 +1126,7 @@ class Contact
                $photos_link = '';
 
                if ($uid == 0) {
-                       $uid = local_user();
+                       $uid = DI::userSession()->getLocalUserId();
                }
 
                if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
@@ -1076,7 +1147,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'];
                }
@@ -1087,25 +1158,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';
                        }
                }
 
@@ -1119,7 +1190,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 = [
@@ -1130,7 +1201,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'])) {
@@ -1194,11 +1265,15 @@ class Contact
                        return 0;
                }
 
-               $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
+               $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
 
                if (!empty($contact)) {
                        $contact_id = $contact['id'];
 
+                       if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                               Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+                       }
+
                        if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
                                Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
                                return $contact_id;
@@ -1253,6 +1328,11 @@ class Contact
                        return 0;
                }
 
+               if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
+                       Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
+                       return 0;
+               }
+
                if (!$contact_id) {
                        $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
                        if (!empty($data['alias'])) {
@@ -1277,25 +1357,21 @@ 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.
-                       if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
-                               $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
-                               if (DBA::isResult($contact)) {
-                                       $contact_id = $contact['id'];
-                                       Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
-                               } else {
-                                       $contact_id = self::insert($fields);
-                                       if ($contact_id) {
-                                               Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
-                                       }
-                               }
-                               DI::lock()->release(self::LOCK_INSERT);
+                       $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
+                       if (DBA::isResult($contact)) {
+                               $contact_id = $contact['id'];
+                               Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
                        } else {
-                               Logger::warning('Contact lock had not been acquired');
+                               $contact_id = self::insert($fields);
+                               if ($contact_id) {
+                                       Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
+                               }
                        }
 
                        if (!$contact_id) {
@@ -1453,11 +1529,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)) {
@@ -1475,10 +1551,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'));
                }
 
@@ -1486,7 +1562,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 {
@@ -1495,27 +1571,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);
                                }
                        }
@@ -1524,7 +1600,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));
@@ -1628,11 +1704,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
@@ -1659,7 +1733,7 @@ class Contact
                        }
                }
 
-               return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
+               return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
        }
 
        /**
@@ -2219,25 +2293,22 @@ class Contact
        /**
         * Helper function for "updateFromProbe". Updates personal and public contact
         *
-        * @param integer $id      contact id
-        * @param integer $uid     user id
-        * @param string  $old_url The previous profile URL of the contact
-        * @param string  $new_url The profile URL of the contact
-        * @param array   $fields  The fields that are updated
+        * @param integer $id     contact id
+        * @param integer $uid    user id
+        * @param integer $uri_id Uri-Id
+        * @param string  $url    The profile URL of the contact
+        * @param array   $fields The fields that are updated
         *
         * @throws \Exception
         */
-       private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
+       private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
        {
                if (!self::update($fields, ['id' => $id])) {
                        Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
                        return;
                }
 
-               // Search for duplicated contacts and get rid of them
-               if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
-                       return;
-               }
+               self::setAccountUser($id, $uid, $uri_id, $url);
 
                // Archive or unarchive the contact.
                $contact = DBA::selectFirst('contact', [], ['id' => $id]);
@@ -2259,7 +2330,7 @@ class Contact
                }
 
                // Update contact data for all users
-               $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
+               $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
 
                $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
                self::update($fields, $condition);
@@ -2281,6 +2352,51 @@ class Contact
                self::update($fields, $condition);
        }
 
+       /**
+        * Create or update an "account-user" entry
+        *
+        * @param integer $id
+        * @param integer $uid
+        * @param integer $uri_id
+        * @param string $url
+        * @return void
+        */
+       public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
+       {
+               if (empty($uri_id)) {
+                       return;
+               }
+
+               $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
+               if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
+                       if ($account_user['uid'] == $uid) {
+                               $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
+                               Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
+                       } else {
+                               // This should never happen
+                               Logger::warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
+                       }
+               }
+
+               $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
+               if (!empty($account_user['id'])) {
+                       if ($account_user['id'] == $id) {
+                               Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
+                               return;
+                       } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
+                               $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
+                               Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
+                               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(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 {
+                       Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
+               }
+       }
+
        /**
         * Remove duplicated contacts
         *
@@ -2305,11 +2421,6 @@ class Contact
 
                $first = $first_contact['id'];
                Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
-               if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
-                       // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
-                       Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
-                       return false;
-               }
 
                // Find all duplicates
                $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
@@ -2319,7 +2430,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)]);
@@ -2460,7 +2571,7 @@ class Contact
 
                $has_local_data = self::hasLocalData($id, $contact);
 
-               if (!in_array($ret['network'], array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM]))) {
+               if (!Probe::isProbable($ret['network'])) {
                        // Periodical checks are only done on federated contacts
                        $failed_next_update  = null;
                        $success_next_update = null;
@@ -2474,7 +2585,7 @@ class Contact
 
                if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
                        Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
-                       self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
+                       self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
                        return false;
                }
 
@@ -2482,14 +2593,14 @@ class Contact
                // We check after the probing to be able to correct falsely detected contact types.
                if (($contact['contact-type'] == self::TYPE_RELAY) &&
                        (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
-                       self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
+                       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]);
                        Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
                        return true;
                }
 
                // If Probe::uri fails the network code will be different ("feed" or "unkn")
                if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
-                       self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
+                       self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
                        return false;
                }
 
@@ -2521,7 +2632,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']);
                                }
                        }
 
@@ -2558,13 +2669,11 @@ class Contact
                        self::updateAvatar($id, $ret['photo'], $update);
                }
 
-               $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
-
                if (!$update) {
-                       self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
+                       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
@@ -2578,7 +2687,7 @@ class Contact
                        return true;
                }
 
-               $ret['uri-id']      = $uriid;
+               $ret['uri-id']      = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
                $ret['nurl']        = Strings::normaliseLink($ret['url']);
                $ret['updated']     = $updated;
                $ret['failed']      = false;
@@ -2605,10 +2714,10 @@ class Contact
 
                unset($ret['photo']);
 
-               self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
+               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;
@@ -2768,30 +2877,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);
@@ -2850,7 +2959,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;
                }
 
@@ -2864,13 +2973,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);
@@ -3146,7 +3255,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;
                }
 
@@ -3192,7 +3301,7 @@ class Contact
        {
                $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
 
-               if (!Session::isAuthenticated()) {
+               if (!DI::userSession()->isAuthenticated()) {
                        return $destination;
                }
 
@@ -3201,7 +3310,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';
                }
 
@@ -3213,7 +3322,7 @@ class Contact
                        return $destination;
                }
 
-               $redirect = 'redir/' . $contact['id'];
+               $redirect = 'contact/redir/' . $contact['id'];
 
                if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
                        $redirect .= '?url=' . $url;
@@ -3262,11 +3371,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 [];
@@ -3286,6 +3397,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
@@ -3295,11 +3408,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);
+               $contacts = self::selectToArray([], $condition, $params);
                return $contacts;
        }
 
@@ -3320,12 +3441,12 @@ class Contact
                        if (empty($url) || !is_string($url)) {
                                continue;
                        }
-                       $contact = self::getByURL($url, false, ['id', 'updated']);
+                       $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 ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
-                               Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
+                       } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                               Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
                                ++$updated;
                        } else {
                                ++$unchanged;
@@ -3355,4 +3476,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);
+       }
 }