3 * @copyright Copyright (C) 2010-2023, 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);
176 * Insert a row into the contact table
177 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
179 * @param array $fields field array
180 * @param int $duplicate_mode Do an update on a duplicate entry
182 * @return int id of the created contact
185 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
187 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
188 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
191 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
193 if (empty($fields['created'])) {
194 $fields['created'] = DateTimeFormat::utcNow();
197 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
198 DBA::insert('contact', $fields, $duplicate_mode);
199 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
200 if (!DBA::isResult($contact)) {
202 Logger::warning('Created contact could not be found', ['fields' => $fields]);
206 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
207 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
208 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
209 if (empty($account_user['id'])) {
210 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
211 } elseif ($account_user['id'] != $contact['id']) {
212 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
213 if (!empty($duplicate['id'])) {
214 $ret = Contact::deleteById($contact['id']);
215 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']]);
216 $contact = $duplicate;
218 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
219 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']]);
223 Contact\User::insertForContactArray($contact);
225 if ((empty($contact['baseurl']) || empty($contact['gsid'])) && Probe::isProbable($contact['network'])) {
226 Logger::debug('Update missing baseurl', ['id' => $contact['id'], 'url' => $contact['url'], 'callstack' => System::callstack(4, 0, true)]);
227 UpdateContact::add(['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true], $contact['id']);
230 return $contact['id'];
234 * Delete contact by id
239 public static function deleteById(int $id): bool
241 Logger::debug('Delete contact', ['id' => $id]);
242 DBA::delete('account-user', ['id' => $id]);
243 return DBA::delete('contact', ['id' => $id]);
247 * Updates rows in the contact table
249 * @param array $fields contains the fields that are updated
250 * @param array $condition condition array with the key values
251 * @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)
253 * @return boolean was the update successful?
255 * @todo Let's get rid of boolean type of $old_fields
257 public static function update(array $fields, array $condition, $old_fields = []): bool
259 // Apply changes to the "user-contact" table on dedicated fields
260 Contact\User::updateByContactUpdate($fields, $condition);
262 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
263 return DBA::update('contact', $fields, $condition, $old_fields);
267 * @param integer $id Contact ID
268 * @param array $fields Array of selected fields, empty for all
269 * @return array|boolean Contact record if it exists, false otherwise
272 public static function getById(int $id, array $fields = [])
274 return DBA::selectFirst('contact', $fields, ['id' => $id]);
278 * Fetch the first contact with the provided uri-id.
280 * @param integer $uri_id uri-id of the contact
281 * @param array $fields Array of selected fields, empty for all
282 * @return array|boolean Contact record if it exists, false otherwise
285 public static function getByUriId(int $uri_id, array $fields = [])
287 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
291 * Fetch all remote contacts for a given contact url
293 * @param string $url The URL of the contact
294 * @param array $fields The wanted fields
296 * @return array all remote contacts
300 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
304 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
305 while ($contact = DBA::fetch($remote_contacts)) {
306 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
309 $remote[$contact['uid']] = $contact['id'];
311 DBA::close($remote_contacts);
317 * Fetches a contact by a given url
319 * @param string $url profile url
320 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
321 * @param array $fields Field list
322 * @param integer $uid User ID of the contact
323 * @return array contact array
325 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
327 if ($update || is_null($update)) {
328 $cid = self::getIdForURL($url, $uid, $update);
333 $contact = self::getById($cid, $fields);
334 if (empty($contact)) {
340 // Add internal fields
342 if (!empty($fields)) {
343 foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
344 if (!in_array($internal, $fields)) {
345 $fields[] = $internal;
346 $removal[] = $internal;
351 // We first try the nurl (http://server.tld/nick), most common case
352 $options = ['order' => ['id']];
353 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
355 // Then the addr (nick@server.tld)
356 if (!DBA::isResult($contact)) {
357 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
360 // Then the alias (which could be anything)
361 if (!DBA::isResult($contact)) {
362 // The link could be provided as http although we stored it as https
363 $ssl_url = str_replace('http://', 'https://', $url);
364 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
365 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
368 if (!DBA::isResult($contact)) {
372 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
374 // Update the contact in the background if needed
375 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
377 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
378 } catch (\InvalidArgumentException $e) {
379 Logger::notice($e->getMessage(), ['contact' => $contact]);
383 // Remove the internal fields
384 foreach ($removal as $internal) {
385 unset($contact[$internal]);
392 * Fetches a contact for a given user by a given url.
393 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
395 * @param string $url profile url
396 * @param integer $uid User ID of the contact
397 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
398 * @param array $fields Field list
399 * @return array contact array
401 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
404 $contact = self::getByURL($url, $update, $fields, $uid);
405 if (!empty($contact)) {
406 if (!empty($contact['id'])) {
407 $contact['cid'] = $contact['id'];
414 $contact = self::getByURL($url, $update, $fields);
415 if (!empty($contact['id'])) {
417 $contact['zid'] = $contact['id'];
423 * Checks if a contact uses a specific platform
426 * @param string $platform
429 public static function isPlatform(string $url, string $platform): bool
431 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
435 * Tests if the given contact is a follower
437 * @param int $cid Either public contact id or user's contact id
438 * @param int $uid User ID
439 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
441 * @return boolean is the contact id a follower?
442 * @throws HTTPException\InternalServerErrorException
443 * @throws \ImagickException
445 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
447 if (Contact\User::isBlocked($cid, $uid)) {
451 $cdata = self::getPublicAndUserContactID($cid, $uid);
452 if (empty($cdata['user'])) {
456 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
458 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
460 return DBA::exists('contact', $condition);
464 * Tests if the given contact url is a follower
466 * @param string $url Contact URL
467 * @param int $uid User ID
468 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
470 * @return boolean is the contact id a follower?
471 * @throws HTTPException\InternalServerErrorException
472 * @throws \ImagickException
474 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
476 $cid = self::getIdForURL($url, $uid);
482 return self::isFollower($cid, $uid, $strict);
486 * Tests if the given user shares with the given contact
488 * @param int $cid Either public contact id or user's contact id
489 * @param int $uid User ID
490 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
492 * @return boolean is the contact sharing with given user?
493 * @throws HTTPException\InternalServerErrorException
494 * @throws \ImagickException
496 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
498 if (Contact\User::isBlocked($cid, $uid)) {
502 $cdata = self::getPublicAndUserContactID($cid, $uid);
503 if (empty($cdata['user'])) {
507 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
509 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
511 return DBA::exists('contact', $condition);
515 * Tests if the given user follow the given contact url
517 * @param string $url Contact URL
518 * @param int $uid User ID
519 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
521 * @return boolean is the contact url being followed?
522 * @throws HTTPException\InternalServerErrorException
523 * @throws \ImagickException
525 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
527 $cid = self::getIdForURL($url, $uid);
533 return self::isSharing($cid, $uid, $strict);
537 * Checks if the provided public contact id has got followers on this system
539 * @param integer $cid
542 public static function hasFollowers(int $cid): bool
544 return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?)", $cid, 0, self::SHARING, self::FRIEND]);
548 * Get the basepath for a given contact link
550 * @param string $url The contact link
551 * @param boolean $dont_update Don't update the contact
553 * @return string basepath
554 * @throws HTTPException\InternalServerErrorException
555 * @throws \ImagickException
557 public static function getBasepath(string $url, bool $dont_update = false): string
559 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
560 if (!DBA::isResult($contact)) {
564 if (!empty($contact['baseurl'])) {
565 return $contact['baseurl'];
566 } elseif ($dont_update) {
570 // Update the existing contact
571 self::updateFromProbe($contact['id']);
573 // And fetch the result
574 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
575 if (empty($contact['baseurl'])) {
576 Logger::info('No baseurl for contact', ['url' => $url]);
580 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
581 return $contact['baseurl'];
585 * Check if the given contact url is on the same server
587 * @param string $url The contact link
589 * @return boolean Is it the same server?
591 public static function isLocal(string $url): bool
593 if (!parse_url($url, PHP_URL_SCHEME)) {
594 $addr_parts = explode('@', $url);
595 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
598 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
602 * Check if the given contact ID is on the same server
604 * @param string $url The contact link
605 * @return boolean Is it the same server?
607 public static function isLocalById(int $cid): bool
609 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
610 if (!DBA::isResult($contact)) {
614 if (empty($contact['baseurl'])) {
615 $baseurl = self::getBasepath($contact['url'], true);
617 $baseurl = $contact['baseurl'];
620 return Strings::compareLink($baseurl, DI::baseUrl());
624 * Returns the public contact id of the given user id
626 * @param integer $uid User ID
628 * @return integer|boolean Public contact id for given user id
631 public static function getPublicIdByUserId(int $uid)
633 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
634 if (!DBA::isResult($self)) {
637 return self::getIdForURL($self['url']);
641 * Returns the contact id for the user and the public contact id for a given contact id
643 * @param int $cid Either public contact id or user's contact id
644 * @param int $uid User ID
646 * @return array with public and user's contact id
647 * @throws HTTPException\InternalServerErrorException
648 * @throws \ImagickException
650 public static function getPublicAndUserContactID(int $cid, int $uid): array
652 // We have to use the legacy function as long as the post update hasn't finished
653 if (DI::keyValue()->get('post_update_version') < 1427) {
654 return self::legacyGetPublicAndUserContactID($cid, $uid);
657 if (empty($uid) || empty($cid)) {
661 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
662 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
666 $pcid = $contact['pid'];
667 if ($contact['uid'] == $uid) {
668 $ucid = $contact['id'];
670 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
671 if (DBA::isResult($contact)) {
672 $ucid = $contact['id'];
678 return ['public' => $pcid, 'user' => $ucid];
682 * Helper function for "getPublicAndUserContactID"
684 * @param int $cid Either public contact id or user's contact id
685 * @param int $uid User ID
686 * @return array with public and user's contact id
687 * @throws HTTPException\InternalServerErrorException
688 * @throws \ImagickException
690 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
692 if (empty($uid) || empty($cid)) {
696 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
697 if (!DBA::isResult($contact)) {
701 // We quit when the user id don't match the user id of the provided contact
702 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
706 if ($contact['uid'] != 0) {
707 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
711 $ucid = $contact['id'];
713 $pcid = $contact['id'];
714 $ucid = self::getIdForURL($contact['url'], $uid);
717 return ['public' => $pcid, 'user' => $ucid];
721 * Returns contact details for a given contact id in combination with a user id
723 * @param int $cid A contact ID
724 * @param int $uid The User ID
725 * @param array $fields The selected fields for the contact
726 * @return array The contact details
730 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
732 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
734 if (!DBA::isResult($contact)) {
742 * Creates the self-contact for the provided user id
745 * @return bool Operation success
746 * @throws HTTPException\InternalServerErrorException
748 public static function createSelfFromUserId(int $uid): bool
750 $user = DBA::selectFirst(
752 ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
753 ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
755 if (!DBA::isResult($user)) {
760 'uid' => $user['uid'],
761 'created' => DateTimeFormat::utcNow(),
763 'name' => $user['username'],
764 'nick' => $user['nickname'],
765 'pubkey' => $user['pubkey'],
766 'prvkey' => $user['prvkey'],
767 'photo' => User::getAvatarUrl($user),
768 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
769 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
772 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
773 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
774 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
775 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
776 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
777 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
778 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
779 'name-date' => DateTimeFormat::utcNow(),
780 'uri-date' => DateTimeFormat::utcNow(),
781 'avatar-date' => DateTimeFormat::utcNow(),
787 // Only create the entry if it doesn't exist yet
788 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
789 $return = (bool)self::insert($contact);
792 // Create the public contact
793 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
794 $contact['self'] = false;
796 $contact['prvkey'] = null;
798 self::insert($contact, Database::INSERT_IGNORE);
805 * Updates the self-contact for the provided user id
808 * @param bool $update_avatar Force the avatar update
809 * @return bool "true" if updated
812 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
815 'id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
816 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
817 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'
819 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
820 if (!DBA::isResult($self)) {
824 $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
825 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
826 if (!DBA::isResult($user)) {
831 'name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
832 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'
834 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
835 if (!DBA::isResult($profile)) {
839 $file_suffix = 'jpg';
840 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
843 'name' => $user['username'],
844 'nick' => $user['nickname'],
845 'avatar-date' => $self['avatar-date'],
846 'location' => Profile::formatLocation($profile),
847 'about' => $profile['about'],
848 'keywords' => $profile['pub_keywords'],
849 'contact-type' => $user['account-type'],
850 'prvkey' => $user['prvkey'],
851 'pubkey' => $user['pubkey'],
852 'xmpp' => $profile['xmpp'],
853 'matrix' => $profile['matrix'],
854 'network' => Protocol::DFRN,
856 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
857 'nurl' => Strings::normaliseLink($url),
858 'uri-id' => ItemURI::getIdByURI($url),
859 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
860 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
861 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
862 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
863 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
866 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
867 if (DBA::isResult($avatar)) {
868 if ($update_avatar) {
869 $fields['avatar-date'] = DateTimeFormat::utcNow();
872 // Creating the path to the avatar, beginning with the file suffix
873 $types = Images::supportedTypes();
874 if (isset($types[$avatar['type']])) {
875 $file_suffix = $types[$avatar['type']];
878 // We are adding a timestamp value so that other systems won't use cached content
879 $timestamp = strtotime($fields['avatar-date']);
881 $prefix = DI::baseUrl() . '/photo/' . $avatar['resource-id'] . '-';
882 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
884 $fields['photo'] = $prefix . '4' . $suffix;
885 $fields['thumb'] = $prefix . '5' . $suffix;
886 $fields['micro'] = $prefix . '6' . $suffix;
888 // We hadn't found a photo entry, so we use the default avatar
889 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
890 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
891 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
894 $fields['avatar'] = User::getAvatarUrl($user);
895 $fields['header'] = User::getBannerUrl($user);
896 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
897 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
898 $fields['unsearchable'] = !$profile['net-publish'];
899 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
903 foreach ($fields as $field => $content) {
904 if ($self[$field] != $content) {
910 if ($fields['name'] != $self['name']) {
911 $fields['name-date'] = DateTimeFormat::utcNow();
913 $fields['updated'] = DateTimeFormat::utcNow();
914 self::update($fields, ['id' => $self['id']]);
916 // Update the other contacts as well
917 unset($fields['prvkey']);
918 $fields['self'] = false;
919 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
921 // Update the profile
923 'photo' => User::getAvatarUrl($user),
924 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
927 DBA::update('profile', $fields, ['uid' => $uid]);
934 * Marks a contact for removal
936 * @param int $id contact id
938 * @throws HTTPException\InternalServerErrorException
940 public static function remove(int $id)
942 // We want just to make sure that we don't delete our "self" contact
943 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
944 if (!DBA::isResult($contact)) {
948 DBA::delete('account-user', ['id' => $id]);
950 self::clearFollowerFollowingEndpointCache($contact['uid']);
952 // Archive the contact
953 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
955 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
956 Avatar::deleteCache($contact);
959 // Delete it in the background
960 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
964 * Unfollow the remote contact
966 * @param array $contact Target user-specific contact (uid != 0) array
968 * @throws HTTPException\InternalServerErrorException
969 * @throws \ImagickException
971 public static function unfollow(array $contact): void
973 if (empty($contact['network'])) {
974 throw new \InvalidArgumentException('Empty network in contact array');
977 if (empty($contact['uid'])) {
978 throw new \InvalidArgumentException('Unexpected public contact record');
981 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
982 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
983 if (!empty($cdata['public'])) {
984 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
988 self::removeSharer($contact);
992 * Revoke follow privileges of the remote user contact
994 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
996 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
998 * @throws HTTPException\InternalServerErrorException
999 * @throws \ImagickException
1001 public static function revokeFollow(array $contact): void
1003 if (empty($contact['network'])) {
1004 throw new \InvalidArgumentException('Empty network in contact array');
1007 if (empty($contact['uid'])) {
1008 throw new \InvalidArgumentException('Unexpected public contact record');
1011 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
1012 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1013 if (!empty($cdata['public'])) {
1014 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1018 self::removeFollower($contact);
1022 * Completely severs a relationship with a contact
1024 * @param array $contact User-specific contact (uid != 0) array
1026 * @throws HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 public static function terminateFriendship(array $contact)
1031 if (empty($contact['network'])) {
1032 throw new \InvalidArgumentException('Empty network in contact array');
1035 if (empty($contact['uid'])) {
1036 throw new \InvalidArgumentException('Unexpected public contact record');
1039 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1041 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1042 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1045 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1046 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1049 self::remove($contact['id']);
1052 private static function clearFollowerFollowingEndpointCache(int $uid)
1058 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1059 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1063 * Marks a contact for archival after a communication issue delay
1065 * Contact has refused to recognise us as a friend. We will start a countdown.
1066 * If they still don't recognise us in 32 days, the relationship is over,
1067 * and we won't waste any more time trying to communicate with them.
1068 * This provides for the possibility that their database is temporarily messed
1069 * up or some other transient event and that there's a possibility we could recover from it.
1071 * @param array $contact contact to mark for archival
1073 * @throws HTTPException\InternalServerErrorException
1075 public static function markForArchival(array $contact)
1077 if (!isset($contact['url']) && !empty($contact['id'])) {
1078 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1079 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1080 if (!DBA::isResult($contact)) {
1083 } elseif (!isset($contact['url'])) {
1084 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1087 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1089 // Contact already archived or "self" contact? => nothing to do
1090 if ($contact['archive'] || $contact['self']) {
1094 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1095 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1096 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1099 * We really should send a notification to the owner after 2-3 weeks
1100 * so they won't be surprised when the contact vanishes and can take
1101 * remedial action if this was a serious mistake or glitch
1104 /// @todo Check for contact vitality via probing
1105 $archival_days = DI::config()->get('system', 'archival_days', 32);
1107 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1108 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1109 /* Relationship is really truly dead. archive them rather than
1110 * delete, though if the owner tries to unarchive them we'll start
1111 * the whole process over again.
1113 self::update(['archive' => true], ['id' => $contact['id']]);
1114 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1120 * Cancels the archival countdown
1122 * @see Contact::markForArchival()
1124 * @param array $contact contact to be unmarked for archival
1126 * @throws \Exception
1128 public static function unmarkForArchival(array $contact)
1130 // Always unarchive the relay contact entry
1131 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1132 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1133 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1134 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1135 self::update($fields, $condition);
1139 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1140 $exists = DBA::exists('contact', $condition);
1142 // We don't need to update, we never marked this contact for archival
1147 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1149 if (!isset($contact['url']) && !empty($contact['id'])) {
1150 $fields = ['id', 'url', 'batch'];
1151 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1152 if (!DBA::isResult($contact)) {
1157 // It's a miracle. Our dead contact has inexplicably come back to life.
1158 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1159 self::update($fields, ['id' => $contact['id']]);
1160 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1164 * Returns the data array for the photo menu of a given contact
1166 * @param array $contact contact
1167 * @param int $uid Visitor user id
1169 * @throws HTTPException\InternalServerErrorException
1170 * @throws \ImagickException
1172 public static function photoMenu(array $contact, int $uid): array
1174 // Anonymous visitor
1176 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1184 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1185 $profile_link = 'contact/redir/' . $contact['id'];
1186 $status_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
1187 $photos_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
1188 $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
1190 $profile_link = $contact['url'];
1193 if ($profile_link === 'mailbox') {
1197 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1198 $pm_url = 'message/new/' . $contact['id'];
1201 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1202 $mention_label = DI::l10n()->t('Post to group');
1203 $mention_url = 'compose/0?body=!' . $contact['addr'];
1205 $mention_label = DI::l10n()->t('Mention');
1206 $mention_url = 'compose/0?body=@' . $contact['addr'];
1209 $contact_url = 'contact/' . $contact['id'];
1211 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1212 $network_label = DI::l10n()->t('View group');
1213 $network_url = 'network/group/' . $contact['id'];
1215 $network_label = DI::l10n()->t('Network Posts');
1216 $network_url = 'contact/' . $contact['id'] . '/conversations';
1220 $unfollow_link = '';
1221 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1222 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1223 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1224 } elseif (!$contact['pending']) {
1225 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1231 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1235 if (empty($contact['uid'])) {
1237 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1238 'network' => [$network_label, $network_url, false],
1239 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1240 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1241 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1242 'mention' => [DI::l10n()->t('Mention'), DI::l10n()->t('Post to group'), $mention_url, false],
1243 'group' => [DI::l10n()->t('View group'), $group_link, $contact['forum'], true],
1244 'self' => [$contact['self'] ?? false, true],
1248 'status' => [DI::l10n()->t('View Status'), $status_link, true],
1249 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1250 'photos' => [DI::l10n()->t('View Photos'), $photos_link, true],
1251 'network' => [$network_label, $network_url, false],
1252 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1253 'pm' => [DI::l10n()->t('Send PM'), $pm_url, false],
1254 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1255 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1256 'mention' => [$mention_label, $mention_url, false],
1259 if (!empty($contact['pending'])) {
1261 $intro = DI::intro()->selectForContact($contact['id']);
1262 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1263 } catch (IntroductionNotFoundException $exception) {
1264 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1269 $args = ['contact' => $contact, 'menu' => &$menu];
1271 Hook::callAll('contact_photo_menu', $args);
1273 $menucondensed = [];
1275 foreach ($menu as $menuname => $menuitem) {
1276 if ($menuitem[1] != '') {
1277 $menucondensed[$menuname] = $menuitem;
1281 return $menucondensed;
1285 * Fetch the contact id for a given URL and user
1287 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1288 * `addr` or `alias`.
1290 * If there's no record and we aren't looking for a public contact, we quit.
1291 * If there's one, we check that it isn't time to update the picture else we
1292 * directly return the found contact id.
1294 * Second, we probe the provided $url whether it's http://server.tld/profile or
1295 * nick@server.tld. We quit if we can't get any info back.
1297 * Third, we create the contact record if it doesn't exist
1299 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1300 * if there's any updates
1302 * @param string $url Contact URL
1303 * @param integer $uid The user id for the contact (0 = public contact)
1304 * @param boolean $update true = always update, false = never update, null = update when not found
1305 * @param array $default Default value for creating the contact when everything else fails
1307 * @return integer Contact ID
1308 * @throws HTTPException\InternalServerErrorException
1309 * @throws \ImagickException
1311 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1316 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1320 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
1322 if (!empty($contact)) {
1323 $contact_id = $contact['id'];
1325 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
1327 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1329 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
1330 } catch (\InvalidArgumentException $e) {
1331 Logger::notice($e->getMessage(), ['contact' => $contact]);
1335 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1336 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1339 } elseif ($uid != 0) {
1340 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1342 } elseif (empty($default) && !is_null($update) && !$update) {
1343 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1349 if (empty($default['network']) || $update) {
1350 $data = Probe::uri($url, '', $uid);
1352 // Take the default values when probing failed
1353 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1354 $data = array_merge($data, $default);
1356 } elseif (!empty($default['network'])) {
1360 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1361 // Fetch data for the public contact via the first found personal contact
1362 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1364 'name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1365 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1366 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'
1369 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1370 if (!DBA::isResult($personal_contact)) {
1371 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1374 if (DBA::isResult($personal_contact)) {
1375 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1376 $data = $personal_contact;
1377 $data['photo'] = $personal_contact['avatar'];
1378 $data['account-type'] = $personal_contact['contact-type'];
1379 $data['hide'] = $personal_contact['unsearchable'];
1380 unset($data['avatar']);
1381 unset($data['contact-type']);
1382 unset($data['unsearchable']);
1386 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1387 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1391 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1392 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1397 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1398 if (!empty($data['alias'])) {
1399 $urls[] = Strings::normaliseLink($data['alias']);
1401 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1402 if (!empty($contact['id'])) {
1403 $contact_id = $contact['id'];
1404 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1409 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1412 'url' => $data['url'],
1413 'baseurl' => $data['baseurl'] ?? '',
1414 'nurl' => Strings::normaliseLink($data['url']),
1415 'network' => $data['network'],
1416 'created' => DateTimeFormat::utcNow(),
1417 'rel' => self::SHARING,
1424 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1426 // Before inserting we do check if the entry does exist now.
1427 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1428 if (DBA::isResult($contact)) {
1429 $contact_id = $contact['id'];
1430 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1432 $contact_id = self::insert($fields);
1434 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1439 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1443 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1446 if ($data['network'] == Protocol::DIASPORA) {
1448 DI::dsprContact()->updateFromProbeArray($data);
1449 } catch (HTTPException\NotFoundException $e) {
1450 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1451 } catch (\InvalidArgumentException $e) {
1452 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1454 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1456 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1457 } catch (HTTPException\NotFoundException $e) {
1458 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1459 } catch (\InvalidArgumentException $e) {
1460 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1464 self::updateFromProbeArray($contact_id, $data);
1466 // Don't return a number for a deleted account
1467 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1468 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1476 * Checks if the contact is archived
1478 * @param int $cid contact id
1480 * @return boolean Is the contact archived?
1481 * @throws HTTPException\InternalServerErrorException
1483 public static function isArchived(int $cid): bool
1489 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1490 if (!DBA::isResult($contact)) {
1494 if ($contact['archive']) {
1498 // Check status of ActivityPub endpoints
1499 $apcontact = APContact::getByURL($contact['url'], false);
1500 if (!empty($apcontact)) {
1501 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1505 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1510 // Check status of Diaspora endpoints
1511 if (!empty($contact['batch'])) {
1512 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1513 return DBA::exists('contact', $condition);
1520 * Checks if the contact is blocked
1522 * @param int $cid contact id
1523 * @return boolean Is the contact blocked?
1524 * @throws HTTPException\InternalServerErrorException
1526 public static function isBlocked(int $cid): bool
1532 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1533 if (!DBA::isResult($blocked)) {
1537 if (Network::isUrlBlocked($blocked['url'])) {
1541 return (bool) $blocked['blocked'];
1545 * Checks if the contact is hidden
1547 * @param int $cid contact id
1548 * @return boolean Is the contact hidden?
1549 * @throws \Exception
1551 public static function isHidden(int $cid): bool
1557 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1558 if (!DBA::isResult($hidden)) {
1561 return (bool) $hidden['hidden'];
1565 * Returns posts from a given contact url
1567 * @param string $contact_url Contact URL
1568 * @param bool $thread_mode
1569 * @param int $update Update mode
1570 * @param int $parent Item parent ID for the update mode
1571 * @param bool $only_media Only display media content
1572 * @return string posts in HTML
1573 * @throws \Exception
1575 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1577 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1581 * Returns posts from a given contact id
1583 * @param int $cid Contact ID
1584 * @param bool $thread_mode
1585 * @param int $update Update mode
1586 * @param int $parent Item parent ID for the update mode
1587 * @param bool $only_media Only display media content
1588 * @return string posts in HTML
1589 * @throws \Exception
1591 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1593 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1594 if (!DBA::isResult($contact)) {
1598 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1599 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1604 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1608 "((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1609 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()
1613 "`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1614 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()
1618 if (!empty($parent)) {
1619 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1621 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1622 if (!empty($last_received)) {
1623 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1628 $condition = DBA::mergeConditions($condition, [
1629 "`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1630 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO
1634 if (DI::mode()->isMobile()) {
1635 $itemsPerPage = DI::pConfig()->get(
1636 DI::userSession()->getLocalUserId(),
1638 'itemspage_mobile_network',
1639 DI::config()->get('system', 'itemspage_network_mobile')
1642 $itemsPerPage = DI::pConfig()->get(
1643 DI::userSession()->getLocalUserId(),
1645 'itemspage_network',
1646 DI::config()->get('system', 'itemspage_network')
1650 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1652 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1654 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1655 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1656 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1662 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1663 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1665 if ($pager->getStart() == 0) {
1666 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1667 if (!empty($cdata['public'])) {
1668 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1669 $items = array_merge($items, $pinned);
1673 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1675 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1676 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1678 if ($pager->getStart() == 0) {
1679 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1680 if (!empty($cdata['public'])) {
1682 "`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1683 $cdata['public'], Post\Collection::FEATURED
1685 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1686 $items = array_merge($pinned, $items);
1690 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS, $update);
1694 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1695 $o .= HTML::scrollLoader();
1697 $o .= $pager->renderMinimal(count($items));
1705 * Returns the account type name
1707 * The function can be called with either the user or the contact array
1709 * @param int $type type of contact or account
1712 public static function getAccountType(int $type): string
1715 case self::TYPE_ORGANISATION:
1716 $account_type = DI::l10n()->t("Organisation");
1719 case self::TYPE_NEWS:
1720 $account_type = DI::l10n()->t('News');
1723 case self::TYPE_COMMUNITY:
1724 $account_type = DI::l10n()->t("Group");
1732 return $account_type;
1738 * @param int $cid Contact id to block
1739 * @param string $reason Block reason
1740 * @return bool Whether it was successful
1742 public static function block(int $cid, string $reason = null): bool
1744 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1750 * Unblocks a contact
1752 * @param int $cid Contact id to unblock
1753 * @return bool Whether it was successful
1755 public static function unblock(int $cid): bool
1757 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1763 * Ensure that cached avatar exist
1765 * @param integer $cid Contact id
1767 public static function checkAvatarCache(int $cid)
1769 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1770 if (!DBA::isResult($contact)) {
1774 if (Network::isLocalLink($contact['url'])) {
1778 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1779 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1780 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1781 self::updateAvatar($cid, $contact['avatar'], true);
1784 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1785 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1786 self::updateAvatar($cid, $contact['avatar'], true);
1788 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1789 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1790 self::updateAvatar($cid, $contact['avatar'], true);
1796 * Return the photo path for a given contact array in the given size
1798 * @param array $contact contact array
1799 * @param string $size Size of the avatar picture
1800 * @param bool $no_update Don't perform an update if no cached avatar was found
1801 * @return string photo path
1803 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1805 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1807 if (DI::config()->get('system', 'avatar_cache')) {
1809 case Proxy::SIZE_MICRO:
1810 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1811 return $contact['micro'];
1814 case Proxy::SIZE_THUMB:
1815 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1816 return $contact['thumb'];
1819 case Proxy::SIZE_SMALL:
1820 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1821 return $contact['photo'];
1827 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1831 * Return the photo path for a given contact array
1833 * @param array $contact Contact array
1834 * @param bool $no_update Don't perform an update if no cached avatar was found
1835 * @return string photo path
1837 public static function getPhoto(array $contact, bool $no_update = false): string
1839 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1843 * Return the photo path (thumb size) for a given contact array
1845 * @param array $contact Contact array
1846 * @param bool $no_update Don't perform an update if no cached avatar was found
1847 * @return string photo path
1849 public static function getThumb(array $contact, bool $no_update = false): string
1851 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1855 * Return the photo path (micro size) for a given contact array
1857 * @param array $contact Contact array
1858 * @param bool $no_update Don't perform an update if no cached avatar was found
1859 * @return string photo path
1861 public static function getMicro(array $contact, bool $no_update = false): string
1863 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1867 * Check the given contact array for avatar cache fields
1869 * @param array $contact
1870 * @param bool $no_update Don't perform an update if no cached avatar was found
1871 * @return array contact array with avatar cache fields
1873 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1876 $contact_fields = [];
1877 $fields = ['photo', 'thumb', 'micro'];
1878 foreach ($fields as $field) {
1879 if (isset($contact[$field])) {
1880 $contact_fields[] = $field;
1882 if (isset($contact[$field]) && empty($contact[$field])) {
1887 if (!$update || $no_update) {
1891 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1893 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1894 self::updateAvatar($contact['id'], $contact['avatar'], true);
1896 $new_contact = self::getById($contact['id'], $contact_fields);
1897 if (DBA::isResult($new_contact)) {
1898 // We only update the cache fields
1899 $contact = array_merge($contact, $new_contact);
1901 } elseif ($local && !empty($contact['avatar'])) {
1905 /// add the default avatars if the fields aren't filled
1906 if (isset($contact['photo']) && empty($contact['photo'])) {
1907 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1909 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1910 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1912 if (isset($contact['micro']) && empty($contact['micro'])) {
1913 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1920 * Fetch the default header for the given contact
1922 * @param array $contact contact array
1923 * @return string avatar URL
1925 public static function getDefaultHeader(array $contact): string
1927 if (!empty($contact['header'])) {
1928 return $contact['header'];
1931 if (!empty($contact['gsid'])) {
1932 // Use default banners for certain platforms
1933 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1934 $platform = strtolower($gserver['platform'] ?? '');
1939 switch ($platform) {
1942 $header = DI::baseUrl() . (new Header(DI::config()))->getMastodonBannerPath();
1947 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1948 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1949 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1951 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1955 * Use a random picture.
1956 * The service provides random pictures from Unsplash.
1957 * @license https://unsplash.com/license
1959 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1967 * Fetch the default avatar for the given contact and size
1969 * @param array $contact contact array
1970 * @param string $size Size of the avatar picture
1971 * @return string avatar URL
1973 public static function getDefaultAvatar(array $contact, string $size): string
1976 case Proxy::SIZE_MICRO:
1977 $avatar['size'] = 48;
1978 $default = self::DEFAULT_AVATAR_MICRO;
1981 case Proxy::SIZE_THUMB:
1982 $avatar['size'] = 80;
1983 $default = self::DEFAULT_AVATAR_THUMB;
1986 case Proxy::SIZE_SMALL:
1988 $avatar['size'] = 300;
1989 $default = self::DEFAULT_AVATAR_PHOTO;
1993 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1995 $type = Contact::TYPE_PERSON;
1997 if (!empty($contact['id'])) {
1998 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1999 $platform = $account['platform'] ?? '';
2000 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
2003 if (empty($platform) && !empty($contact['uri-id'])) {
2004 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
2005 $platform = $account['platform'] ?? '';
2006 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
2009 switch ($platform) {
2013 * @license GNU Affero General Public License v3.0
2014 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
2016 $default = '/images/default/corgidon.png';
2022 * @license GNU Affero General Public License v3.0
2023 * @link https://github.com/diaspora/diaspora/
2025 $default = '/images/default/diaspora.png';
2031 * @license GNU Affero General Public License v3.0
2032 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
2034 $default = '/images/default/gotosocial.svg';
2040 * @license GNU Affero General Public License v3.0
2041 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
2043 $default = '/images/default/hometown.png';
2049 * @license GNU Affero General Public License v3.0
2050 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
2052 $default = '/images/default/koyuspace.png';
2060 * @license GNU Affero General Public License v3.0
2061 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2063 $default = '/images/default/mastodon.png';
2067 if ($type == Contact::TYPE_COMMUNITY) {
2070 * @license GNU Affero General Public License v3.0
2071 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2073 $default = '/images/default/peertube-channel.png';
2077 * @license GNU Affero General Public License v3.0
2078 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2080 $default = '/images/default/peertube-account.png';
2087 * @license GNU Affero General Public License v3.0
2088 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2090 $default = '/images/default/pleroma.png';
2096 * @license GNU Affero General Public License v3.0
2097 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2099 $default = '/images/default/plume.png';
2102 return DI::baseUrl() . $default;
2105 if (!empty($contact['xmpp'])) {
2106 $avatar['email'] = $contact['xmpp'];
2107 } elseif (!empty($contact['addr'])) {
2108 $avatar['email'] = $contact['addr'];
2109 } elseif (!empty($contact['url'])) {
2110 $avatar['email'] = $contact['url'];
2112 return DI::baseUrl() . $default;
2115 $avatar['url'] = '';
2116 $avatar['success'] = false;
2118 Hook::callAll('avatar_lookup', $avatar);
2120 if ($avatar['success'] && !empty($avatar['url'])) {
2121 return $avatar['url'];
2124 return DI::baseUrl() . $default;
2128 * Get avatar link for given contact id
2130 * @param integer $cid contact id
2131 * @param string $size One of the Proxy::SIZE_* constants
2132 * @param string $updated Contact update date
2133 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2134 * @return string avatar link
2136 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2138 // We have to fetch the "updated" variable when it wasn't provided
2139 // The parameter can be provided to improve performance
2140 if (empty($updated)) {
2141 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2142 $updated = $account['updated'] ?? '';
2143 $guid = $account['guid'] ?? '';
2146 $guid = urlencode($guid);
2148 $url = DI::baseUrl() . '/photo/contact/';
2150 case Proxy::SIZE_MICRO:
2151 $url .= Proxy::PIXEL_MICRO . '/';
2153 case Proxy::SIZE_THUMB:
2154 $url .= Proxy::PIXEL_THUMB . '/';
2156 case Proxy::SIZE_SMALL:
2157 $url .= Proxy::PIXEL_SMALL . '/';
2159 case Proxy::SIZE_MEDIUM:
2160 $url .= Proxy::PIXEL_MEDIUM . '/';
2162 case Proxy::SIZE_LARGE:
2163 $url .= Proxy::PIXEL_LARGE . '/';
2168 $query_params['ts'] = strtotime($updated);
2171 $query_params['static'] = true;
2174 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2178 * Get avatar link for given contact URL
2180 * @param string $url contact url
2181 * @param integer $uid user id
2182 * @param string $size One of the Proxy::SIZE_* constants
2183 * @return string avatar link
2185 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2188 "`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2189 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0
2191 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2192 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2196 * Get header link for given contact id
2198 * @param integer $cid contact id
2199 * @param string $size One of the Proxy::SIZE_* constants
2200 * @param string $updated Contact update date
2201 * @param bool $static If "true" a parameter is added to convert the header to a static one
2202 * @return string header link
2204 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2206 // We have to fetch the "updated" variable when it wasn't provided
2207 // The parameter can be provided to improve performance
2208 if (empty($updated) || empty($guid)) {
2209 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2210 $updated = $account['updated'] ?? '';
2211 $guid = $account['guid'] ?? '';
2214 $guid = urlencode($guid);
2216 $url = DI::baseUrl() . '/photo/header/';
2218 case Proxy::SIZE_MICRO:
2219 $url .= Proxy::PIXEL_MICRO . '/';
2221 case Proxy::SIZE_THUMB:
2222 $url .= Proxy::PIXEL_THUMB . '/';
2224 case Proxy::SIZE_SMALL:
2225 $url .= Proxy::PIXEL_SMALL . '/';
2227 case Proxy::SIZE_MEDIUM:
2228 $url .= Proxy::PIXEL_MEDIUM . '/';
2230 case Proxy::SIZE_LARGE:
2231 $url .= Proxy::PIXEL_LARGE . '/';
2237 $query_params['ts'] = strtotime($updated);
2240 $query_params['static'] = true;
2243 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2247 * Updates the avatar links in a contact only if needed
2249 * @param int $cid Contact id
2250 * @param string $avatar Link to avatar picture
2251 * @param bool $force force picture update
2252 * @param bool $create_cache Enforces the creation of cached avatar fields
2255 * @throws HTTPException\InternalServerErrorException
2256 * @throws HTTPException\NotFoundException
2257 * @throws \ImagickException
2259 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2261 $contact = DBA::selectFirst(
2263 ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2264 ['id' => $cid, 'self' => false]
2266 if (!DBA::isResult($contact)) {
2270 if (!Network::isValidHttpUrl($avatar)) {
2271 Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
2275 $uid = $contact['uid'];
2277 // Only update the cached photo links of public contacts when they already are cached
2278 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2279 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2280 $update_fields = ['avatar' => $avatar];
2281 if (!Network::isLocalLink($avatar)) {
2283 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2285 $img_str = $fetchResult->getBody();
2286 if (!empty($img_str)) {
2287 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2288 if ($image->isValid()) {
2289 $update_fields['blurhash'] = $image->getBlurHash();
2294 } catch (\Exception $exception) {
2295 Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
2298 } elseif (!empty($contact['blurhash'])) {
2299 $update_fields['blurhash'] = null;
2304 self::update($update_fields, ['id' => $cid]);
2305 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2310 // User contacts use are updated through the public contacts
2311 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2312 $pcid = self::getIdForURL($contact['url'], 0, false);
2313 if (!empty($pcid)) {
2314 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2315 self::updateAvatar($pcid, $avatar, $force, true);
2320 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2322 if ($default_avatar) {
2323 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2326 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2328 // Local contact avatars don't need to be cached
2329 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2330 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2333 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2334 if (Avatar::deleteCache($contact)) {
2338 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2340 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2342 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2343 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)
2345 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2348 // Use the data from the self account
2349 if (empty($fields)) {
2350 $local_uid = User::getIdForURL($contact['url']);
2351 if (!empty($local_uid)) {
2352 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2353 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2357 if (empty($fields)) {
2358 $update = ($contact['avatar'] != $avatar) || $force;
2362 $contact['photo'] ?? '',
2363 $contact['thumb'] ?? '',
2364 $contact['micro'] ?? '',
2367 foreach ($data as $image_uri) {
2368 $image_rid = Photo::ridFromURI($image_uri);
2369 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2370 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2377 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2379 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2380 $update = !empty($fields);
2381 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2387 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2390 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2391 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2392 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2401 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2402 // Collect all user contacts of the given public contact
2403 $personal_contacts = DBA::select(
2406 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]
2408 while ($personal_contact = DBA::fetch($personal_contacts)) {
2409 $cids[] = $personal_contact['id'];
2410 $uids[] = $personal_contact['uid'];
2412 DBA::close($personal_contacts);
2414 if (!empty($cids)) {
2415 // Delete possibly existing cached user contact avatars
2416 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2422 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2423 self::update($fields, ['id' => $cids]);
2426 public static function deleteContactByUrl(string $url)
2428 // Update contact data for all users
2429 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2430 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2431 while ($contact = DBA::fetch($contacts)) {
2432 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2433 self::remove($contact['id']);
2438 * Helper function for "updateFromProbe". Updates personal and public contact
2440 * @param integer $id contact id
2441 * @param integer $uid user id
2442 * @param integer $uri_id Uri-Id
2443 * @param string $url The profile URL of the contact
2444 * @param array $fields The fields that are updated
2446 * @throws \Exception
2448 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2450 if (!self::update($fields, ['id' => $id])) {
2451 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2455 self::setAccountUser($id, $uid, $uri_id, $url);
2457 // Archive or unarchive the contact.
2458 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2459 if (!DBA::isResult($contact)) {
2460 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2464 if (isset($fields['failed'])) {
2465 if ($fields['failed']) {
2466 self::markForArchival($contact);
2468 self::unmarkForArchival($contact);
2472 if ($contact['uid'] != 0) {
2476 // Update contact data for all users
2477 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2479 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2481 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
2482 $condition['network'][] = $contact['network'];
2485 self::update($fields, $condition);
2487 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2488 $condition['network'] = Protocol::OSTATUS;
2490 // If the contact failed, propagate the update fields to all contacts
2491 if (empty($fields['failed'])) {
2492 unset($fields['last-update']);
2493 unset($fields['success_update']);
2494 unset($fields['failure_update']);
2497 if (empty($fields)) {
2501 self::update($fields, $condition);
2505 * Create or update an "account-user" entry
2507 * @param integer $id
2508 * @param integer $uid
2509 * @param integer $uri_id
2510 * @param string $url
2513 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2515 if (empty($uri_id)) {
2519 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2520 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2521 if ($account_user['uid'] == $uid) {
2522 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2523 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2525 // This should never happen
2526 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]);
2530 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2531 if (!empty($account_user['id'])) {
2532 if ($account_user['id'] == $id) {
2533 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2535 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2536 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2537 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2540 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2541 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2542 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2543 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2545 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2550 * Remove duplicated contacts
2552 * @param string $nurl Normalised contact url
2553 * @param integer $uid User id
2555 * @throws \Exception
2557 public static function removeDuplicates(string $nurl, int $uid)
2559 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2560 $count = DBA::count('contact', $condition);
2565 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2566 if (!DBA::isResult($first_contact)) {
2567 // Shouldn't happen - so we handle it
2571 $first = $first_contact['id'];
2572 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2574 // Find all duplicates
2575 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2576 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2577 while ($duplicate = DBA::fetch($duplicates)) {
2578 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2582 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2584 DBA::close($duplicates);
2585 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2590 * Perform a contact update if the contact is outdated
2592 * @param integer $id contact id
2595 public static function updateByIdIfNeeded(int $id): bool
2597 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2598 if (empty($contact['url'])) {
2602 if (self::isLocal($contact['url'])) {
2606 $stamp = (float)microtime(true);
2607 self::updateFromProbe($id);
2608 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
2613 * Perform a contact update if the contact is outdated
2615 * @param string $url contact url
2618 public static function updateByUrlIfNeeded(string $url): bool
2620 $id = self::getIdForURL($url, 0, false);
2622 return self::updateByIdIfNeeded($id);
2624 return (bool)self::getIdForURL($url);
2628 * Updates contact record by provided id and optional network
2630 * @param integer $id contact id
2631 * @param string $network Optional network we are probing for
2633 * @throws HTTPException\InternalServerErrorException
2634 * @throws \ImagickException
2636 public static function updateFromProbe(int $id, string $network = ''): bool
2638 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2639 if (!DBA::isResult($contact)) {
2643 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2645 if ($data['network'] == Protocol::DIASPORA) {
2647 DI::dsprContact()->updateFromProbeArray($data);
2648 } catch (HTTPException\NotFoundException $e) {
2649 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2650 } catch (\InvalidArgumentException $e) {
2651 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2653 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2655 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2656 } catch (HTTPException\NotFoundException $e) {
2657 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2658 } catch (\InvalidArgumentException $e) {
2659 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2663 return self::updateFromProbeArray($id, $data);
2667 * Checks if the given contact has got local data
2670 * @param array $contact
2674 private static function hasLocalData(int $id, array $contact): bool
2676 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2677 // User contacts with the same uri-id exist
2679 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2680 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2683 if (DBA::exists('post-tag', ['cid' => $id])) {
2684 // Is tagged in a post
2687 if (DBA::exists('user-contact', ['cid' => $id])) {
2688 // Has got user-contact data
2691 if (Post::exists(['author-id' => $id])) {
2692 // Posts with this author exist
2695 if (Post::exists(['owner-id' => $id])) {
2696 // Posts with this owner exist
2699 if (Post::exists(['causer-id' => $id])) {
2700 // Posts with this causer exist
2703 // We don't have got this contact locally
2708 * Updates contact record by provided id and probed data
2710 * @param integer $id contact id
2711 * @param array $ret Probed data
2713 * @throws HTTPException\InternalServerErrorException
2714 * @throws \ImagickException
2716 private static function updateFromProbeArray(int $id, array $ret): bool
2719 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2720 This will reliably kill your communication with old Friendica contacts.
2723 // These fields aren't updated by this routine:
2727 'uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2728 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2729 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2730 'created', 'last-update'
2732 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2733 if (!DBA::isResult($contact)) {
2737 if (self::isLocal($ret['url'])) {
2738 if ($contact['uid'] == 0) {
2739 Logger::info('Local contacts are not updated here.');
2741 self::updateFromPublicContact($id, $contact);
2746 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2747 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2750 // Delete all contacts with the same URL
2751 self::deleteContactByUrl($ret['url']);
2755 $has_local_data = self::hasLocalData($id, $contact);
2757 $uid = $contact['uid'];
2758 unset($contact['uid']);
2760 $uriid = $contact['uri-id'];
2761 unset($contact['uri-id']);
2763 $pubkey = $contact['pubkey'];
2764 unset($contact['pubkey']);
2766 $created = $contact['created'];
2767 unset($contact['created']);
2769 $last_update = $contact['last-update'];
2770 unset($contact['last-update']);
2772 $contact['photo'] = $contact['avatar'];
2773 unset($contact['avatar']);
2775 $updated = DateTimeFormat::utcNow();
2777 if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
2778 // Periodical checks are only done on federated contacts
2779 $failed_next_update = null;
2780 $success_next_update = null;
2781 } elseif ($has_local_data) {
2782 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2783 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2784 } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
2785 $failed_next_update = DateTimeFormat::utc('now +6 month');
2786 $success_next_update = DateTimeFormat::utc('now +1 month');
2788 // We don't check connector networks very often to not run into API rate limits
2789 $failed_next_update = DateTimeFormat::utc('now +12 month');
2790 $success_next_update = DateTimeFormat::utc('now +12 month');
2793 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2794 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2795 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]);
2799 // We must not try to update relay contacts via probe. They are no real contacts.
2800 // We check after the probing to be able to correct falsely detected contact types.
2801 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2802 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))
2804 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]);
2805 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2809 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2810 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2811 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]);
2815 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2816 $cid = self::getIdForURL($ret['url'], 0, false);
2817 if (!empty($cid) && ($cid != $id)) {
2818 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2819 return self::updateFromProbeArray($cid, $ret);
2823 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2824 $ret['unsearchable'] = $ret['hide'];
2827 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2828 $ret['forum'] = false;
2829 $ret['prv'] = false;
2830 $ret['contact-type'] = $ret['account-type'];
2831 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2832 $ret['forum'] = (bool)!$ret['manually-approve'];
2833 $ret['prv'] = (bool)!$ret['forum'];
2837 $new_pubkey = $ret['pubkey'] ?? '';
2839 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2840 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2841 $apcontact = APContact::getByURL($ret['url'], false);
2842 if (!empty($apcontact['featured'])) {
2843 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2847 $ret['last-item'] = Probe::getLastUpdate($ret);
2848 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2852 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? '');
2854 // make sure to not overwrite existing values with blank entries except some technical fields
2855 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2856 foreach ($ret as $key => $val) {
2857 if (!array_key_exists($key, $contact)) {
2859 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2860 $ret[$key] = $contact[$key];
2861 } elseif ($ret[$key] != $contact[$key]) {
2866 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2869 unset($ret['last-item']);
2872 if (empty($uriid)) {
2876 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2877 self::updateAvatar($id, $ret['photo'], $update);
2881 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]);
2883 if (Contact\Relation::isDiscoverable($ret['url'])) {
2884 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2887 // Update the public contact
2889 $contact = self::getByURL($ret['url'], false, ['id']);
2890 if (!empty($contact['id'])) {
2891 self::updateFromProbeArray($contact['id'], $ret);
2898 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2899 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2900 $ret['updated'] = $updated;
2901 $ret['failed'] = false;
2902 $ret['next-update'] = $success_next_update;
2903 $ret['local-data'] = $has_local_data;
2905 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2906 if (empty($pubkey) && !empty($new_pubkey)) {
2907 $ret['pubkey'] = $new_pubkey;
2910 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2911 $ret['uri-date'] = $updated;
2914 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2915 $ret['name-date'] = $updated;
2918 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2919 $ret['last-update'] = $updated;
2920 $ret['success_update'] = $updated;
2923 unset($ret['photo']);
2925 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2927 if (Contact\Relation::isDiscoverable($ret['url'])) {
2928 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2934 private static function updateFromPublicContact(int $id, array $contact)
2936 $public = self::getByURL($contact['url'], false);
2940 foreach ($contact as $field => $value) {
2941 if ($field == 'uid') {
2944 if ($public[$field] != $value) {
2945 $fields[$field] = $public[$field];
2948 if (!empty($fields)) {
2949 self::update($fields, ['id' => $id, 'self' => false]);
2950 Logger::info('Updating local contact', ['id' => $id]);
2955 * Updates contact record by provided URL
2957 * @param integer $url contact url
2958 * @return integer Contact id
2959 * @throws HTTPException\InternalServerErrorException
2960 * @throws \ImagickException
2962 public static function updateFromProbeByURL(string $url): int
2964 $id = self::getIdForURL($url);
2970 self::updateFromProbe($id);
2976 * Detects the communication protocol for a given contact url.
2977 * This is used to detect Friendica contacts that we can communicate via AP.
2979 * @param string $url contact url
2980 * @param string $network Network of that contact
2981 * @return string with protocol
2983 public static function getProtocol(string $url, string $network): string
2985 if ($network != Protocol::DFRN) {
2989 $apcontact = APContact::getByURL($url);
2990 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2991 return Protocol::ACTIVITYPUB;
2998 * Takes a $uid and a url/handle and adds a new contact
3000 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
3001 * dfrn_request page.
3003 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
3006 * $return['success'] boolean true if successful
3007 * $return['message'] error text if success is false.
3009 * Takes a $uid and a url/handle and adds a new contact
3011 * @param int $uid The user id the contact should be created for
3012 * @param string $url The profile URL of the contact
3013 * @param string $network
3015 * @throws HTTPException\InternalServerErrorException
3016 * @throws HTTPException\NotFoundException
3017 * @throws \ImagickException
3019 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
3021 $result = ['cid' => -1, 'success' => false, 'message' => ''];
3023 // remove ajax junk, e.g. Twitter
3024 $url = str_replace('/#!/', '/', $url);
3026 if (!Network::isUrlAllowed($url)) {
3027 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
3031 if (Network::isUrlBlocked($url)) {
3032 $result['message'] = DI::l10n()->t('Blocked domain');
3037 $result['message'] = DI::l10n()->t('Connect URL missing.');
3041 $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
3043 Hook::callAll('follow', $arr);
3046 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
3050 if (!empty($arr['contact']['name'])) {
3052 $ret = $arr['contact'];
3055 $ret = Probe::uri($url, $network, $uid);
3057 // Ensure that the public contact exists
3058 if ($ret['network'] != Protocol::PHANTOM) {
3059 self::getIdForURL($url);
3063 if (($network != '') && ($ret['network'] != $network)) {
3064 $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
3068 // check if we already have a contact
3069 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
3070 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
3072 $protocol = self::getProtocol($ret['url'], $ret['network']);
3074 // This extra param just confuses things, remove it
3075 if ($protocol === Protocol::DIASPORA) {
3076 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
3079 // do we have enough information?
3080 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
3081 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
3082 if (empty($ret['poll'])) {
3083 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
3085 if (empty($ret['name'])) {
3086 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
3088 if (empty($ret['url'])) {
3089 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
3091 if (strpos($ret['url'], '@') !== false) {
3092 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
3093 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
3098 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3099 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3100 $ret['notify'] = '';
3103 if (!$ret['notify']) {
3104 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3107 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3109 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3111 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3114 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3115 $pending = (bool)$ret['manually-approve'];
3118 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3122 if (DBA::isResult($contact)) {
3124 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3126 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3128 if ($contact['pending'] && !empty($contact['hub-verify'])) {
3129 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3130 $fields['pending'] = false;
3133 self::update($fields, ['id' => $contact['id']]);
3135 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3137 // create contact record
3140 'created' => DateTimeFormat::utcNow(),
3141 'url' => $ret['url'],
3142 'nurl' => Strings::normaliseLink($ret['url']),
3143 'addr' => $ret['addr'],
3144 'alias' => $ret['alias'],
3145 'batch' => $ret['batch'],
3146 'notify' => $ret['notify'],
3147 'poll' => $ret['poll'],
3148 'poco' => $ret['poco'],
3149 'name' => $ret['name'],
3150 'nick' => $ret['nick'],
3151 'network' => $ret['network'],
3152 'baseurl' => $ret['baseurl'],
3153 'gsid' => $ret['gsid'] ?? null,
3154 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON,
3155 'protocol' => $protocol,
3156 'pubkey' => $ret['pubkey'],
3157 'rel' => $new_relation,
3158 'priority' => $ret['priority'],
3159 'writable' => $writeable,
3160 'hidden' => $hidden,
3163 'pending' => $pending,
3168 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3169 if (!DBA::isResult($contact)) {
3170 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3174 $contact_id = $contact['id'];
3175 $result['cid'] = $contact_id;
3177 if ($contact['contact-type'] == self::TYPE_COMMUNITY) {
3178 Circle::addMember(User::getDefaultGroupCircle($uid), $contact_id);
3180 Circle::addMember(User::getDefaultCircle($uid), $contact_id);
3183 // Update the avatar
3184 self::updateAvatar($contact_id, $ret['photo']);
3186 // pull feed and consume it, which should subscribe to the hub.
3187 if ($contact['network'] == Protocol::OSTATUS) {
3188 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3192 self::updateFromProbeArray($contact_id, $ret);
3195 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3196 } catch (\InvalidArgumentException $e) {
3197 Logger::notice($e->getMessage(), ['contact' => $contact]);
3201 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3207 * @param array $importer Owner (local user) data
3208 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3209 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3210 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3211 * @param string $note Introduction additional message
3212 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3213 * @throws HTTPException\InternalServerErrorException
3214 * @throws \ImagickException
3216 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3218 // Should always be set
3219 if (empty($datarray['author-id'])) {
3223 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl'];
3224 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3225 if (!DBA::isResult($pub_contact)) {
3226 // Should never happen
3230 // Contact is blocked at node-level
3231 if (self::isBlocked($datarray['author-id'])) {
3235 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3236 $name = $pub_contact['name'];
3237 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3238 $nick = $pub_contact['nick'];
3239 $network = $pub_contact['network'];
3241 // Ensure that we don't create a new contact when there already is one
3242 $cid = self::getIdForURL($url, $importer['uid']);
3244 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3247 self::clearFollowerFollowingEndpointCache($importer['uid']);
3249 if (!empty($contact)) {
3250 if (!empty($contact['pending'])) {
3251 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3255 // Contact is blocked at user-level
3257 !empty($contact['id']) && !empty($importer['id']) &&
3258 Contact\User::isBlocked($contact['id'], $importer['id'])
3263 // Make sure that the existing contact isn't archived
3264 self::unmarkForArchival($contact);
3266 if (($contact['rel'] == self::SHARING)
3267 || ($sharing && $contact['rel'] == self::FOLLOWER)
3270 ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3271 ['id' => $contact['id'], 'uid' => $importer['uid']]
3275 // Ensure to always have the correct network type, independent from the connection request method
3276 self::updateFromProbe($contact['id']);
3278 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3282 // send email notification to owner?
3283 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3284 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3288 // create contact record
3289 $contact_id = self::insert([
3290 'uid' => $importer['uid'],
3291 'created' => DateTimeFormat::utcNow(),
3293 'nurl' => Strings::normaliseLink($url),
3294 'baseurl' => $pub_contact['baseurl'] ?? '',
3297 'network' => $network,
3298 'rel' => self::FOLLOWER,
3305 // Ensure to always have the correct network type, independent from the connection request method
3306 self::updateFromProbe($contact_id);
3308 self::updateAvatar($contact_id, $photo, true);
3310 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3312 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo', 'contact-type'], ['id' => $contact_id]);
3314 /// @TODO Encapsulate this into a function/method
3315 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3316 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3317 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3318 // create notification
3319 if (is_array($contact_record)) {
3320 $intro = DI::introFactory()->createNew(
3322 $contact_record['id'],
3325 DI::intro()->save($intro);
3328 if ($contact_record['contact-type'] == self::TYPE_COMMUNITY) {
3329 Circle::addMember(User::getDefaultGroupCircle($importer['uid']), $contact_record['id']);
3331 Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
3334 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3335 DI::notify()->createFromArray([
3336 'type' => Notification\Type::INTRO,
3337 'otype' => Notification\ObjectType::INTRO,
3338 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3339 'uid' => $user['uid'],
3340 'cid' => $contact_record['id'],
3341 'link' => DI::baseUrl() . '/notifications/intros',
3344 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3345 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3346 self::createFromProbeForUser($importer['uid'], $url, $network);
3349 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3350 $fields = ['pending' => false];
3351 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3352 $fields['rel'] = self::FRIEND;
3355 self::update($fields, $condition);
3365 * Update the local relationship when a local user loses a follower
3367 * @param array $contact User-specific contact (uid != 0) array
3369 * @throws HTTPException\InternalServerErrorException
3370 * @throws \ImagickException
3372 public static function removeFollower(array $contact)
3374 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3375 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3376 } elseif (!empty($contact['id'])) {
3377 self::remove($contact['id']);
3379 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3383 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3385 self::clearFollowerFollowingEndpointCache($contact['uid']);
3387 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3388 if (!empty($cdata['public'])) {
3389 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3394 * Update the local relationship when a local user unfollow a contact.
3395 * Removes the contact for sharing-only protocols (feed and mail).
3397 * @param array $contact User-specific contact (uid != 0) array
3398 * @throws HTTPException\InternalServerErrorException
3400 public static function removeSharer(array $contact)
3402 self::clearFollowerFollowingEndpointCache($contact['uid']);
3404 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3405 self::remove($contact['id']);
3407 self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
3410 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3414 * Create a birthday event.
3416 * Update the year and the birthday.
3418 public static function updateBirthdays()
3422 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3423 AND NOT `contact`.`pending`
3424 AND NOT `contact`.`hidden`
3425 AND NOT `contact`.`blocked`
3426 AND NOT `contact`.`archive`
3427 AND NOT `contact`.`deleted`',
3433 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3435 while ($contact = DBA::fetch($contacts)) {
3436 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3438 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3440 if (Event::createBirthday($contact, $nextbd)) {
3444 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3445 ['id' => $contact['id']]
3449 DBA::close($contacts);
3453 * Remove the unavailable contact ids from the provided list
3455 * @param array $contact_ids Contact id list
3457 * @throws \Exception
3459 public static function pruneUnavailable(array $contact_ids): array
3461 if (empty($contact_ids)) {
3465 $contacts = self::selectToArray(['id'], [
3466 'id' => $contact_ids,
3472 return array_column($contacts, 'id');
3476 * Returns a magic link to authenticate remote visitors
3478 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3480 * @param string $contact_url The address of the target contact profile
3481 * @param string $url An url that we will be redirected to after the authentication
3483 * @return string with "redir" link
3484 * @throws HTTPException\InternalServerErrorException
3485 * @throws \ImagickException
3487 public static function magicLink(string $contact_url, string $url = ''): string
3489 if (!DI::userSession()->isAuthenticated()) {
3490 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3493 $contact = self::getByURL($contact_url, false);
3494 if (empty($contact)) {
3495 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3498 // Prevents endless loop in case only a non-public contact exists for the contact URL
3499 unset($contact['uid']);
3501 return self::magicLinkByContact($contact, $url ?: $contact_url);
3505 * Returns a magic link to authenticate remote visitors
3507 * @param integer $cid The contact id of the target contact profile
3508 * @param string $url An url that we will be redirected to after the authentication
3510 * @return string with "redir" link
3511 * @throws HTTPException\InternalServerErrorException
3512 * @throws \ImagickException
3514 public static function magicLinkById(int $cid, string $url = ''): string
3516 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], ['id' => $cid]);
3518 return self::magicLinkByContact($contact, $url);
3522 * Returns a magic link to authenticate remote visitors
3524 * @param array $contact The contact array with "uid", "network" and "url"
3525 * @param string $url An url that we will be redirected to after the authentication
3527 * @return string with "redir" link
3528 * @throws HTTPException\InternalServerErrorException
3529 * @throws \ImagickException
3531 public static function magicLinkByContact(array $contact, string $url = ''): string
3533 $destination = $url ?: (!Network::isValidHttpUrl($contact['url']) && !empty($contact['alias']) && Network::isValidHttpUrl($contact['alias']) ? $contact['alias'] : $contact['url']);
3535 if (!DI::userSession()->isAuthenticated()) {
3536 return $destination;
3539 // Only redirections to the same host do make sense
3540 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3544 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3545 return 'contact/' . $contact['id'] . '/conversations';
3548 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3549 return $destination;
3552 if (empty($contact['id'])) {
3553 return $destination;
3556 $redirect = 'contact/redir/' . $contact['id'];
3558 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3559 $redirect .= '?url=' . $url;
3566 * Is the contact a group?
3568 * @param integer $contactid ID of the contact
3570 * @return boolean "true" if it is a group
3572 public static function isGroup(int $contactid): bool
3574 $fields = ['contact-type'];
3575 $condition = ['id' => $contactid];
3576 $contact = DBA::selectFirst('contact', $fields, $condition);
3577 if (!DBA::isResult($contact)) {
3582 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3586 * Can the remote contact receive private messages?
3588 * @param array $contact
3591 public static function canReceivePrivateMessages(array $contact): bool
3593 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3594 $self = $contact['self'] ?? false;
3596 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3600 * Search contact table by nick or name
3602 * @param string $search Name or nick
3603 * @param string $mode Search mode (e.g. "community")
3604 * @param bool $show_blocked Show users from blocked servers. Default is false
3605 * @param int $uid User ID
3606 * @param int $limit Maximum amount of returned values
3607 * @param int $offset Limit offset
3609 * @return array with search results
3610 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3612 public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
3614 if (empty($search)) {
3618 // check supported networks
3619 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3620 if (DI::config()->get('system', 'diaspora_enabled')) {
3621 $networks[] = Protocol::DIASPORA;
3624 if (!DI::config()->get('system', 'ostatus_disabled')) {
3625 $networks[] = Protocol::OSTATUS;
3629 'network' => $networks,
3630 'server-failed' => false,
3633 'unsearchable' => false,
3637 if (!$show_blocked) {
3638 $condition['server-blocked'] = true;
3642 $condition['blocked'] = false;
3644 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3647 // check if we search only communities or every contact
3648 if ($mode === 'community') {
3649 $condition['contact-type'] = self::TYPE_COMMUNITY;
3656 if (!empty($limit) && !empty($offset)) {
3657 $params['limit'] = [$offset, $limit];
3658 } elseif (!empty($limit)) {
3659 $params['limit'] = $limit;
3662 $condition = DBA::mergeConditions(
3664 ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]
3667 return DBA::selectToArray('account-user-view', [], $condition, $params);
3671 * Add public contacts from an array
3673 * @param array $urls
3674 * @return array result "count", "added" and "updated"
3676 public static function addByUrls(array $urls): array
3683 foreach ($urls as $url) {
3684 if (empty($url) || !is_string($url)) {
3687 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3688 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3689 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3691 } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3693 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3695 } catch (\InvalidArgumentException $e) {
3696 Logger::notice($e->getMessage(), ['contact' => $contact]);
3704 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3708 * Returns a random, global contact array of the current node
3710 * @return array The profile array
3713 public static function getRandomContact(): array
3715 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], [
3716 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3717 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3718 ], ['order' => ['RAND()']]);
3720 if (DBA::isResult($contact)) {
3728 * Checks, if contacts with the given condition exists
3730 * @param array $condition
3733 * @throws \Exception
3735 public static function exists(array $condition): bool
3737 return DBA::exists('contact', $condition);