]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Contact.php
Merge pull request #13172 from annando/parent-view
[friendica.git] / src / Model / Contact.php
index 392f7776154b863f1f1bfe54998907450fd40526..78150f1ff4085606ced6119babf7784c1eadedfd 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -23,6 +23,7 @@ namespace Friendica\Model;
 
 use Friendica\Contact\Avatar;
 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
+use Friendica\Content\Conversation As ConversationContent;
 use Friendica\Content\Pager;
 use Friendica\Content\Text\HTML;
 use Friendica\Core\Hook;
@@ -47,6 +48,7 @@ use Friendica\Util\Images;
 use Friendica\Util\Network;
 use Friendica\Util\Proxy;
 use Friendica\Util\Strings;
+use Friendica\Worker\UpdateContact;
 
 /**
  * functions for interacting with a contact
@@ -237,19 +239,17 @@ class Contact
         * @param array         $condition  condition array with the key values
         * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
         *
-        * @return boolean was the update successfull?
+        * @return boolean was the update successful?
         * @throws \Exception
         * @todo Let's get rid of boolean type of $old_fields
         */
-       public static function update(array $fields, array $condition, $old_fields = [])
+       public static function update(array $fields, array $condition, $old_fields = []): bool
        {
-               $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
-               $ret = DBA::update('contact', $fields, $condition, $old_fields);
-
                // Apply changes to the "user-contact" table on dedicated fields
                Contact\User::updateByContactUpdate($fields, $condition);
 
-               return $ret;
+               $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
+               return DBA::update('contact', $fields, $condition, $old_fields);
        }
 
        /**
@@ -329,7 +329,7 @@ class Contact
                // Add internal fields
                $removal = [];
                if (!empty($fields)) {
-                       foreach (['id', 'next-update', 'network'] as $internal) {
+                       foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
                                if (!in_array($internal, $fields)) {
                                        $fields[] = $internal;
                                        $removal[] = $internal;
@@ -358,9 +358,15 @@ class Contact
                        return [];
                }
 
+               $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
+
                // Update the contact in the background if needed
-               if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
-                       Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+               if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                       try {
+                               UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::notice($e->getMessage(), ['contact' => $contact]);
+                       }
                }
 
                // Remove the internal fields
@@ -564,7 +570,7 @@ class Contact
        {
                if (!parse_url($url, PHP_URL_SCHEME)) {
                        $addr_parts = explode('@', $url);
-                       return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
+                       return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
                }
 
                return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
@@ -622,7 +628,7 @@ class Contact
        public static function getPublicAndUserContactID(int $cid, int $uid): array
        {
                // We have to use the legacy function as long as the post update hasn't finished
-               if (DI::config()->get('system', 'post_update_version') < 1427) {
+               if (DI::keyValue()->get('post_update_version') < 1427) {
                        return self::legacyGetPublicAndUserContactID($cid, $uid);
                }
 
@@ -1146,10 +1152,11 @@ class Contact
                $status_link = '';
                $photos_link = '';
 
-               $sparkle = false;
                if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
-                       $sparkle      = true;
                        $profile_link = 'contact/redir/' . $contact['id'];
+                       $status_link  = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
+                       $photos_link  = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
+                       $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
                } else {
                        $profile_link = $contact['url'];
                }
@@ -1158,12 +1165,6 @@ class Contact
                        $profile_link = '';
                }
 
-               if ($sparkle) {
-                       $status_link  = $profile_link . '/status';
-                       $photos_link  = $profile_link . '/photos';
-                       $profile_link = $profile_link . '/profile';
-               }
-
                if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
                        $pm_url = 'message/new/' . $contact['id'];
                }
@@ -1266,13 +1267,19 @@ class Contact
                        return 0;
                }
 
-               $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
+               $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $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']);
+                       $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
+
+                       if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                               try {
+                                       UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+                               } catch (\InvalidArgumentException $e) {
+                                       Logger::notice($e->getMessage(), ['contact' => $contact]);
+                               }
                        }
 
                        if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
@@ -1544,8 +1551,8 @@ 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 `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
-                               $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
+                       $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
+                               $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()];
                } else {
                        $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
                                $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
@@ -1596,7 +1603,7 @@ class Contact
                                }
                        }
 
-                       $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
+                       $o .= DI::conversation()->create($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
                } else {
                        $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
                        $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
@@ -1611,7 +1618,7 @@ class Contact
                                }
                        }
 
-                       $o .= DI::conversation()->create($items, 'contact-posts', $update);
+                       $o .= DI::conversation()->create($items, ConversationContent::MODE_CONTACT_POSTS, $update);
                }
 
                if (!$update) {
@@ -1674,7 +1681,7 @@ class Contact
         * Unblocks a contact
         *
         * @param int $cid Contact id to unblock
-        * @return bool Whether it was successfull
+        * @return bool Whether it was successful
         */
        public static function unblock(int $cid): bool
        {
@@ -1721,7 +1728,7 @@ class Contact
         *
         * @param array  $contact   contact array
         * @param string $size      Size of the avatar picture
-        * @param bool   $no_update Don't perfom an update if no cached avatar was found
+        * @param bool   $no_update Don't perform 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
@@ -1755,7 +1762,7 @@ class Contact
         * Return the photo path for a given contact array
         *
         * @param array  $contact   Contact array
-        * @param bool   $no_update Don't perfom an update if no cached avatar was found
+        * @param bool   $no_update Don't perform an update if no cached avatar was found
         * @return string photo path
         */
        public static function getPhoto(array $contact, bool $no_update = false): string
@@ -1767,7 +1774,7 @@ class Contact
         * Return the photo path (thumb size) for a given contact array
         *
         * @param array  $contact   Contact array
-        * @param bool   $no_update Don't perfom an update if no cached avatar was found
+        * @param bool   $no_update Don't perform an update if no cached avatar was found
         * @return string photo path
         */
        public static function getThumb(array $contact, bool $no_update = false): string
@@ -1779,7 +1786,7 @@ class Contact
         * Return the photo path (micro size) for a given contact array
         *
         * @param array  $contact   Contact array
-        * @param bool   $no_update Don't perfom an update if no cached avatar was found
+        * @param bool   $no_update Don't perform an update if no cached avatar was found
         * @return string photo path
         */
        public static function getMicro(array $contact, bool $no_update = false): string
@@ -1791,7 +1798,7 @@ class Contact
         * Check the given contact array for avatar cache fields
         *
         * @param array $contact
-        * @param bool  $no_update Don't perfom an update if no cached avatar was found
+        * @param bool  $no_update Don't perform an update if no cached avatar was found
         * @return array contact array with avatar cache fields
         */
        private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
@@ -2192,20 +2199,38 @@ class Contact
                        return;
                }
 
+               if (!Network::isValidHttpUrl($avatar)) {
+                       Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
+                       $avatar = '';
+               }
+
                $uid = $contact['uid'];
 
                // 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) || 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();
+                               if (!Network::isLocalLink($avatar)) {
+                                       try {
+                                               $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();
+                                                       } else {
+                                                               return;
+                                                       }
+                                               }
+                                       } catch (\Exception $exception) {
+                                               Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
+                                               return;
                                        }
+                               } elseif (!empty($contact['blurhash'])) {
+                                       $update_fields['blurhash'] = null;
+                               } else {
+                                       return;
                                }
 
                                self::update($update_fields, ['id' => $cid]);
@@ -2238,7 +2263,9 @@ class Contact
                }
 
                if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
-                       Avatar::deleteCache($contact);
+                       if (Avatar::deleteCache($contact)) {
+                               $force = true;
+                       }
 
                        if ($default_avatar && Proxy::isLocalImage($avatar)) {
                                $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
@@ -2377,6 +2404,11 @@ class Contact
                $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
 
                $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
+
+               if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
+                       $condition['network'][] = $contact['network'];
+               }
+
                self::update($fields, $condition);
 
                // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
@@ -2481,6 +2513,44 @@ class Contact
                return true;
        }
 
+       /**
+        * Perform a contact update if the contact is outdated
+        *
+        * @param integer $id contact id
+        * @return bool
+        */
+       public static function updateByIdIfNeeded(int $id): bool
+       {
+               $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
+               if (empty($contact['url'])) {
+                       return false;
+               }
+
+               if (self::isLocal($contact['url'])) {
+                       return true;
+               }
+
+               $stamp = (float)microtime(true);
+               self::updateFromProbe($id);
+               Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
+               return true;
+       }
+
+       /**
+        * Perform a contact update if the contact is outdated
+        *
+        * @param string $url contact url
+        * @return bool
+        */
+       public static function updateByUrlIfNeeded(string $url): bool
+       {
+               $id = self::getIdForURL($url, 0, false);
+               if (!empty($id)) {
+                       return self::updateByIdIfNeeded($id);
+               }
+               return (bool)self::getIdForURL($url);
+       }
+
        /**
         * Updates contact record by provided id and optional network
         *
@@ -2607,6 +2677,8 @@ class Contact
                        return true;
                }
 
+                $has_local_data = self::hasLocalData($id, $contact);
+
                $uid = $contact['uid'];
                unset($contact['uid']);
 
@@ -2627,18 +2699,20 @@ class Contact
 
                $updated = DateTimeFormat::utcNow();
 
-               $has_local_data = self::hasLocalData($id, $contact);
-
-               if (!Probe::isProbable($ret['network'])) {
+               if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
                        // Periodical checks are only done on federated contacts
                        $failed_next_update  = null;
                        $success_next_update = null;
                } elseif ($has_local_data) {
                        $failed_next_update  = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
                        $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
-               } else {
+               } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
                        $failed_next_update  = DateTimeFormat::utc('now +6 month');
                        $success_next_update = DateTimeFormat::utc('now +1 month');
+               } else {
+                       // We don't check connector networks very often to not run into API rate limits
+                       $failed_next_update  = DateTimeFormat::utc('now +12 month');
+                       $success_next_update = DateTimeFormat::utc('now +12 month');
                }
 
                if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
@@ -2911,12 +2985,12 @@ class Contact
                }
 
                if (($network != '') && ($ret['network'] != $network)) {
-                       Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
+                       $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
                        return $result;
                }
 
                // check if we already have a contact
-               $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url'])];
+               $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
                $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
 
                $protocol = self::getProtocol($ret['url'], $ret['network']);
@@ -3023,7 +3097,7 @@ class Contact
                $contact_id = $contact['id'];
                $result['cid'] = $contact_id;
 
-               Group::addMember(User::getDefaultGroup($uid), $contact_id);
+               Circle::addMember(User::getDefaultCircle($uid), $contact_id);
 
                // Update the avatar
                self::updateAvatar($contact_id, $ret['photo']);
@@ -3036,7 +3110,11 @@ class Contact
                if ($probed) {
                        self::updateFromProbeArray($contact_id, $ret);
                } else {
-                       Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
+                       try {
+                               UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
+                       } catch (\InvalidArgumentException $e) {
+                               Logger::notice($e->getMessage(), ['contact' => $contact]);
+                       }
                }
 
                $result['success'] = Protocol::follow($uid, $contact, $protocol);
@@ -3160,7 +3238,7 @@ class Contact
                                        DI::intro()->save($intro);
                                }
 
-                               Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
+                               Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
 
                                if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
                                        DI::notify()->createFromArray([
@@ -3235,7 +3313,7 @@ class Contact
                if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
                        self::remove($contact['id']);
                } else {
-                       self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
+                       self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
                }
 
                Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
@@ -3361,7 +3439,7 @@ class Contact
         */
        public static function magicLinkByContact(array $contact, string $url = ''): string
        {
-               $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
+               $destination = $url ?: $contact['url'];
 
                if (!DI::userSession()->isAuthenticated()) {
                        return $destination;
@@ -3430,16 +3508,17 @@ class Contact
        /**
         * Search contact table by nick or name
         *
-        * @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
+        * @param string $search       Name or nick
+        * @param string $mode         Search mode (e.g. "community")
+        * @param bool   $show_blocked Show users from blocked servers. Default is false
+        * @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, int $limit = 0, int $offset = 0): array
+       public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
        {
                if (empty($search)) {
                        return [];
@@ -3455,7 +3534,18 @@ class Contact
                        $networks[] = Protocol::OSTATUS;
                }
 
-               $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
+               $condition = [
+                       'network'        => $networks,
+                       'server-failed'  => false,
+                       'failed'         => false,
+                       'deleted'        => false,
+                       'unsearchable'   => false,
+                       'uid'            => $uid
+               ];
+
+               if (!$show_blocked) {
+                       $condition['server-blocked'] = true;
+               }
 
                if ($uid == 0) {
                        $condition['blocked'] = false;
@@ -3479,10 +3569,9 @@ class Contact
                }
 
                $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]);
+                       ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
 
-               return self::selectToArray([], $condition, $params);
+               return DBA::selectToArray('account-user-view', [], $condition, $params);
        }
 
        /**
@@ -3506,9 +3595,13 @@ class Contact
                        if (empty($contact['id']) && Network::isValidHttpUrl($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' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
-                               ++$updated;
+                       } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+                               try {
+                                       UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+                                       ++$updated;
+                               } catch (\InvalidArgumentException $e) {
+                                       Logger::notice($e->getMessage(), ['contact' => $contact]);
+                               }
                        } else {
                                ++$unchanged;
                        }