3 * @copyright Copyright (C) 2010-2024, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Contact\Avatar;
25 use Friendica\Contact\Header;
26 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
27 use Friendica\Contact\LocalRelationship\Entity\LocalRelationship;
28 use Friendica\Content\Conversation as ConversationContent;
29 use Friendica\Content\Pager;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Core\Hook;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\System;
36 use Friendica\Core\Worker;
37 use Friendica\Database\Database;
38 use Friendica\Database\DBA;
40 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
41 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
42 use Friendica\Network\HTTPException;
43 use Friendica\Network\Probe;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\HTTPSignature;
49 use Friendica\Util\Images;
50 use Friendica\Util\Network;
51 use Friendica\Util\Proxy;
52 use Friendica\Util\Strings;
53 use Friendica\Worker\UpdateContact;
56 * functions for interacting with a contact
60 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
61 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
62 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
68 const LOCK_INSERT = 'contact-insert';
73 * TYPE_UNKNOWN - unknown type
75 * TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
78 * TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_SOAPBOX
84 * TYPE_COMMUNITY - the account is community group
85 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
87 * TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const TYPE_UNKNOWN = -1;
92 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
93 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
94 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
95 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
96 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
107 const NOTHING = 0; // There is no relationship between the contact and the user
108 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
109 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
110 const FRIEND = 3; // There is a mutual relationship between the contact and the user
111 const SELF = 4; // This is the user theirself
116 /** @deprecated Use Entity\LocalRelationship::MIRROR_DEACTIVATED instead */
117 const MIRROR_DEACTIVATED = LocalRelationship::MIRROR_DEACTIVATED;
118 /** @deprecated Now does the same as MIRROR_OWN_POST */
119 const MIRROR_FORWARDED = 1;
120 /** @deprecated Use Entity\LocalRelationship::MIRROR_OWN_POST instead */
121 const MIRROR_OWN_POST = LocalRelationship::MIRROR_OWN_POST;
122 /** @deprecated Use Entity\LocalRelationship::MIRROR_NATIVE_RESHARE instead */
123 const MIRROR_NATIVE_RESHARE = LocalRelationship::MIRROR_NATIVE_RESHARE;
126 * @param array $fields Array of selected fields, empty for all
127 * @param array $condition Array of fields for condition
128 * @param array $params Array of several parameters
132 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
134 return DBA::selectToArray('contact', $fields, $condition, $params);
138 * @param array $fields Array of selected fields, empty for all
139 * @param array $condition Array of fields for condition
140 * @param array $params Array of several parameters
144 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
146 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
152 * @param array $fields Array of selected fields, empty for all
153 * @param array $condition Array of fields for condition
154 * @param array $params Array of several parameters
158 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
160 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
164 * @param array $fields Array of selected fields, empty for all
165 * @param array $condition Array of fields for condition
166 * @param array $params Array of several parameters
170 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
172 return DBA::selectFirst('account-view', $fields, $condition, $params);
175 public static function selectFirstAccountUser(array $fields = [], array $condition = [], array $params = [])
177 return DBA::selectFirst('account-user-view', $fields, $condition, $params);
181 * Insert a row into the contact table
182 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
184 * @param array $fields field array
185 * @param int $duplicate_mode Do an update on a duplicate entry
187 * @return int id of the created contact
190 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
192 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
193 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
196 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
198 if (empty($fields['created'])) {
199 $fields['created'] = DateTimeFormat::utcNow();
202 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
203 DBA::insert('contact', $fields, $duplicate_mode);
204 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
205 if (!DBA::isResult($contact)) {
207 Logger::warning('Created contact could not be found', ['fields' => $fields]);
211 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
212 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
213 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
214 if (empty($account_user['id'])) {
215 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
216 } elseif ($account_user['id'] != $contact['id']) {
217 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
218 if (!empty($duplicate['id'])) {
219 $ret = Contact::deleteById($contact['id']);
220 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']]);
221 $contact = $duplicate;
223 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
224 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']]);
228 Contact\User::insertForContactArray($contact);
230 if ((empty($contact['baseurl']) || empty($contact['gsid'])) && Probe::isProbable($contact['network'])) {
231 Logger::debug('Update missing baseurl', ['id' => $contact['id'], 'url' => $contact['url'], 'callstack' => System::callstack(4, 0, true)]);
232 UpdateContact::add(['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true], $contact['id']);
235 return $contact['id'];
239 * Delete contact by id
244 public static function deleteById(int $id): bool
246 Logger::debug('Delete contact', ['id' => $id]);
247 DBA::delete('account-user', ['id' => $id]);
248 return DBA::delete('contact', ['id' => $id]);
252 * Updates rows in the contact table
254 * @param array $fields contains the fields that are updated
255 * @param array $condition condition array with the key values
256 * @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)
258 * @return boolean was the update successful?
260 * @todo Let's get rid of boolean type of $old_fields
262 public static function update(array $fields, array $condition, $old_fields = []): bool
264 // Apply changes to the "user-contact" table on dedicated fields
265 Contact\User::updateByContactUpdate($fields, $condition);
267 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
268 return DBA::update('contact', $fields, $condition, $old_fields);
272 * @param integer $id Contact ID
273 * @param array $fields Array of selected fields, empty for all
274 * @return array|boolean Contact record if it exists, false otherwise
277 public static function getById(int $id, array $fields = [])
279 return DBA::selectFirst('contact', $fields, ['id' => $id]);
283 * Fetch the first contact with the provided uri-id.
285 * @param integer $uri_id uri-id of the contact
286 * @param array $fields Array of selected fields, empty for all
287 * @return array|boolean Contact record if it exists, false otherwise
290 public static function getByUriId(int $uri_id, array $fields = [])
292 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
296 * Fetch all remote contacts for a given contact url
298 * @param string $url The URL of the contact
299 * @param array $fields The wanted fields
301 * @return array all remote contacts
305 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
309 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
310 while ($contact = DBA::fetch($remote_contacts)) {
311 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
314 $remote[$contact['uid']] = $contact['id'];
316 DBA::close($remote_contacts);
322 * Fetches a contact by a given url
324 * @param string $url profile url
325 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
326 * @param array $fields Field list
327 * @param integer $uid User ID of the contact
328 * @return array contact array
330 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
332 if ($update || is_null($update)) {
333 $cid = self::getIdForURL($url, $uid, $update);
338 $contact = self::getById($cid, $fields);
339 if (empty($contact)) {
345 // Add internal fields
347 if (!empty($fields)) {
348 foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
349 if (!in_array($internal, $fields)) {
350 $fields[] = $internal;
351 $removal[] = $internal;
356 // We first try the nurl (http://server.tld/nick), most common case
357 $options = ['order' => ['id']];
358 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
360 // Then the addr (nick@server.tld)
361 if (!DBA::isResult($contact)) {
362 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
365 // Then the alias (which could be anything)
366 if (!DBA::isResult($contact)) {
367 // The link could be provided as http although we stored it as https
368 $ssl_url = str_replace('http://', 'https://', $url);
369 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
370 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
373 if (!DBA::isResult($contact)) {
377 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
379 // Update the contact in the background if needed
380 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
382 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
383 } catch (\InvalidArgumentException $e) {
384 Logger::notice($e->getMessage(), ['contact' => $contact]);
388 // Remove the internal fields
389 foreach ($removal as $internal) {
390 unset($contact[$internal]);
397 * Fetches a contact for a given user by a given url.
398 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
400 * @param string $url profile url
401 * @param integer $uid User ID of the contact
402 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
403 * @param array $fields Field list
404 * @return array contact array
406 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
409 $contact = self::getByURL($url, $update, $fields, $uid);
410 if (!empty($contact)) {
411 if (!empty($contact['id'])) {
412 $contact['cid'] = $contact['id'];
419 $contact = self::getByURL($url, $update, $fields);
420 if (!empty($contact['id'])) {
422 $contact['zid'] = $contact['id'];
428 * Checks if a contact uses a specific platform
431 * @param string $platform
434 public static function isPlatform(string $url, string $platform): bool
436 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
440 * Tests if the given contact is a follower
442 * @param int $cid Either public contact id or user's contact id
443 * @param int $uid User ID
444 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
446 * @return boolean is the contact id a follower?
447 * @throws HTTPException\InternalServerErrorException
448 * @throws \ImagickException
450 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
452 if (Contact\User::isBlocked($cid, $uid)) {
456 $cdata = self::getPublicAndUserContactID($cid, $uid);
457 if (empty($cdata['user'])) {
461 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
463 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
465 return DBA::exists('contact', $condition);
469 * Tests if the given contact url is a follower
471 * @param string $url Contact URL
472 * @param int $uid User ID
473 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
475 * @return boolean is the contact id a follower?
476 * @throws HTTPException\InternalServerErrorException
477 * @throws \ImagickException
479 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
481 $cid = self::getIdForURL($url, $uid);
487 return self::isFollower($cid, $uid, $strict);
491 * Tests if the given user shares with the given contact
493 * @param int $cid Either public contact id or user's contact id
494 * @param int $uid User ID
495 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
497 * @return boolean is the contact sharing with given user?
498 * @throws HTTPException\InternalServerErrorException
499 * @throws \ImagickException
501 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
503 if (Contact\User::isBlocked($cid, $uid)) {
507 $cdata = self::getPublicAndUserContactID($cid, $uid);
508 if (empty($cdata['user'])) {
512 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
514 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
516 return DBA::exists('contact', $condition);
520 * Tests if the given user follow the given contact url
522 * @param string $url Contact URL
523 * @param int $uid User ID
524 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
526 * @return boolean is the contact url being followed?
527 * @throws HTTPException\InternalServerErrorException
528 * @throws \ImagickException
530 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
532 $cid = self::getIdForURL($url, $uid);
538 return self::isSharing($cid, $uid, $strict);
542 * Checks if the provided public contact id has got followers on this system
544 * @param integer $cid
547 public static function hasFollowers(int $cid): bool
549 return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?)", $cid, 0, self::SHARING, self::FRIEND]);
553 * Get the basepath for a given contact link
555 * @param string $url The contact link
556 * @param boolean $dont_update Don't update the contact
558 * @return string basepath
559 * @throws HTTPException\InternalServerErrorException
560 * @throws \ImagickException
562 public static function getBasepath(string $url, bool $dont_update = false): string
564 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
565 if (!DBA::isResult($contact)) {
569 if (!empty($contact['baseurl'])) {
570 return $contact['baseurl'];
571 } elseif ($dont_update) {
575 // Update the existing contact
576 self::updateFromProbe($contact['id']);
578 // And fetch the result
579 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
580 if (empty($contact['baseurl'])) {
581 Logger::info('No baseurl for contact', ['url' => $url]);
585 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
586 return $contact['baseurl'];
590 * Check if the given contact url is on the same server
592 * @param string $url The contact link
594 * @return boolean Is it the same server?
596 public static function isLocal(string $url): bool
598 if (!parse_url($url, PHP_URL_SCHEME)) {
599 $addr_parts = explode('@', $url);
600 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
603 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
607 * Check if the given contact ID is on the same server
609 * @param string $url The contact link
610 * @return boolean Is it the same server?
612 public static function isLocalById(int $cid): bool
614 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
615 if (!DBA::isResult($contact)) {
619 if (empty($contact['baseurl'])) {
620 $baseurl = self::getBasepath($contact['url'], true);
622 $baseurl = $contact['baseurl'];
625 return Strings::compareLink($baseurl, DI::baseUrl());
629 * Returns the public contact id of the given user id
631 * @param integer $uid User ID
633 * @return integer|boolean Public contact id for given user id
636 public static function getPublicIdByUserId(int $uid)
638 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
639 if (!DBA::isResult($self)) {
642 return self::getIdForURL($self['url']);
646 * Returns the contact id for the user and the public contact id for a given contact id
648 * @param int $cid Either public contact id or user's contact id
649 * @param int $uid User ID
651 * @return array with public and user's contact id
652 * @throws HTTPException\InternalServerErrorException
653 * @throws \ImagickException
655 public static function getPublicAndUserContactID(int $cid, int $uid): array
657 // We have to use the legacy function as long as the post update hasn't finished
658 if (DI::keyValue()->get('post_update_version') < 1427) {
659 return self::legacyGetPublicAndUserContactID($cid, $uid);
662 if (empty($uid) || empty($cid)) {
666 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
667 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
671 $pcid = $contact['pid'];
672 if ($contact['uid'] == $uid) {
673 $ucid = $contact['id'];
675 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
676 if (DBA::isResult($contact)) {
677 $ucid = $contact['id'];
683 return ['public' => $pcid, 'user' => $ucid];
687 * Helper function for "getPublicAndUserContactID"
689 * @param int $cid Either public contact id or user's contact id
690 * @param int $uid User ID
691 * @return array with public and user's contact id
692 * @throws HTTPException\InternalServerErrorException
693 * @throws \ImagickException
695 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
697 if (empty($uid) || empty($cid)) {
701 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
702 if (!DBA::isResult($contact)) {
706 // We quit when the user id don't match the user id of the provided contact
707 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
711 if ($contact['uid'] != 0) {
712 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
716 $ucid = $contact['id'];
718 $pcid = $contact['id'];
719 $ucid = self::getIdForURL($contact['url'], $uid);
722 return ['public' => $pcid, 'user' => $ucid];
726 * Returns contact details for a given contact id in combination with a user id
728 * @param int $cid A contact ID
729 * @param int $uid The User ID
730 * @param array $fields The selected fields for the contact
731 * @return array The contact details
735 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
737 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
739 if (!DBA::isResult($contact)) {
747 * Creates the self-contact for the provided user id
750 * @return bool Operation success
751 * @throws HTTPException\InternalServerErrorException
753 public static function createSelfFromUserId(int $uid): bool
755 $user = DBA::selectFirst(
757 ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
758 ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
760 if (!DBA::isResult($user)) {
765 'uid' => $user['uid'],
766 'created' => DateTimeFormat::utcNow(),
768 'name' => $user['username'],
769 'nick' => $user['nickname'],
770 'pubkey' => $user['pubkey'],
771 'prvkey' => $user['prvkey'],
772 'photo' => User::getAvatarUrl($user),
773 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
774 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
777 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
778 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
779 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
780 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
781 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
782 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
783 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
784 'name-date' => DateTimeFormat::utcNow(),
785 'uri-date' => DateTimeFormat::utcNow(),
786 'avatar-date' => DateTimeFormat::utcNow(),
792 // Only create the entry if it doesn't exist yet
793 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
794 $return = (bool)self::insert($contact);
797 // Create the public contact
798 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
799 $contact['self'] = false;
801 $contact['prvkey'] = null;
803 self::insert($contact, Database::INSERT_IGNORE);
810 * Updates the self-contact for the provided user id
813 * @param bool $update_avatar Force the avatar update
814 * @return bool "true" if updated
817 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
820 'id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
821 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
822 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'
824 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
825 if (!DBA::isResult($self)) {
829 $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
830 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
831 if (!DBA::isResult($user)) {
836 'name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
837 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'
839 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
840 if (!DBA::isResult($profile)) {
844 $file_suffix = 'jpg';
845 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
848 'name' => $user['username'],
849 'nick' => $user['nickname'],
850 'avatar-date' => $self['avatar-date'],
851 'location' => Profile::formatLocation($profile),
852 'about' => $profile['about'],
853 'keywords' => $profile['pub_keywords'],
854 'contact-type' => $user['account-type'],
855 'prvkey' => $user['prvkey'],
856 'pubkey' => $user['pubkey'],
857 'xmpp' => $profile['xmpp'],
858 'matrix' => $profile['matrix'],
859 'network' => Protocol::DFRN,
861 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
862 'nurl' => Strings::normaliseLink($url),
863 'uri-id' => ItemURI::getIdByURI($url),
864 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
865 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
866 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
867 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
868 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
871 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
872 if (DBA::isResult($avatar)) {
873 if ($update_avatar) {
874 $fields['avatar-date'] = DateTimeFormat::utcNow();
877 // Creating the path to the avatar, beginning with the file suffix
878 $types = Images::supportedTypes();
879 if (isset($types[$avatar['type']])) {
880 $file_suffix = $types[$avatar['type']];
883 // We are adding a timestamp value so that other systems won't use cached content
884 $timestamp = strtotime($fields['avatar-date']);
886 $prefix = DI::baseUrl() . '/photo/' . $avatar['resource-id'] . '-';
887 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
889 $fields['photo'] = $prefix . '4' . $suffix;
890 $fields['thumb'] = $prefix . '5' . $suffix;
891 $fields['micro'] = $prefix . '6' . $suffix;
893 // We hadn't found a photo entry, so we use the default avatar
894 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
895 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
896 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
899 $fields['avatar'] = User::getAvatarUrl($user);
900 $fields['header'] = User::getBannerUrl($user);
901 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
902 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
903 $fields['unsearchable'] = !$profile['net-publish'];
904 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
908 foreach ($fields as $field => $content) {
909 if ($self[$field] != $content) {
915 if ($fields['name'] != $self['name']) {
916 $fields['name-date'] = DateTimeFormat::utcNow();
918 $fields['updated'] = DateTimeFormat::utcNow();
919 self::update($fields, ['id' => $self['id']]);
921 // Update the other contacts as well
922 unset($fields['prvkey']);
923 $fields['self'] = false;
924 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
926 // Update the profile
928 'photo' => User::getAvatarUrl($user),
929 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
932 DBA::update('profile', $fields, ['uid' => $uid]);
939 * Marks a contact for removal
941 * @param int $id contact id
943 * @throws HTTPException\InternalServerErrorException
945 public static function remove(int $id)
947 // We want just to make sure that we don't delete our "self" contact
948 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
949 if (!DBA::isResult($contact)) {
953 DBA::delete('account-user', ['id' => $id]);
955 self::clearFollowerFollowingEndpointCache($contact['uid']);
957 // Archive the contact
958 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
960 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
961 Avatar::deleteCache($contact);
964 // Delete it in the background
965 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
969 * Unfollow the remote contact
971 * @param array $contact Target user-specific contact (uid != 0) array
973 * @throws HTTPException\InternalServerErrorException
974 * @throws \ImagickException
976 public static function unfollow(array $contact): void
978 if (empty($contact['network'])) {
979 throw new \InvalidArgumentException('Empty network in contact array');
982 if (empty($contact['uid'])) {
983 throw new \InvalidArgumentException('Unexpected public contact record');
986 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
987 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
988 if (!empty($cdata['public'])) {
989 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
993 self::removeSharer($contact);
997 * Revoke follow privileges of the remote user contact
999 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
1001 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
1003 * @throws HTTPException\InternalServerErrorException
1004 * @throws \ImagickException
1006 public static function revokeFollow(array $contact): void
1008 if (empty($contact['network'])) {
1009 throw new \InvalidArgumentException('Empty network in contact array');
1012 if (empty($contact['uid'])) {
1013 throw new \InvalidArgumentException('Unexpected public contact record');
1016 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
1017 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1018 if (!empty($cdata['public'])) {
1019 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1023 self::removeFollower($contact);
1027 * Completely severs a relationship with a contact
1029 * @param array $contact User-specific contact (uid != 0) array
1031 * @throws HTTPException\InternalServerErrorException
1032 * @throws \ImagickException
1034 public static function terminateFriendship(array $contact)
1036 if (empty($contact['network'])) {
1037 throw new \InvalidArgumentException('Empty network in contact array');
1040 if (empty($contact['uid'])) {
1041 throw new \InvalidArgumentException('Unexpected public contact record');
1044 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1046 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1047 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1050 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1051 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1054 self::remove($contact['id']);
1057 private static function clearFollowerFollowingEndpointCache(int $uid)
1063 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1064 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1068 * Marks a contact for archival after a communication issue delay
1070 * Contact has refused to recognise us as a friend. We will start a countdown.
1071 * If they still don't recognise us in 32 days, the relationship is over,
1072 * and we won't waste any more time trying to communicate with them.
1073 * This provides for the possibility that their database is temporarily messed
1074 * up or some other transient event and that there's a possibility we could recover from it.
1076 * @param array $contact contact to mark for archival
1078 * @throws HTTPException\InternalServerErrorException
1080 public static function markForArchival(array $contact)
1082 if (!isset($contact['url']) && !empty($contact['id'])) {
1083 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1084 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1085 if (!DBA::isResult($contact)) {
1088 } elseif (!isset($contact['url'])) {
1089 Logger::info('Empty contact', ['contact' => $contact]);
1092 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1094 // Contact already archived or "self" contact? => nothing to do
1095 if ($contact['archive'] || $contact['self']) {
1099 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1100 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1101 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1104 * We really should send a notification to the owner after 2-3 weeks
1105 * so they won't be surprised when the contact vanishes and can take
1106 * remedial action if this was a serious mistake or glitch
1109 /// @todo Check for contact vitality via probing
1110 $archival_days = DI::config()->get('system', 'archival_days', 32);
1112 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1113 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1114 /* Relationship is really truly dead. archive them rather than
1115 * delete, though if the owner tries to unarchive them we'll start
1116 * the whole process over again.
1118 self::update(['archive' => true], ['id' => $contact['id']]);
1119 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1125 * Cancels the archival countdown
1127 * @see Contact::markForArchival()
1129 * @param array $contact contact to be unmarked for archival
1131 * @throws \Exception
1133 public static function unmarkForArchival(array $contact)
1135 // Always unarchive the relay contact entry
1136 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1137 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1138 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1139 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1140 self::update($fields, $condition);
1144 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1145 $exists = DBA::exists('contact', $condition);
1147 // We don't need to update, we never marked this contact for archival
1152 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1154 if (!isset($contact['url']) && !empty($contact['id'])) {
1155 $fields = ['id', 'url', 'batch'];
1156 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1157 if (!DBA::isResult($contact)) {
1162 // It's a miracle. Our dead contact has inexplicably come back to life.
1163 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1164 self::update($fields, ['id' => $contact['id']]);
1165 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1169 * Returns the data array for the photo menu of a given contact
1171 * @param array $contact contact
1172 * @param int $uid Visitor user id
1174 * @throws HTTPException\InternalServerErrorException
1175 * @throws \ImagickException
1177 public static function photoMenu(array $contact, int $uid): array
1179 // Anonymous visitor
1181 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1189 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1190 $profile_link = 'contact/redir/' . $contact['id'];
1191 $status_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
1192 $photos_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
1193 $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
1195 $profile_link = $contact['url'];
1198 if ($profile_link === 'mailbox') {
1202 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1203 $pm_url = 'message/new/' . $contact['id'];
1206 $contact_url = 'contact/' . $contact['id'];
1208 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1209 $mention_label = DI::l10n()->t('Post to group');
1210 $mention_url = 'compose/0?body=!' . $contact['addr'];
1211 $network_label = DI::l10n()->t('View group');
1212 $network_url = 'network/group/' . $contact['id'];
1214 $mention_label = DI::l10n()->t('Mention');
1215 $mention_url = 'compose/0?body=@' . $contact['addr'];
1216 $network_label = DI::l10n()->t('Network Posts');
1217 $network_url = 'contact/' . $contact['id'] . '/conversations';
1221 $unfollow_link = '';
1222 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1223 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1224 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1225 } elseif (!$contact['pending']) {
1226 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1232 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1236 if (empty($contact['uid'])) {
1238 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1239 'network' => [$network_label, $network_url, false],
1240 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1241 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1242 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1243 'mention' => [$mention_label, $mention_url, false],
1247 'status' => [DI::l10n()->t('View Status'), $status_link, true],
1248 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1249 'photos' => [DI::l10n()->t('View Photos'), $photos_link, true],
1250 'network' => [$network_label, $network_url, false],
1251 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1252 'pm' => [DI::l10n()->t('Send PM'), $pm_url, false],
1253 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1254 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1255 'mention' => [$mention_label, $mention_url, false],
1258 if (!empty($contact['pending'])) {
1260 $intro = DI::intro()->selectForContact($contact['id']);
1261 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1262 } catch (IntroductionNotFoundException $exception) {
1263 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1268 $args = ['contact' => $contact, 'menu' => &$menu];
1270 Hook::callAll('contact_photo_menu', $args);
1272 $menucondensed = [];
1274 foreach ($menu as $menuname => $menuitem) {
1275 if ($menuitem[1] != '') {
1276 $menucondensed[$menuname] = $menuitem;
1280 return $menucondensed;
1284 * Fetch the contact id for a given URL and user
1286 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1287 * `addr` or `alias`.
1289 * If there's no record and we aren't looking for a public contact, we quit.
1290 * If there's one, we check that it isn't time to update the picture else we
1291 * directly return the found contact id.
1293 * Second, we probe the provided $url whether it's http://server.tld/profile or
1294 * nick@server.tld. We quit if we can't get any info back.
1296 * Third, we create the contact record if it doesn't exist
1298 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1299 * if there's any updates
1301 * @param string $url Contact URL
1302 * @param integer $uid The user id for the contact (0 = public contact)
1303 * @param boolean $update true = always update, false = never update, null = update when not found
1304 * @param array $default Default value for creating the contact when everything else fails
1306 * @return integer Contact ID
1307 * @throws HTTPException\InternalServerErrorException
1308 * @throws \ImagickException
1310 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1315 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1319 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
1321 if (!empty($contact)) {
1322 $contact_id = $contact['id'];
1324 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
1326 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1328 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
1329 } catch (\InvalidArgumentException $e) {
1330 Logger::notice($e->getMessage(), ['contact' => $contact]);
1334 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1335 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1338 } elseif ($uid != 0) {
1339 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1341 } elseif (empty($default) && !is_null($update) && !$update) {
1342 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1348 if (empty($default['network']) || $update) {
1349 $data = Probe::uri($url, '', $uid);
1351 // Take the default values when probing failed
1352 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1353 $data = array_merge($data, $default);
1355 } elseif (!empty($default['network'])) {
1359 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1360 // Fetch data for the public contact via the first found personal contact
1361 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1363 'name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1364 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1365 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'
1368 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1369 if (!DBA::isResult($personal_contact)) {
1370 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1373 if (DBA::isResult($personal_contact)) {
1374 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact]);
1375 $data = $personal_contact;
1376 $data['photo'] = $personal_contact['avatar'];
1377 $data['account-type'] = $personal_contact['contact-type'];
1378 $data['hide'] = $personal_contact['unsearchable'];
1379 unset($data['avatar']);
1380 unset($data['contact-type']);
1381 unset($data['unsearchable']);
1385 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1386 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update]);
1390 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1391 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1396 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1397 if (!empty($data['alias'])) {
1398 $urls[] = Strings::normaliseLink($data['alias']);
1400 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1401 if (!empty($contact['id'])) {
1402 $contact_id = $contact['id'];
1403 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1408 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1411 'url' => $data['url'],
1412 'baseurl' => $data['baseurl'] ?? '',
1413 'nurl' => Strings::normaliseLink($data['url']),
1414 'network' => $data['network'],
1415 'created' => DateTimeFormat::utcNow(),
1416 'rel' => self::SHARING,
1423 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1425 // Before inserting we do check if the entry does exist now.
1426 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1427 if (DBA::isResult($contact)) {
1428 $contact_id = $contact['id'];
1429 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1431 $contact_id = self::insert($fields);
1433 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1438 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1442 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1445 if ($data['network'] == Protocol::DIASPORA) {
1447 DI::dsprContact()->updateFromProbeArray($data);
1448 } catch (HTTPException\NotFoundException $e) {
1449 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1450 } catch (\InvalidArgumentException $e) {
1451 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1453 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1455 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1456 } catch (HTTPException\NotFoundException $e) {
1457 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1458 } catch (\InvalidArgumentException $e) {
1459 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1463 self::updateFromProbeArray($contact_id, $data);
1465 // Don't return a number for a deleted account
1466 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1467 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1475 * Checks if the contact is archived
1477 * @param int $cid contact id
1479 * @return boolean Is the contact archived?
1480 * @throws HTTPException\InternalServerErrorException
1482 public static function isArchived(int $cid): bool
1488 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1489 if (!DBA::isResult($contact)) {
1493 if ($contact['archive']) {
1497 // Check status of ActivityPub endpoints
1498 $apcontact = APContact::getByURL($contact['url'], false);
1499 if (!empty($apcontact)) {
1500 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1504 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1509 // Check status of Diaspora endpoints
1510 if (!empty($contact['batch'])) {
1511 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1512 return DBA::exists('contact', $condition);
1519 * Checks if the contact is blocked
1521 * @param int $cid contact id
1522 * @return boolean Is the contact blocked?
1523 * @throws HTTPException\InternalServerErrorException
1525 public static function isBlocked(int $cid): bool
1531 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1532 if (!DBA::isResult($blocked)) {
1536 if (Network::isUrlBlocked($blocked['url'])) {
1540 return (bool) $blocked['blocked'];
1544 * Checks if the contact is hidden
1546 * @param int $cid contact id
1547 * @return boolean Is the contact hidden?
1548 * @throws \Exception
1550 public static function isHidden(int $cid): bool
1556 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1557 if (!DBA::isResult($hidden)) {
1560 return (bool) $hidden['hidden'];
1564 * Returns posts from a given contact url
1566 * @param string $contact_url Contact URL
1567 * @param bool $thread_mode
1568 * @param int $update Update mode
1569 * @param int $parent Item parent ID for the update mode
1570 * @param bool $only_media Only display media content
1571 * @return string posts in HTML
1572 * @throws \Exception
1574 public static function getPostsFromUrl(string $contact_url, int $uid, bool $only_media = false): string
1576 return self::getPostsFromId(self::getIdForURL($contact_url), $uid, $only_media);
1580 * Returns posts from a given contact id
1582 * @param int $cid Contact ID
1583 * @param bool $only_media Only display media content
1584 * @return string posts in HTML
1585 * @throws \Exception
1587 public static function getPostsFromId(int $cid, int $uid, bool $only_media = false, string $last_created = null): string
1589 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1590 if (!DBA::isResult($contact)) {
1594 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1595 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))", $uid];
1597 $condition = ["`uid` = ?", $uid];
1600 $contact_field = ((($contact['contact-type'] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1602 $condition = DBA::mergeConditions($condition, ["`$contact_field` = ? AND `gravity` IN (?, ?)", $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]);
1604 if (!empty($last_created)) {
1605 $condition = DBA::mergeConditions($condition, ["`created` < ?", $last_created]);
1609 $condition = DBA::mergeConditions($condition, [
1610 "`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1611 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO
1615 if (DI::mode()->isMobile()) {
1616 $itemsPerPage = DI::pConfig()->get($uid, 'system', 'itemspage_mobile_network', DI::config()->get('system', 'itemspage_network_mobile'));
1618 $itemsPerPage = DI::pConfig()->get($uid, 'system', 'itemspage_network', DI::config()->get('system', 'itemspage_network'));
1621 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1623 $params = ['order' => ['created' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1625 if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) {
1626 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1627 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1632 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1633 $items = Post::toArray(Post::selectForUser($uid, $fields, $condition, $params));
1635 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS);
1637 if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) {
1638 $o .= HTML::scrollLoader();
1640 $o .= $pager->renderMinimal(count($items));
1647 * Returns threads from a given contact id
1649 * @param int $cid Contact ID
1650 * @param int $update Update mode
1651 * @param int $parent Item parent ID for the update mode
1652 * @return string posts in HTML
1653 * @throws \Exception
1655 public static function getThreadsFromId(int $cid, int $uid, int $update = 0, int $parent = 0, string $last_created = ''): string
1657 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1658 if (!DBA::isResult($contact)) {
1662 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1663 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))", $uid];
1665 $condition = ["`uid` = ?", $uid];
1668 if (!empty($parent)) {
1669 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1670 } elseif (!empty($last_created)) {
1671 $condition = DBA::mergeConditions($condition, ["`created` < ?", $last_created]);
1674 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1676 if (DI::mode()->isMobile()) {
1677 $itemsPerPage = DI::pConfig()->get($uid, 'system', 'itemspage_mobile_network', DI::config()->get('system', 'itemspage_network_mobile'));
1679 $itemsPerPage = DI::pConfig()->get($uid, 'system', 'itemspage_network', DI::config()->get('system', 'itemspage_network'));
1682 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1684 if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) {
1685 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1686 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1691 $condition1 = DBA::mergeConditions($condition, ["`$contact_field` = ? AND `gravity` = ?", $cid, Item::GRAVITY_PARENT]);
1693 $condition2 = DBA::mergeConditions($condition, [
1694 "`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`",
1695 $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA
1698 $sql1 = "SELECT `uri-id`, `created` FROM `post-thread-user-view` WHERE " . array_shift($condition1);
1699 $sql2 = "SELECT `thr-parent-id` AS `uri-id`, `created` FROM `post-user-view` WHERE " . array_shift($condition2);
1701 $union = array_merge($condition1, $condition2);
1702 $sql = $sql1 . " UNION " . $sql2;
1704 $sql .= " ORDER BY `created` DESC LIMIT ?, ?";
1705 $union = array_merge($union, [$pager->getStart(), $pager->getItemsPerPage()]);
1706 $items = Post::toArray(DBA::p($sql, $union));
1708 if (empty($last_created) && ($pager->getStart() == 0)) {
1709 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'created'];
1710 $pinned = Post\Collection::selectToArrayForContact($cid, Post\Collection::FEATURED, $fields);
1711 $items = array_merge($items, $pinned);
1714 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_created', $uid);
1717 if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) {
1718 $o .= HTML::scrollLoader();
1720 $o .= $pager->renderMinimal(count($items));
1728 * Returns the account type name
1730 * The function can be called with either the user or the contact array
1732 * @param int $type type of contact or account
1735 public static function getAccountType(int $type): string
1738 case self::TYPE_ORGANISATION:
1739 $account_type = DI::l10n()->t("Organisation");
1742 case self::TYPE_NEWS:
1743 $account_type = DI::l10n()->t('News');
1746 case self::TYPE_COMMUNITY:
1747 $account_type = DI::l10n()->t("Group");
1755 return $account_type;
1761 * @param int $cid Contact id to block
1762 * @param string $reason Block reason
1763 * @return bool Whether it was successful
1765 public static function block(int $cid, string $reason = null): bool
1767 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1773 * Unblocks a contact
1775 * @param int $cid Contact id to unblock
1776 * @return bool Whether it was successful
1778 public static function unblock(int $cid): bool
1780 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1786 * Ensure that cached avatar exist
1788 * @param integer $cid Contact id
1790 public static function checkAvatarCache(int $cid)
1792 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1793 if (!DBA::isResult($contact)) {
1797 if (Network::isLocalLink($contact['url'])) {
1801 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1802 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1803 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1804 self::updateAvatar($cid, $contact['avatar'], true);
1807 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1808 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1809 self::updateAvatar($cid, $contact['avatar'], true);
1811 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1812 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1813 self::updateAvatar($cid, $contact['avatar'], true);
1819 * Return the photo path for a given contact array in the given size
1821 * @param array $contact contact array
1822 * @param string $size Size of the avatar picture
1823 * @param bool $no_update Don't perform an update if no cached avatar was found
1824 * @return string photo path
1826 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1828 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1830 if (DI::config()->get('system', 'avatar_cache')) {
1832 case Proxy::SIZE_MICRO:
1833 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1834 return $contact['micro'];
1837 case Proxy::SIZE_THUMB:
1838 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1839 return $contact['thumb'];
1842 case Proxy::SIZE_SMALL:
1843 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1844 return $contact['photo'];
1850 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1854 * Return the photo path for a given contact array
1856 * @param array $contact Contact array
1857 * @param bool $no_update Don't perform an update if no cached avatar was found
1858 * @return string photo path
1860 public static function getPhoto(array $contact, bool $no_update = false): string
1862 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1866 * Return the photo path (thumb size) for a given contact array
1868 * @param array $contact Contact array
1869 * @param bool $no_update Don't perform an update if no cached avatar was found
1870 * @return string photo path
1872 public static function getThumb(array $contact, bool $no_update = false): string
1874 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1878 * Return the photo path (micro size) for a given contact array
1880 * @param array $contact Contact array
1881 * @param bool $no_update Don't perform an update if no cached avatar was found
1882 * @return string photo path
1884 public static function getMicro(array $contact, bool $no_update = false): string
1886 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1890 * Check the given contact array for avatar cache fields
1892 * @param array $contact
1893 * @param bool $no_update Don't perform an update if no cached avatar was found
1894 * @return array contact array with avatar cache fields
1896 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1899 $contact_fields = [];
1900 $fields = ['photo', 'thumb', 'micro'];
1901 foreach ($fields as $field) {
1902 if (isset($contact[$field])) {
1903 $contact_fields[] = $field;
1905 if (isset($contact[$field]) && empty($contact[$field])) {
1910 if (!$update || $no_update) {
1914 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1916 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1917 self::updateAvatar($contact['id'], $contact['avatar'], true);
1919 $new_contact = self::getById($contact['id'], $contact_fields);
1920 if (DBA::isResult($new_contact)) {
1921 // We only update the cache fields
1922 $contact = array_merge($contact, $new_contact);
1924 } elseif ($local && !empty($contact['avatar'])) {
1928 /// add the default avatars if the fields aren't filled
1929 if (isset($contact['photo']) && empty($contact['photo'])) {
1930 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1932 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1933 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1935 if (isset($contact['micro']) && empty($contact['micro'])) {
1936 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1943 * Fetch the default header for the given contact
1945 * @param array $contact contact array
1946 * @return string avatar URL
1948 public static function getDefaultHeader(array $contact): string
1950 if (!empty($contact['header'])) {
1951 return $contact['header'];
1954 if (!empty($contact['gsid'])) {
1955 // Use default banners for certain platforms
1956 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1957 $platform = strtolower($gserver['platform'] ?? '');
1962 switch ($platform) {
1965 $header = DI::baseUrl() . (new Header(DI::config()))->getMastodonBannerPath();
1970 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1971 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1972 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1974 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1978 * Use a random picture.
1979 * The service provides random pictures from Unsplash.
1980 * @license https://unsplash.com/license
1982 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1990 * Fetch the default avatar for the given contact and size
1992 * @param array $contact contact array
1993 * @param string $size Size of the avatar picture
1994 * @return string avatar URL
1996 public static function getDefaultAvatar(array $contact, string $size): string
1999 case Proxy::SIZE_MICRO:
2000 $avatar['size'] = 48;
2001 $default = self::DEFAULT_AVATAR_MICRO;
2004 case Proxy::SIZE_THUMB:
2005 $avatar['size'] = 80;
2006 $default = self::DEFAULT_AVATAR_THUMB;
2009 case Proxy::SIZE_SMALL:
2011 $avatar['size'] = 300;
2012 $default = self::DEFAULT_AVATAR_PHOTO;
2016 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
2018 $type = Contact::TYPE_PERSON;
2020 if (!empty($contact['id'])) {
2021 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
2022 $platform = $account['platform'] ?? '';
2023 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
2026 if (empty($platform) && !empty($contact['uri-id'])) {
2027 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
2028 $platform = $account['platform'] ?? '';
2029 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
2032 switch ($platform) {
2036 * @license GNU Affero General Public License v3.0
2037 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
2039 $default = '/images/default/corgidon.png';
2045 * @license GNU Affero General Public License v3.0
2046 * @link https://github.com/diaspora/diaspora/
2048 $default = '/images/default/diaspora.png';
2054 * @license GNU Affero General Public License v3.0
2055 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
2057 $default = '/images/default/gotosocial.svg';
2063 * @license GNU Affero General Public License v3.0
2064 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
2066 $default = '/images/default/hometown.png';
2072 * @license GNU Affero General Public License v3.0
2073 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
2075 $default = '/images/default/koyuspace.png';
2083 * @license GNU Affero General Public License v3.0
2084 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2086 $default = '/images/default/mastodon.png';
2090 if ($type == Contact::TYPE_COMMUNITY) {
2093 * @license GNU Affero General Public License v3.0
2094 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2096 $default = '/images/default/peertube-channel.png';
2100 * @license GNU Affero General Public License v3.0
2101 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2103 $default = '/images/default/peertube-account.png';
2110 * @license GNU Affero General Public License v3.0
2111 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2113 $default = '/images/default/pleroma.png';
2119 * @license GNU Affero General Public License v3.0
2120 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2122 $default = '/images/default/plume.png';
2125 return DI::baseUrl() . $default;
2128 if (!empty($contact['xmpp'])) {
2129 $avatar['email'] = $contact['xmpp'];
2130 } elseif (!empty($contact['addr'])) {
2131 $avatar['email'] = $contact['addr'];
2132 } elseif (!empty($contact['url'])) {
2133 $avatar['email'] = $contact['url'];
2135 return DI::baseUrl() . $default;
2138 $avatar['url'] = '';
2139 $avatar['success'] = false;
2141 Hook::callAll('avatar_lookup', $avatar);
2143 if ($avatar['success'] && !empty($avatar['url'])) {
2144 return $avatar['url'];
2147 return DI::baseUrl() . $default;
2151 * Get avatar link for given contact id
2153 * @param integer $cid contact id
2154 * @param string $size One of the Proxy::SIZE_* constants
2155 * @param string $updated Contact update date
2156 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2157 * @return string avatar link
2159 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2161 // We have to fetch the "updated" variable when it wasn't provided
2162 // The parameter can be provided to improve performance
2163 if (empty($updated)) {
2164 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2165 $updated = $account['updated'] ?? '';
2166 $guid = $account['guid'] ?? '';
2169 $guid = urlencode($guid);
2171 $url = DI::baseUrl() . '/photo/contact/';
2173 case Proxy::SIZE_MICRO:
2174 $url .= Proxy::PIXEL_MICRO . '/';
2176 case Proxy::SIZE_THUMB:
2177 $url .= Proxy::PIXEL_THUMB . '/';
2179 case Proxy::SIZE_SMALL:
2180 $url .= Proxy::PIXEL_SMALL . '/';
2182 case Proxy::SIZE_MEDIUM:
2183 $url .= Proxy::PIXEL_MEDIUM . '/';
2185 case Proxy::SIZE_LARGE:
2186 $url .= Proxy::PIXEL_LARGE . '/';
2191 $query_params['ts'] = strtotime($updated);
2194 $query_params['static'] = true;
2197 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2201 * Get avatar link for given contact URL
2203 * @param string $url contact url
2204 * @param integer $uid user id
2205 * @param string $size One of the Proxy::SIZE_* constants
2206 * @return string avatar link
2208 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2211 "`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2212 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0
2214 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2215 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2219 * Get header link for given contact id
2221 * @param integer $cid contact id
2222 * @param string $size One of the Proxy::SIZE_* constants
2223 * @param string $updated Contact update date
2224 * @param bool $static If "true" a parameter is added to convert the header to a static one
2225 * @return string header link
2227 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2229 // We have to fetch the "updated" variable when it wasn't provided
2230 // The parameter can be provided to improve performance
2231 if (empty($updated) || empty($guid)) {
2232 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2233 $updated = $account['updated'] ?? '';
2234 $guid = $account['guid'] ?? '';
2237 $guid = urlencode($guid);
2239 $url = DI::baseUrl() . '/photo/header/';
2241 case Proxy::SIZE_MICRO:
2242 $url .= Proxy::PIXEL_MICRO . '/';
2244 case Proxy::SIZE_THUMB:
2245 $url .= Proxy::PIXEL_THUMB . '/';
2247 case Proxy::SIZE_SMALL:
2248 $url .= Proxy::PIXEL_SMALL . '/';
2250 case Proxy::SIZE_MEDIUM:
2251 $url .= Proxy::PIXEL_MEDIUM . '/';
2253 case Proxy::SIZE_LARGE:
2254 $url .= Proxy::PIXEL_LARGE . '/';
2260 $query_params['ts'] = strtotime($updated);
2263 $query_params['static'] = true;
2266 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2270 * Updates the avatar links in a contact only if needed
2272 * @param int $cid Contact id
2273 * @param string $avatar Link to avatar picture
2274 * @param bool $force force picture update
2275 * @param bool $create_cache Enforces the creation of cached avatar fields
2278 * @throws HTTPException\InternalServerErrorException
2279 * @throws HTTPException\NotFoundException
2280 * @throws \ImagickException
2282 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2284 $contact = DBA::selectFirst(
2286 ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2287 ['id' => $cid, 'self' => false]
2289 if (!DBA::isResult($contact)) {
2293 if (!Network::isValidHttpUrl($avatar)) {
2294 Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
2298 $uid = $contact['uid'];
2300 // Only update the cached photo links of public contacts when they already are cached
2301 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2302 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2303 $update_fields = ['avatar' => $avatar];
2304 if (!Network::isLocalLink($avatar)) {
2306 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2308 $img_str = $fetchResult->getBodyString();
2309 if (!empty($img_str)) {
2310 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2311 if ($image->isValid()) {
2312 $update_fields['blurhash'] = $image->getBlurHash();
2317 } catch (\Exception $exception) {
2318 Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
2321 } elseif (!empty($contact['blurhash'])) {
2322 $update_fields['blurhash'] = null;
2327 self::update($update_fields, ['id' => $cid]);
2328 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2333 // User contacts use are updated through the public contacts
2334 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2335 $pcid = self::getIdForURL($contact['url'], 0, false);
2336 if (!empty($pcid)) {
2337 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2338 self::updateAvatar($pcid, $avatar, $force, true);
2343 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2345 if ($default_avatar) {
2346 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2349 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2351 // Local contact avatars don't need to be cached
2352 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2353 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2356 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2357 if (Avatar::deleteCache($contact)) {
2361 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2363 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2365 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2366 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)
2368 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2371 // Use the data from the self account
2372 if (empty($fields)) {
2373 $local_uid = User::getIdForURL($contact['url']);
2374 if (!empty($local_uid)) {
2375 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2376 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2380 if (empty($fields)) {
2381 $update = ($contact['avatar'] != $avatar) || $force;
2385 $contact['photo'] ?? '',
2386 $contact['thumb'] ?? '',
2387 $contact['micro'] ?? '',
2390 foreach ($data as $image_uri) {
2391 $image_rid = Photo::ridFromURI($image_uri);
2392 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2393 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2400 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2402 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2403 $update = !empty($fields);
2404 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2410 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2413 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2414 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2415 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2424 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2425 // Collect all user contacts of the given public contact
2426 $personal_contacts = DBA::select(
2429 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]
2431 while ($personal_contact = DBA::fetch($personal_contacts)) {
2432 $cids[] = $personal_contact['id'];
2433 $uids[] = $personal_contact['uid'];
2435 DBA::close($personal_contacts);
2437 if (!empty($cids)) {
2438 // Delete possibly existing cached user contact avatars
2439 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2445 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2446 self::update($fields, ['id' => $cids]);
2449 public static function deleteContactByUrl(string $url)
2451 // Update contact data for all users
2452 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2453 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2454 while ($contact = DBA::fetch($contacts)) {
2455 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2456 self::remove($contact['id']);
2461 * Helper function for "updateFromProbe". Updates personal and public contact
2463 * @param integer $id contact id
2464 * @param integer $uid user id
2465 * @param integer $uri_id Uri-Id
2466 * @param string $url The profile URL of the contact
2467 * @param array $fields The fields that are updated
2469 * @throws \Exception
2471 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2473 if (!self::update($fields, ['id' => $id])) {
2474 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2478 self::setAccountUser($id, $uid, $uri_id, $url);
2480 // Archive or unarchive the contact.
2481 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2482 if (!DBA::isResult($contact)) {
2483 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2487 if (isset($fields['failed'])) {
2488 if ($fields['failed']) {
2489 self::markForArchival($contact);
2491 self::unmarkForArchival($contact);
2495 if ($contact['uid'] != 0) {
2499 // Update contact data for all users
2500 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2502 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2504 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
2505 $condition['network'][] = $contact['network'];
2508 self::update($fields, $condition);
2510 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2511 $condition['network'] = Protocol::OSTATUS;
2513 // If the contact failed, propagate the update fields to all contacts
2514 if (empty($fields['failed'])) {
2515 unset($fields['last-update']);
2516 unset($fields['success_update']);
2517 unset($fields['failure_update']);
2520 if (empty($fields)) {
2524 self::update($fields, $condition);
2528 * Create or update an "account-user" entry
2530 * @param integer $id
2531 * @param integer $uid
2532 * @param integer $uri_id
2533 * @param string $url
2536 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2538 if (empty($uri_id)) {
2542 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2543 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2544 if ($account_user['uid'] == $uid) {
2545 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2546 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2548 // This should never happen
2549 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]);
2553 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2554 if (!empty($account_user['id'])) {
2555 if ($account_user['id'] == $id) {
2556 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2558 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2559 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2560 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2563 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2564 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2565 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2566 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2568 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2573 * Remove duplicated contacts
2575 * @param string $nurl Normalised contact url
2576 * @param integer $uid User id
2578 * @throws \Exception
2580 public static function removeDuplicates(string $nurl, int $uid)
2582 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2583 $count = DBA::count('contact', $condition);
2588 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2589 if (!DBA::isResult($first_contact)) {
2590 // Shouldn't happen - so we handle it
2594 $first = $first_contact['id'];
2595 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2597 // Find all duplicates
2598 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2599 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2600 while ($duplicate = DBA::fetch($duplicates)) {
2601 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2605 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2607 DBA::close($duplicates);
2608 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2613 * Perform a contact update if the contact is outdated
2615 * @param integer $id contact id
2618 public static function updateByIdIfNeeded(int $id): bool
2620 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2621 if (empty($contact['url'])) {
2625 if (self::isLocal($contact['url'])) {
2629 $stamp = (float)microtime(true);
2630 self::updateFromProbe($id);
2631 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url']]);
2636 * Perform a contact update if the contact is outdated
2638 * @param string $url contact url
2641 public static function updateByUrlIfNeeded(string $url): bool
2643 $id = self::getIdForURL($url, 0, false);
2645 return self::updateByIdIfNeeded($id);
2647 return (bool)self::getIdForURL($url);
2651 * Updates contact record by provided id and optional network
2653 * @param integer $id contact id
2654 * @param string $network Optional network we are probing for
2656 * @throws HTTPException\InternalServerErrorException
2657 * @throws \ImagickException
2659 public static function updateFromProbe(int $id, string $network = ''): bool
2661 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2662 if (!DBA::isResult($contact)) {
2666 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2668 if ($data['network'] == Protocol::DIASPORA) {
2670 DI::dsprContact()->updateFromProbeArray($data);
2671 } catch (HTTPException\NotFoundException $e) {
2672 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2673 } catch (\InvalidArgumentException $e) {
2674 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2676 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2678 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2679 } catch (HTTPException\NotFoundException $e) {
2680 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2681 } catch (\InvalidArgumentException $e) {
2682 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2686 return self::updateFromProbeArray($id, $data);
2690 * Checks if the given contact has got local data
2693 * @param array $contact
2697 private static function hasLocalData(int $id, array $contact): bool
2699 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2700 // User contacts with the same uri-id exist
2702 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2703 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2706 if (DBA::exists('post-tag', ['cid' => $id])) {
2707 // Is tagged in a post
2710 if (DBA::exists('user-contact', ['cid' => $id])) {
2711 // Has got user-contact data
2714 if (Post::exists(['author-id' => $id])) {
2715 // Posts with this author exist
2718 if (Post::exists(['owner-id' => $id])) {
2719 // Posts with this owner exist
2722 if (Post::exists(['causer-id' => $id])) {
2723 // Posts with this causer exist
2726 // We don't have got this contact locally
2731 * Updates contact record by provided id and probed data
2733 * @param integer $id contact id
2734 * @param array $ret Probed data
2736 * @throws HTTPException\InternalServerErrorException
2737 * @throws \ImagickException
2739 private static function updateFromProbeArray(int $id, array $ret): bool
2742 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2743 This will reliably kill your communication with old Friendica contacts.
2746 // These fields aren't updated by this routine:
2750 'uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2751 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2752 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2753 'created', 'last-update'
2755 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2756 if (!DBA::isResult($contact)) {
2760 if (self::isLocal($ret['url'])) {
2761 if ($contact['uid'] == 0) {
2762 Logger::info('Local contacts are not updated here.');
2764 self::updateFromPublicContact($id, $contact);
2769 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2770 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2773 // Delete all contacts with the same URL
2774 self::deleteContactByUrl($ret['url']);
2778 $has_local_data = self::hasLocalData($id, $contact);
2780 $uid = $contact['uid'];
2781 unset($contact['uid']);
2783 $uriid = $contact['uri-id'];
2784 unset($contact['uri-id']);
2786 $pubkey = $contact['pubkey'];
2787 unset($contact['pubkey']);
2789 $created = $contact['created'];
2790 unset($contact['created']);
2792 $last_update = $contact['last-update'];
2793 unset($contact['last-update']);
2795 $contact['photo'] = $contact['avatar'];
2796 unset($contact['avatar']);
2798 $updated = DateTimeFormat::utcNow();
2800 if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
2801 // Periodical checks are only done on federated contacts
2802 $failed_next_update = null;
2803 $success_next_update = null;
2804 } elseif ($has_local_data) {
2805 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2806 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2807 } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
2808 $failed_next_update = DateTimeFormat::utc('now +6 month');
2809 $success_next_update = DateTimeFormat::utc('now +1 month');
2811 // We don't check connector networks very often to not run into API rate limits
2812 $failed_next_update = DateTimeFormat::utc('now +12 month');
2813 $success_next_update = DateTimeFormat::utc('now +12 month');
2816 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2817 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2818 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]);
2822 // We must not try to update relay contacts via probe. They are no real contacts.
2823 // We check after the probing to be able to correct falsely detected contact types.
2824 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2825 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))
2827 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]);
2828 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2832 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2833 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2834 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]);
2838 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2839 $cid = self::getIdForURL($ret['url'], 0, false);
2840 if (!empty($cid) && ($cid != $id)) {
2841 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2842 return self::updateFromProbeArray($cid, $ret);
2846 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2847 $ret['unsearchable'] = $ret['hide'];
2850 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2851 $ret['forum'] = false;
2852 $ret['prv'] = false;
2853 $ret['contact-type'] = $ret['account-type'];
2854 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2855 $ret['forum'] = (bool)!$ret['manually-approve'];
2856 $ret['prv'] = (bool)!$ret['forum'];
2860 $new_pubkey = $ret['pubkey'] ?? '';
2862 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2863 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2864 $apcontact = APContact::getByURL($ret['url'], false);
2865 if (!empty($apcontact['featured'])) {
2866 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2870 $ret['last-item'] = Probe::getLastUpdate($ret);
2871 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item']]);
2875 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? '');
2877 // make sure to not overwrite existing values with blank entries except some technical fields
2878 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2879 foreach ($ret as $key => $val) {
2880 if (!array_key_exists($key, $contact)) {
2882 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2883 $ret[$key] = $contact[$key];
2884 } elseif ($ret[$key] != $contact[$key]) {
2889 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2892 unset($ret['last-item']);
2895 if (empty($uriid)) {
2899 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2900 self::updateAvatar($id, $ret['photo'], $update);
2904 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]);
2906 if (Contact\Relation::isDiscoverable($ret['url'])) {
2907 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2910 // Update the public contact
2912 $contact = self::getByURL($ret['url'], false, ['id']);
2913 if (!empty($contact['id'])) {
2914 self::updateFromProbeArray($contact['id'], $ret);
2921 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2922 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2923 $ret['updated'] = $updated;
2924 $ret['failed'] = false;
2925 $ret['next-update'] = $success_next_update;
2926 $ret['local-data'] = $has_local_data;
2928 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2929 if (empty($pubkey) && !empty($new_pubkey)) {
2930 $ret['pubkey'] = $new_pubkey;
2933 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2934 $ret['uri-date'] = $updated;
2937 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2938 $ret['name-date'] = $updated;
2941 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2942 $ret['last-update'] = $updated;
2943 $ret['success_update'] = $updated;
2946 unset($ret['photo']);
2948 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2950 if (Contact\Relation::isDiscoverable($ret['url'])) {
2951 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2957 private static function updateFromPublicContact(int $id, array $contact)
2959 $public = self::getByURL($contact['url'], false);
2963 foreach ($contact as $field => $value) {
2964 if ($field == 'uid') {
2967 if ($public[$field] != $value) {
2968 $fields[$field] = $public[$field];
2971 if (!empty($fields)) {
2972 self::update($fields, ['id' => $id, 'self' => false]);
2973 Logger::info('Updating local contact', ['id' => $id]);
2978 * Updates contact record by provided URL
2980 * @param integer $url contact url
2981 * @return integer Contact id
2982 * @throws HTTPException\InternalServerErrorException
2983 * @throws \ImagickException
2985 public static function updateFromProbeByURL(string $url): int
2987 $id = self::getIdForURL($url);
2993 self::updateFromProbe($id);
2999 * Detects the communication protocol for a given contact url.
3000 * This is used to detect Friendica contacts that we can communicate via AP.
3002 * @param string $url contact url
3003 * @param string $network Network of that contact
3004 * @return string with protocol
3006 public static function getProtocol(string $url, string $network): string
3008 if ($network != Protocol::DFRN) {
3012 $apcontact = APContact::getByURL($url);
3013 if (!empty($apcontact) && !empty($apcontact['generator'])) {
3014 return Protocol::ACTIVITYPUB;
3021 * Takes a $uid and a url/handle and adds a new contact
3023 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
3024 * dfrn_request page.
3026 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
3029 * $return['success'] boolean true if successful
3030 * $return['message'] error text if success is false.
3032 * Takes a $uid and a url/handle and adds a new contact
3034 * @param int $uid The user id the contact should be created for
3035 * @param string $url The profile URL of the contact
3036 * @param string $network
3038 * @throws HTTPException\InternalServerErrorException
3039 * @throws HTTPException\NotFoundException
3040 * @throws \ImagickException
3042 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
3044 $result = ['cid' => -1, 'success' => false, 'message' => ''];
3046 // remove ajax junk, e.g. Twitter
3047 $url = str_replace('/#!/', '/', $url);
3049 if (!Network::isUrlAllowed($url)) {
3050 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
3054 if (Network::isUrlBlocked($url)) {
3055 $result['message'] = DI::l10n()->t('Blocked domain');
3060 $result['message'] = DI::l10n()->t('Connect URL missing.');
3064 $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
3066 Hook::callAll('follow', $arr);
3069 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
3073 if (!empty($arr['contact']['name'])) {
3075 $ret = $arr['contact'];
3078 $ret = Probe::uri($url, $network, $uid);
3080 // Ensure that the public contact exists
3081 if ($ret['network'] != Protocol::PHANTOM) {
3082 self::getIdForURL($url);
3086 if (($network != '') && ($ret['network'] != $network)) {
3087 $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
3091 // check if we already have a contact
3092 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
3093 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
3095 $protocol = self::getProtocol($ret['url'], $ret['network']);
3097 // This extra param just confuses things, remove it
3098 if ($protocol === Protocol::DIASPORA) {
3099 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
3102 // do we have enough information?
3103 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
3104 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
3105 if (empty($ret['poll'])) {
3106 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
3108 if (empty($ret['name'])) {
3109 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
3111 if (empty($ret['url'])) {
3112 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
3114 if (strpos($ret['url'], '@') !== false) {
3115 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
3116 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
3121 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3122 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3123 $ret['notify'] = '';
3126 if (!$ret['notify']) {
3127 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3130 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3132 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3134 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3137 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3138 $pending = (bool)$ret['manually-approve'];
3141 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3145 if (DBA::isResult($contact)) {
3147 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3149 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3151 if ($contact['pending'] && !empty($contact['hub-verify'])) {
3152 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3153 $fields['pending'] = false;
3156 self::update($fields, ['id' => $contact['id']]);
3158 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3160 // create contact record
3163 'created' => DateTimeFormat::utcNow(),
3164 'url' => $ret['url'],
3165 'nurl' => Strings::normaliseLink($ret['url']),
3166 'addr' => $ret['addr'],
3167 'alias' => $ret['alias'],
3168 'batch' => $ret['batch'],
3169 'notify' => $ret['notify'],
3170 'poll' => $ret['poll'],
3171 'poco' => $ret['poco'],
3172 'name' => $ret['name'],
3173 'nick' => $ret['nick'],
3174 'network' => $ret['network'],
3175 'baseurl' => $ret['baseurl'],
3176 'gsid' => $ret['gsid'] ?? null,
3177 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON,
3178 'protocol' => $protocol,
3179 'pubkey' => $ret['pubkey'],
3180 'rel' => $new_relation,
3181 'priority' => $ret['priority'],
3182 'writable' => $writeable,
3183 'hidden' => $hidden,
3186 'pending' => $pending,
3191 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3192 if (!DBA::isResult($contact)) {
3193 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3197 $contact_id = $contact['id'];
3198 $result['cid'] = $contact_id;
3200 if ($contact['contact-type'] == self::TYPE_COMMUNITY) {
3201 Circle::addMember(User::getDefaultGroupCircle($uid), $contact_id);
3203 Circle::addMember(User::getDefaultCircle($uid), $contact_id);
3206 // Update the avatar
3207 self::updateAvatar($contact_id, $ret['photo']);
3209 // pull feed and consume it, which should subscribe to the hub.
3210 if ($contact['network'] == Protocol::OSTATUS) {
3211 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3215 self::updateFromProbeArray($contact_id, $ret);
3218 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3219 } catch (\InvalidArgumentException $e) {
3220 Logger::notice($e->getMessage(), ['contact' => $contact]);
3224 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3230 * @param array $importer Owner (local user) data
3231 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3232 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3233 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3234 * @param string $note Introduction additional message
3235 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3236 * @throws HTTPException\InternalServerErrorException
3237 * @throws \ImagickException
3239 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3241 // Should always be set
3242 if (empty($datarray['author-id'])) {
3246 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl'];
3247 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3248 if (!DBA::isResult($pub_contact)) {
3249 // Should never happen
3253 // Contact is blocked at node-level
3254 if (self::isBlocked($datarray['author-id'])) {
3258 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3259 $name = $pub_contact['name'];
3260 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3261 $nick = $pub_contact['nick'];
3262 $network = $pub_contact['network'];
3264 // Ensure that we don't create a new contact when there already is one
3265 $cid = self::getIdForURL($url, $importer['uid']);
3267 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3270 self::clearFollowerFollowingEndpointCache($importer['uid']);
3272 if (!empty($contact)) {
3273 if (!empty($contact['pending'])) {
3274 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3278 // Contact is blocked at user-level
3280 !empty($contact['id']) && !empty($importer['id']) &&
3281 Contact\User::isBlocked($contact['id'], $importer['id'])
3286 // Make sure that the existing contact isn't archived
3287 self::unmarkForArchival($contact);
3289 if (($contact['rel'] == self::SHARING)
3290 || ($sharing && $contact['rel'] == self::FOLLOWER)
3293 ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3294 ['id' => $contact['id'], 'uid' => $importer['uid']]
3298 // Ensure to always have the correct network type, independent from the connection request method
3299 self::updateFromProbe($contact['id']);
3301 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3305 // send email notification to owner?
3306 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3307 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3311 // create contact record
3312 $contact_id = self::insert([
3313 'uid' => $importer['uid'],
3314 'created' => DateTimeFormat::utcNow(),
3316 'nurl' => Strings::normaliseLink($url),
3317 'baseurl' => $pub_contact['baseurl'] ?? '',
3320 'network' => $network,
3321 'rel' => self::FOLLOWER,
3328 // Ensure to always have the correct network type, independent from the connection request method
3329 self::updateFromProbe($contact_id);
3331 self::updateAvatar($contact_id, $photo, true);
3333 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3335 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo', 'contact-type'], ['id' => $contact_id]);
3337 /// @TODO Encapsulate this into a function/method
3338 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3339 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3340 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3341 // create notification
3342 if (is_array($contact_record)) {
3343 $intro = DI::introFactory()->createNew(
3345 $contact_record['id'],
3348 DI::intro()->save($intro);
3351 if ($contact_record['contact-type'] == self::TYPE_COMMUNITY) {
3352 Circle::addMember(User::getDefaultGroupCircle($importer['uid']), $contact_record['id']);
3354 Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
3357 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3358 DI::notify()->createFromArray([
3359 'type' => Notification\Type::INTRO,
3360 'otype' => Notification\ObjectType::INTRO,
3361 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3362 'uid' => $user['uid'],
3363 'cid' => $contact_record['id'],
3364 'link' => DI::baseUrl() . '/notifications/intros',
3367 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3368 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3369 self::createFromProbeForUser($importer['uid'], $url, $network);
3372 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3373 $fields = ['pending' => false];
3374 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3375 $fields['rel'] = self::FRIEND;
3378 self::update($fields, $condition);
3388 * Update the local relationship when a local user loses a follower
3390 * @param array $contact User-specific contact (uid != 0) array
3392 * @throws HTTPException\InternalServerErrorException
3393 * @throws \ImagickException
3395 public static function removeFollower(array $contact)
3397 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3398 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3399 } elseif (!empty($contact['id'])) {
3400 self::remove($contact['id']);
3402 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact]);
3406 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3408 self::clearFollowerFollowingEndpointCache($contact['uid']);
3410 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3411 if (!empty($cdata['public'])) {
3412 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3417 * Update the local relationship when a local user unfollow a contact.
3418 * Removes the contact for sharing-only protocols (feed and mail).
3420 * @param array $contact User-specific contact (uid != 0) array
3421 * @throws HTTPException\InternalServerErrorException
3423 public static function removeSharer(array $contact)
3425 self::clearFollowerFollowingEndpointCache($contact['uid']);
3427 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3428 self::remove($contact['id']);
3430 self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
3433 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3437 * Create a birthday event.
3439 * Update the year and the birthday.
3441 public static function updateBirthdays()
3445 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3446 AND NOT `contact`.`pending`
3447 AND NOT `contact`.`hidden`
3448 AND NOT `contact`.`blocked`
3449 AND NOT `contact`.`archive`
3450 AND NOT `contact`.`deleted`',
3456 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3458 while ($contact = DBA::fetch($contacts)) {
3459 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3461 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3463 if (Event::createBirthday($contact, $nextbd)) {
3467 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3468 ['id' => $contact['id']]
3472 DBA::close($contacts);
3476 * Remove the unavailable contact ids from the provided list
3478 * @param array $contact_ids Contact id list
3480 * @throws \Exception
3482 public static function pruneUnavailable(array $contact_ids): array
3484 if (empty($contact_ids)) {
3488 $contacts = self::selectToArray(['id'], [
3489 'id' => $contact_ids,
3495 return array_column($contacts, 'id');
3499 * Return the link to the profile
3501 * @param array $contact
3504 public static function getProfileLink(array $contact): string
3506 if (!empty($contact['alias']) && Network::isValidHttpUrl($contact['alias']) && (($contact['network'] ?? '') != Protocol::DFRN)) {
3507 return $contact['alias'];
3509 return $contact['url'];
3514 * Returns a magic link to authenticate remote visitors
3516 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3518 * @param string $contact_url The address of the target contact profile
3519 * @param string $url An url that we will be redirected to after the authentication
3521 * @return string with "redir" link
3522 * @throws HTTPException\InternalServerErrorException
3523 * @throws \ImagickException
3525 public static function magicLink(string $contact_url, string $url = ''): string
3527 if (!DI::userSession()->isAuthenticated()) {
3528 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3531 $contact = self::getByURL($contact_url, false);
3532 if (empty($contact)) {
3533 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3536 // Prevents endless loop in case only a non-public contact exists for the contact URL
3537 unset($contact['uid']);
3539 return self::magicLinkByContact($contact, $url ?: $contact_url);
3543 * Returns a magic link to authenticate remote visitors
3545 * @param integer $cid The contact id of the target contact profile
3546 * @param string $url An url that we will be redirected to after the authentication
3548 * @return string with "redir" link
3549 * @throws HTTPException\InternalServerErrorException
3550 * @throws \ImagickException
3552 public static function magicLinkById(int $cid, string $url = ''): string
3554 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], ['id' => $cid]);
3556 return self::magicLinkByContact($contact, $url);
3560 * Returns a magic link to authenticate remote visitors
3562 * @param array $contact The contact array with "uid", "network" and "url"
3563 * @param string $url An url that we will be redirected to after the authentication
3565 * @return string with "redir" link
3566 * @throws HTTPException\InternalServerErrorException
3567 * @throws \ImagickException
3569 public static function magicLinkByContact(array $contact, string $url = ''): string
3571 $destination = $url ?: self::getProfileLink($contact);
3573 if (!DI::userSession()->isAuthenticated()) {
3574 return $destination;
3577 // Only redirections to the same host do make sense
3578 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3582 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3583 return 'contact/' . $contact['id'] . '/conversations';
3586 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3587 return $destination;
3590 if (empty($contact['id'])) {
3591 return $destination;
3594 $redirect = 'contact/redir/' . $contact['id'];
3596 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3597 $redirect .= '?url=' . $url;
3604 * Is the contact a group?
3606 * @param integer $contactid ID of the contact
3608 * @return boolean "true" if it is a group
3610 public static function isGroup(int $contactid): bool
3612 $fields = ['contact-type'];
3613 $condition = ['id' => $contactid];
3614 $contact = DBA::selectFirst('contact', $fields, $condition);
3615 if (!DBA::isResult($contact)) {
3620 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3624 * Can the remote contact receive private messages?
3626 * @param array $contact
3629 public static function canReceivePrivateMessages(array $contact): bool
3631 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3632 $self = $contact['self'] ?? false;
3634 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3638 * Search contact table by nick or name
3640 * @param string $search Name or nick
3641 * @param string $mode Search mode (e.g. "community")
3642 * @param bool $show_blocked Show users from blocked servers. Default is false
3643 * @param int $uid User ID
3644 * @param int $limit Maximum amount of returned values
3645 * @param int $offset Limit offset
3647 * @return array with search results
3648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3650 public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
3652 if (empty($search)) {
3656 // check supported networks
3657 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3658 if (DI::config()->get('system', 'diaspora_enabled')) {
3659 $networks[] = Protocol::DIASPORA;
3662 if (!DI::config()->get('system', 'ostatus_disabled')) {
3663 $networks[] = Protocol::OSTATUS;
3667 'network' => $networks,
3668 'server-failed' => false,
3671 'unsearchable' => false,
3675 if (!$show_blocked) {
3676 $condition['server-blocked'] = false;
3680 $condition['blocked'] = false;
3682 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3685 // check if we search only communities or every contact
3686 if ($mode === 'community') {
3687 $condition['contact-type'] = self::TYPE_COMMUNITY;
3694 if (!empty($limit) && !empty($offset)) {
3695 $params['limit'] = [$offset, $limit];
3696 } elseif (!empty($limit)) {
3697 $params['limit'] = $limit;
3700 $condition = DBA::mergeConditions(
3702 ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]
3705 return DBA::selectToArray('account-user-view', [], $condition, $params);
3709 * Add public contacts from an array
3711 * @param array $urls
3712 * @return array result "count", "added" and "updated"
3714 public static function addByUrls(array $urls): array
3721 foreach ($urls as $url) {
3722 if (empty($url) || !is_string($url)) {
3725 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3726 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3727 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3729 } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3731 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3733 } catch (\InvalidArgumentException $e) {
3734 Logger::notice($e->getMessage(), ['contact' => $contact]);
3742 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3746 * Returns a random, global contact array of the current node
3748 * @return array The profile array
3751 public static function getRandomContact(): array
3753 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], [
3754 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3755 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3756 ], ['order' => ['RAND()']]);
3758 if (DBA::isResult($contact)) {
3766 * Checks, if contacts with the given condition exists
3768 * @param array $condition
3771 * @throws \Exception
3773 public static function exists(array $condition): bool
3775 return DBA::exists('contact', $condition);