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\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Contact\LocalRelationship\Entity\LocalRelationship;
27 use Friendica\Content\Conversation as ConversationContent;
28 use Friendica\Content\Pager;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\Database;
37 use Friendica\Database\DBA;
39 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
40 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\Probe;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\ActivityPub;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy;
51 use Friendica\Util\Strings;
52 use Friendica\Worker\UpdateContact;
55 * functions for interacting with a contact
59 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
60 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
61 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
67 const LOCK_INSERT = 'contact-insert';
72 * TYPE_UNKNOWN - unknown type
74 * TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
77 * TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_SOAPBOX
83 * TYPE_COMMUNITY - the account is community group
84 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
86 * TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const TYPE_UNKNOWN = -1;
91 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
92 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
93 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
94 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
95 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
106 const NOTHING = 0; // There is no relationship between the contact and the user
107 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
108 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
109 const FRIEND = 3; // There is a mutual relationship between the contact and the user
110 const SELF = 4; // This is the user theirself
115 /** @deprecated Use Entity\LocalRelationship::MIRROR_DEACTIVATED instead */
116 const MIRROR_DEACTIVATED = LocalRelationship::MIRROR_DEACTIVATED;
117 /** @deprecated Now does the same as MIRROR_OWN_POST */
118 const MIRROR_FORWARDED = 1;
119 /** @deprecated Use Entity\LocalRelationship::MIRROR_OWN_POST instead */
120 const MIRROR_OWN_POST = LocalRelationship::MIRROR_OWN_POST;
121 /** @deprecated Use Entity\LocalRelationship::MIRROR_NATIVE_RESHARE instead */
122 const MIRROR_NATIVE_RESHARE = LocalRelationship::MIRROR_NATIVE_RESHARE;
125 * @param array $fields Array of selected fields, empty for all
126 * @param array $condition Array of fields for condition
127 * @param array $params Array of several parameters
131 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
133 return DBA::selectToArray('contact', $fields, $condition, $params);
137 * @param array $fields Array of selected fields, empty for all
138 * @param array $condition Array of fields for condition
139 * @param array $params Array of several parameters
143 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
145 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
151 * @param array $fields Array of selected fields, empty for all
152 * @param array $condition Array of fields for condition
153 * @param array $params Array of several parameters
157 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
159 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
163 * @param array $fields Array of selected fields, empty for all
164 * @param array $condition Array of fields for condition
165 * @param array $params Array of several parameters
169 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
171 return DBA::selectFirst('account-view', $fields, $condition, $params);
175 * Insert a row into the contact table
176 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
178 * @param array $fields field array
179 * @param int $duplicate_mode Do an update on a duplicate entry
181 * @return int id of the created contact
184 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
186 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
187 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
190 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
192 if (empty($fields['created'])) {
193 $fields['created'] = DateTimeFormat::utcNow();
196 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
197 DBA::insert('contact', $fields, $duplicate_mode);
198 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
199 if (!DBA::isResult($contact)) {
201 Logger::warning('Created contact could not be found', ['fields' => $fields]);
205 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
206 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
207 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
208 if (empty($account_user['id'])) {
209 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
210 } elseif ($account_user['id'] != $contact['id']) {
211 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
212 if (!empty($duplicate['id'])) {
213 $ret = Contact::deleteById($contact['id']);
214 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']]);
215 $contact = $duplicate;
217 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
218 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']]);
222 Contact\User::insertForContactArray($contact);
224 return $contact['id'];
228 * Delete contact by id
233 public static function deleteById(int $id): bool
235 Logger::debug('Delete contact', ['id' => $id]);
236 DBA::delete('account-user', ['id' => $id]);
237 return DBA::delete('contact', ['id' => $id]);
241 * Updates rows in the contact table
243 * @param array $fields contains the fields that are updated
244 * @param array $condition condition array with the key values
245 * @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)
247 * @return boolean was the update successful?
249 * @todo Let's get rid of boolean type of $old_fields
251 public static function update(array $fields, array $condition, $old_fields = []): bool
253 // Apply changes to the "user-contact" table on dedicated fields
254 Contact\User::updateByContactUpdate($fields, $condition);
256 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
257 return DBA::update('contact', $fields, $condition, $old_fields);
261 * @param integer $id Contact ID
262 * @param array $fields Array of selected fields, empty for all
263 * @return array|boolean Contact record if it exists, false otherwise
266 public static function getById(int $id, array $fields = [])
268 return DBA::selectFirst('contact', $fields, ['id' => $id]);
272 * Fetch the first contact with the provided uri-id.
274 * @param integer $uri_id uri-id of the contact
275 * @param array $fields Array of selected fields, empty for all
276 * @return array|boolean Contact record if it exists, false otherwise
279 public static function getByUriId(int $uri_id, array $fields = [])
281 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
285 * Fetch all remote contacts for a given contact url
287 * @param string $url The URL of the contact
288 * @param array $fields The wanted fields
290 * @return array all remote contacts
294 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
298 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
299 while ($contact = DBA::fetch($remote_contacts)) {
300 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
303 $remote[$contact['uid']] = $contact['id'];
305 DBA::close($remote_contacts);
311 * Fetches a contact by a given url
313 * @param string $url profile url
314 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
315 * @param array $fields Field list
316 * @param integer $uid User ID of the contact
317 * @return array contact array
319 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
321 if ($update || is_null($update)) {
322 $cid = self::getIdForURL($url, $uid, $update);
327 $contact = self::getById($cid, $fields);
328 if (empty($contact)) {
334 // Add internal fields
336 if (!empty($fields)) {
337 foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
338 if (!in_array($internal, $fields)) {
339 $fields[] = $internal;
340 $removal[] = $internal;
345 // We first try the nurl (http://server.tld/nick), most common case
346 $options = ['order' => ['id']];
347 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
349 // Then the addr (nick@server.tld)
350 if (!DBA::isResult($contact)) {
351 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
354 // Then the alias (which could be anything)
355 if (!DBA::isResult($contact)) {
356 // The link could be provided as http although we stored it as https
357 $ssl_url = str_replace('http://', 'https://', $url);
358 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
359 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
362 if (!DBA::isResult($contact)) {
366 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
368 // Update the contact in the background if needed
369 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
371 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
372 } catch (\InvalidArgumentException $e) {
373 Logger::notice($e->getMessage(), ['contact' => $contact]);
377 // Remove the internal fields
378 foreach ($removal as $internal) {
379 unset($contact[$internal]);
386 * Fetches a contact for a given user by a given url.
387 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
389 * @param string $url profile url
390 * @param integer $uid User ID of the contact
391 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
392 * @param array $fields Field list
393 * @return array contact array
395 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
398 $contact = self::getByURL($url, $update, $fields, $uid);
399 if (!empty($contact)) {
400 if (!empty($contact['id'])) {
401 $contact['cid'] = $contact['id'];
408 $contact = self::getByURL($url, $update, $fields);
409 if (!empty($contact['id'])) {
411 $contact['zid'] = $contact['id'];
417 * Checks if a contact uses a specific platform
420 * @param string $platform
423 public static function isPlatform(string $url, string $platform): bool
425 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
429 * Tests if the given contact is a follower
431 * @param int $cid Either public contact id or user's contact id
432 * @param int $uid User ID
433 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
435 * @return boolean is the contact id a follower?
436 * @throws HTTPException\InternalServerErrorException
437 * @throws \ImagickException
439 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
441 if (Contact\User::isBlocked($cid, $uid)) {
445 $cdata = self::getPublicAndUserContactID($cid, $uid);
446 if (empty($cdata['user'])) {
450 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
452 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
454 return DBA::exists('contact', $condition);
458 * Tests if the given contact url is a follower
460 * @param string $url Contact URL
461 * @param int $uid User ID
462 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
464 * @return boolean is the contact id a follower?
465 * @throws HTTPException\InternalServerErrorException
466 * @throws \ImagickException
468 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
470 $cid = self::getIdForURL($url, $uid);
476 return self::isFollower($cid, $uid, $strict);
480 * Tests if the given user shares with the given contact
482 * @param int $cid Either public contact id or user's contact id
483 * @param int $uid User ID
484 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
486 * @return boolean is the contact sharing with given user?
487 * @throws HTTPException\InternalServerErrorException
488 * @throws \ImagickException
490 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
492 if (Contact\User::isBlocked($cid, $uid)) {
496 $cdata = self::getPublicAndUserContactID($cid, $uid);
497 if (empty($cdata['user'])) {
501 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
503 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
505 return DBA::exists('contact', $condition);
509 * Tests if the given user follow the given contact url
511 * @param string $url Contact URL
512 * @param int $uid User ID
513 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
515 * @return boolean is the contact url being followed?
516 * @throws HTTPException\InternalServerErrorException
517 * @throws \ImagickException
519 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
521 $cid = self::getIdForURL($url, $uid);
527 return self::isSharing($cid, $uid, $strict);
531 * Get the basepath for a given contact link
533 * @param string $url The contact link
534 * @param boolean $dont_update Don't update the contact
536 * @return string basepath
537 * @throws HTTPException\InternalServerErrorException
538 * @throws \ImagickException
540 public static function getBasepath(string $url, bool $dont_update = false): string
542 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
543 if (!DBA::isResult($contact)) {
547 if (!empty($contact['baseurl'])) {
548 return $contact['baseurl'];
549 } elseif ($dont_update) {
553 // Update the existing contact
554 self::updateFromProbe($contact['id']);
556 // And fetch the result
557 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
558 if (empty($contact['baseurl'])) {
559 Logger::info('No baseurl for contact', ['url' => $url]);
563 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
564 return $contact['baseurl'];
568 * Check if the given contact url is on the same server
570 * @param string $url The contact link
572 * @return boolean Is it the same server?
574 public static function isLocal(string $url): bool
576 if (!parse_url($url, PHP_URL_SCHEME)) {
577 $addr_parts = explode('@', $url);
578 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
581 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
585 * Check if the given contact ID is on the same server
587 * @param string $url The contact link
588 * @return boolean Is it the same server?
590 public static function isLocalById(int $cid): bool
592 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
593 if (!DBA::isResult($contact)) {
597 if (empty($contact['baseurl'])) {
598 $baseurl = self::getBasepath($contact['url'], true);
600 $baseurl = $contact['baseurl'];
603 return Strings::compareLink($baseurl, DI::baseUrl());
607 * Returns the public contact id of the given user id
609 * @param integer $uid User ID
611 * @return integer|boolean Public contact id for given user id
614 public static function getPublicIdByUserId(int $uid)
616 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
617 if (!DBA::isResult($self)) {
620 return self::getIdForURL($self['url']);
624 * Returns the contact id for the user and the public contact id for a given contact id
626 * @param int $cid Either public contact id or user's contact id
627 * @param int $uid User ID
629 * @return array with public and user's contact id
630 * @throws HTTPException\InternalServerErrorException
631 * @throws \ImagickException
633 public static function getPublicAndUserContactID(int $cid, int $uid): array
635 // We have to use the legacy function as long as the post update hasn't finished
636 if (DI::keyValue()->get('post_update_version') < 1427) {
637 return self::legacyGetPublicAndUserContactID($cid, $uid);
640 if (empty($uid) || empty($cid)) {
644 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
645 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
649 $pcid = $contact['pid'];
650 if ($contact['uid'] == $uid) {
651 $ucid = $contact['id'];
653 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
654 if (DBA::isResult($contact)) {
655 $ucid = $contact['id'];
661 return ['public' => $pcid, 'user' => $ucid];
665 * Helper function for "getPublicAndUserContactID"
667 * @param int $cid Either public contact id or user's contact id
668 * @param int $uid User ID
669 * @return array with public and user's contact id
670 * @throws HTTPException\InternalServerErrorException
671 * @throws \ImagickException
673 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
675 if (empty($uid) || empty($cid)) {
679 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
680 if (!DBA::isResult($contact)) {
684 // We quit when the user id don't match the user id of the provided contact
685 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
689 if ($contact['uid'] != 0) {
690 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
694 $ucid = $contact['id'];
696 $pcid = $contact['id'];
697 $ucid = self::getIdForURL($contact['url'], $uid);
700 return ['public' => $pcid, 'user' => $ucid];
704 * Returns contact details for a given contact id in combination with a user id
706 * @param int $cid A contact ID
707 * @param int $uid The User ID
708 * @param array $fields The selected fields for the contact
709 * @return array The contact details
713 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
715 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
717 if (!DBA::isResult($contact)) {
725 * Creates the self-contact for the provided user id
728 * @return bool Operation success
729 * @throws HTTPException\InternalServerErrorException
731 public static function createSelfFromUserId(int $uid): bool
733 $user = DBA::selectFirst(
735 ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
736 ['uid' => $uid, 'account_expired' => false]
738 if (!DBA::isResult($user)) {
743 'uid' => $user['uid'],
744 'created' => DateTimeFormat::utcNow(),
746 'name' => $user['username'],
747 'nick' => $user['nickname'],
748 'pubkey' => $user['pubkey'],
749 'prvkey' => $user['prvkey'],
750 'photo' => User::getAvatarUrl($user),
751 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
752 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
755 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
756 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
757 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
758 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
759 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
760 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
761 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
762 'name-date' => DateTimeFormat::utcNow(),
763 'uri-date' => DateTimeFormat::utcNow(),
764 'avatar-date' => DateTimeFormat::utcNow(),
770 // Only create the entry if it doesn't exist yet
771 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
772 $return = (bool)self::insert($contact);
775 // Create the public contact
776 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
777 $contact['self'] = false;
779 $contact['prvkey'] = null;
781 self::insert($contact, Database::INSERT_IGNORE);
788 * Updates the self-contact for the provided user id
791 * @param bool $update_avatar Force the avatar update
792 * @return bool "true" if updated
793 * @throws HTTPException\InternalServerErrorException
795 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
798 'id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
799 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
800 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'
802 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
803 if (!DBA::isResult($self)) {
807 $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
808 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
809 if (!DBA::isResult($user)) {
814 'name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
815 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'
817 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
818 if (!DBA::isResult($profile)) {
822 $file_suffix = 'jpg';
823 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
826 'name' => $user['username'],
827 'nick' => $user['nickname'],
828 'avatar-date' => $self['avatar-date'],
829 'location' => Profile::formatLocation($profile),
830 'about' => $profile['about'],
831 'keywords' => $profile['pub_keywords'],
832 'contact-type' => $user['account-type'],
833 'prvkey' => $user['prvkey'],
834 'pubkey' => $user['pubkey'],
835 'xmpp' => $profile['xmpp'],
836 'matrix' => $profile['matrix'],
837 'network' => Protocol::DFRN,
839 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
840 'nurl' => Strings::normaliseLink($url),
841 'uri-id' => ItemURI::getIdByURI($url),
842 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
843 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
844 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
845 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
846 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
849 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
850 if (DBA::isResult($avatar)) {
851 if ($update_avatar) {
852 $fields['avatar-date'] = DateTimeFormat::utcNow();
855 // Creating the path to the avatar, beginning with the file suffix
856 $types = Images::supportedTypes();
857 if (isset($types[$avatar['type']])) {
858 $file_suffix = $types[$avatar['type']];
861 // We are adding a timestamp value so that other systems won't use cached content
862 $timestamp = strtotime($fields['avatar-date']);
864 $prefix = DI::baseUrl() . '/photo/' . $avatar['resource-id'] . '-';
865 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
867 $fields['photo'] = $prefix . '4' . $suffix;
868 $fields['thumb'] = $prefix . '5' . $suffix;
869 $fields['micro'] = $prefix . '6' . $suffix;
871 // We hadn't found a photo entry, so we use the default avatar
872 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
873 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
874 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
877 $fields['avatar'] = User::getAvatarUrl($user);
878 $fields['header'] = User::getBannerUrl($user);
879 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
880 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
881 $fields['unsearchable'] = !$profile['net-publish'];
882 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
886 foreach ($fields as $field => $content) {
887 if ($self[$field] != $content) {
893 if ($fields['name'] != $self['name']) {
894 $fields['name-date'] = DateTimeFormat::utcNow();
896 $fields['updated'] = DateTimeFormat::utcNow();
897 self::update($fields, ['id' => $self['id']]);
899 // Update the other contacts as well
900 unset($fields['prvkey']);
901 $fields['self'] = false;
902 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
904 // Update the profile
906 'photo' => User::getAvatarUrl($user),
907 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
910 DBA::update('profile', $fields, ['uid' => $uid]);
917 * Marks a contact for removal
919 * @param int $id contact id
921 * @throws HTTPException\InternalServerErrorException
923 public static function remove(int $id)
925 // We want just to make sure that we don't delete our "self" contact
926 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
927 if (!DBA::isResult($contact)) {
931 DBA::delete('account-user', ['id' => $id]);
933 self::clearFollowerFollowingEndpointCache($contact['uid']);
935 // Archive the contact
936 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
938 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
939 Avatar::deleteCache($contact);
942 // Delete it in the background
943 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
947 * Unfollow the remote contact
949 * @param array $contact Target user-specific contact (uid != 0) array
951 * @throws HTTPException\InternalServerErrorException
952 * @throws \ImagickException
954 public static function unfollow(array $contact): void
956 if (empty($contact['network'])) {
957 throw new \InvalidArgumentException('Empty network in contact array');
960 if (empty($contact['uid'])) {
961 throw new \InvalidArgumentException('Unexpected public contact record');
964 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
965 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
966 if (!empty($cdata['public'])) {
967 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
971 self::removeSharer($contact);
975 * Revoke follow privileges of the remote user contact
977 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
979 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
981 * @throws HTTPException\InternalServerErrorException
982 * @throws \ImagickException
984 public static function revokeFollow(array $contact): void
986 if (empty($contact['network'])) {
987 throw new \InvalidArgumentException('Empty network in contact array');
990 if (empty($contact['uid'])) {
991 throw new \InvalidArgumentException('Unexpected public contact record');
994 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
995 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
996 if (!empty($cdata['public'])) {
997 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1001 self::removeFollower($contact);
1005 * Completely severs a relationship with a contact
1007 * @param array $contact User-specific contact (uid != 0) array
1009 * @throws HTTPException\InternalServerErrorException
1010 * @throws \ImagickException
1012 public static function terminateFriendship(array $contact)
1014 if (empty($contact['network'])) {
1015 throw new \InvalidArgumentException('Empty network in contact array');
1018 if (empty($contact['uid'])) {
1019 throw new \InvalidArgumentException('Unexpected public contact record');
1022 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1024 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1025 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1028 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1029 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1032 self::remove($contact['id']);
1035 private static function clearFollowerFollowingEndpointCache(int $uid)
1041 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1042 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1046 * Marks a contact for archival after a communication issue delay
1048 * Contact has refused to recognise us as a friend. We will start a countdown.
1049 * If they still don't recognise us in 32 days, the relationship is over,
1050 * and we won't waste any more time trying to communicate with them.
1051 * This provides for the possibility that their database is temporarily messed
1052 * up or some other transient event and that there's a possibility we could recover from it.
1054 * @param array $contact contact to mark for archival
1056 * @throws HTTPException\InternalServerErrorException
1058 public static function markForArchival(array $contact)
1060 if (!isset($contact['url']) && !empty($contact['id'])) {
1061 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1062 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1063 if (!DBA::isResult($contact)) {
1066 } elseif (!isset($contact['url'])) {
1067 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1070 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1072 // Contact already archived or "self" contact? => nothing to do
1073 if ($contact['archive'] || $contact['self']) {
1077 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1078 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1079 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1082 * We really should send a notification to the owner after 2-3 weeks
1083 * so they won't be surprised when the contact vanishes and can take
1084 * remedial action if this was a serious mistake or glitch
1087 /// @todo Check for contact vitality via probing
1088 $archival_days = DI::config()->get('system', 'archival_days', 32);
1090 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1091 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1092 /* Relationship is really truly dead. archive them rather than
1093 * delete, though if the owner tries to unarchive them we'll start
1094 * the whole process over again.
1096 self::update(['archive' => true], ['id' => $contact['id']]);
1097 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1103 * Cancels the archival countdown
1105 * @see Contact::markForArchival()
1107 * @param array $contact contact to be unmarked for archival
1109 * @throws \Exception
1111 public static function unmarkForArchival(array $contact)
1113 // Always unarchive the relay contact entry
1114 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1115 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1116 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1117 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1118 self::update($fields, $condition);
1122 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1123 $exists = DBA::exists('contact', $condition);
1125 // We don't need to update, we never marked this contact for archival
1130 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1132 if (!isset($contact['url']) && !empty($contact['id'])) {
1133 $fields = ['id', 'url', 'batch'];
1134 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1135 if (!DBA::isResult($contact)) {
1140 // It's a miracle. Our dead contact has inexplicably come back to life.
1141 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1142 self::update($fields, ['id' => $contact['id']]);
1143 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1147 * Returns the data array for the photo menu of a given contact
1149 * @param array $contact contact
1150 * @param int $uid Visitor user id
1152 * @throws HTTPException\InternalServerErrorException
1153 * @throws \ImagickException
1155 public static function photoMenu(array $contact, int $uid): array
1157 // Anonymous visitor
1159 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1166 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1167 $profile_link = 'contact/redir/' . $contact['id'];
1168 $status_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
1169 $photos_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
1170 $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
1172 $profile_link = $contact['url'];
1175 if ($profile_link === 'mailbox') {
1179 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1180 $pm_url = 'message/new/' . $contact['id'];
1183 $contact_url = 'contact/' . $contact['id'];
1184 $posts_link = 'contact/' . $contact['id'] . '/conversations';
1187 $unfollow_link = '';
1188 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1189 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1190 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1191 } elseif (!$contact['pending']) {
1192 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1198 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1200 if (empty($contact['uid'])) {
1202 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1203 'network' => [DI::l10n()->t('Network Posts'), $posts_link, false],
1204 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1205 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1206 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1210 'status' => [DI::l10n()->t('View Status'), $status_link, true],
1211 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
1212 'photos' => [DI::l10n()->t('View Photos'), $photos_link, true],
1213 'network' => [DI::l10n()->t('Network Posts'), $posts_link, false],
1214 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
1215 'pm' => [DI::l10n()->t('Send PM'), $pm_url, false],
1216 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
1217 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
1220 if (!empty($contact['pending'])) {
1222 $intro = DI::intro()->selectForContact($contact['id']);
1223 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1224 } catch (IntroductionNotFoundException $exception) {
1225 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1230 $args = ['contact' => $contact, 'menu' => &$menu];
1232 Hook::callAll('contact_photo_menu', $args);
1234 $menucondensed = [];
1236 foreach ($menu as $menuname => $menuitem) {
1237 if ($menuitem[1] != '') {
1238 $menucondensed[$menuname] = $menuitem;
1242 return $menucondensed;
1246 * Fetch the contact id for a given URL and user
1248 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1249 * `addr` or `alias`.
1251 * If there's no record and we aren't looking for a public contact, we quit.
1252 * If there's one, we check that it isn't time to update the picture else we
1253 * directly return the found contact id.
1255 * Second, we probe the provided $url whether it's http://server.tld/profile or
1256 * nick@server.tld. We quit if we can't get any info back.
1258 * Third, we create the contact record if it doesn't exist
1260 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1261 * if there's any updates
1263 * @param string $url Contact URL
1264 * @param integer $uid The user id for the contact (0 = public contact)
1265 * @param boolean $update true = always update, false = never update, null = update when not found
1266 * @param array $default Default value for creating the contact when everything else fails
1268 * @return integer Contact ID
1269 * @throws HTTPException\InternalServerErrorException
1270 * @throws \ImagickException
1272 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1277 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1281 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
1283 if (!empty($contact)) {
1284 $contact_id = $contact['id'];
1286 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
1288 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1290 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
1291 } catch (\InvalidArgumentException $e) {
1292 Logger::notice($e->getMessage(), ['contact' => $contact]);
1296 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1297 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1300 } elseif ($uid != 0) {
1301 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1303 } elseif (empty($default) && !is_null($update) && !$update) {
1304 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1310 if (empty($default['network']) || $update) {
1311 $data = Probe::uri($url, '', $uid);
1313 // Take the default values when probing failed
1314 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1315 $data = array_merge($data, $default);
1317 } elseif (!empty($default['network'])) {
1321 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1322 // Fetch data for the public contact via the first found personal contact
1323 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1325 'name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1326 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1327 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'
1330 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1331 if (!DBA::isResult($personal_contact)) {
1332 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1335 if (DBA::isResult($personal_contact)) {
1336 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1337 $data = $personal_contact;
1338 $data['photo'] = $personal_contact['avatar'];
1339 $data['account-type'] = $personal_contact['contact-type'];
1340 $data['hide'] = $personal_contact['unsearchable'];
1341 unset($data['avatar']);
1342 unset($data['contact-type']);
1343 unset($data['unsearchable']);
1347 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1348 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1352 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1353 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1358 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1359 if (!empty($data['alias'])) {
1360 $urls[] = Strings::normaliseLink($data['alias']);
1362 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1363 if (!empty($contact['id'])) {
1364 $contact_id = $contact['id'];
1365 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1370 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1373 'url' => $data['url'],
1374 'nurl' => Strings::normaliseLink($data['url']),
1375 'network' => $data['network'],
1376 'created' => DateTimeFormat::utcNow(),
1377 'rel' => self::SHARING,
1384 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1386 // Before inserting we do check if the entry does exist now.
1387 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1388 if (DBA::isResult($contact)) {
1389 $contact_id = $contact['id'];
1390 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1392 $contact_id = self::insert($fields);
1394 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1399 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1403 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1406 if ($data['network'] == Protocol::DIASPORA) {
1408 DI::dsprContact()->updateFromProbeArray($data);
1409 } catch (HTTPException\NotFoundException $e) {
1410 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1411 } catch (\InvalidArgumentException $e) {
1412 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1414 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1416 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1417 } catch (HTTPException\NotFoundException $e) {
1418 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1419 } catch (\InvalidArgumentException $e) {
1420 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1424 self::updateFromProbeArray($contact_id, $data);
1426 // Don't return a number for a deleted account
1427 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1428 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1436 * Checks if the contact is archived
1438 * @param int $cid contact id
1440 * @return boolean Is the contact archived?
1441 * @throws HTTPException\InternalServerErrorException
1443 public static function isArchived(int $cid): bool
1449 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1450 if (!DBA::isResult($contact)) {
1454 if ($contact['archive']) {
1458 // Check status of ActivityPub endpoints
1459 $apcontact = APContact::getByURL($contact['url'], false);
1460 if (!empty($apcontact)) {
1461 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1465 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1470 // Check status of Diaspora endpoints
1471 if (!empty($contact['batch'])) {
1472 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1473 return DBA::exists('contact', $condition);
1480 * Checks if the contact is blocked
1482 * @param int $cid contact id
1483 * @return boolean Is the contact blocked?
1484 * @throws HTTPException\InternalServerErrorException
1486 public static function isBlocked(int $cid): bool
1492 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1493 if (!DBA::isResult($blocked)) {
1497 if (Network::isUrlBlocked($blocked['url'])) {
1501 return (bool) $blocked['blocked'];
1505 * Checks if the contact is hidden
1507 * @param int $cid contact id
1508 * @return boolean Is the contact hidden?
1509 * @throws \Exception
1511 public static function isHidden(int $cid): bool
1517 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1518 if (!DBA::isResult($hidden)) {
1521 return (bool) $hidden['hidden'];
1525 * Returns posts from a given contact url
1527 * @param string $contact_url Contact URL
1528 * @param bool $thread_mode
1529 * @param int $update Update mode
1530 * @param int $parent Item parent ID for the update mode
1531 * @param bool $only_media Only display media content
1532 * @return string posts in HTML
1533 * @throws \Exception
1535 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1537 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1541 * Returns posts from a given contact id
1543 * @param int $cid Contact ID
1544 * @param bool $thread_mode
1545 * @param int $update Update mode
1546 * @param int $parent Item parent ID for the update mode
1547 * @param bool $only_media Only display media content
1548 * @return string posts in HTML
1549 * @throws \Exception
1551 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1553 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1554 if (!DBA::isResult($contact)) {
1558 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1559 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1564 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1568 "((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1569 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()
1573 "`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1574 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()
1578 if (!empty($parent)) {
1579 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1581 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1582 if (!empty($last_received)) {
1583 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1588 $condition = DBA::mergeConditions($condition, [
1589 "`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1590 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO
1594 if (DI::mode()->isMobile()) {
1595 $itemsPerPage = DI::pConfig()->get(
1596 DI::userSession()->getLocalUserId(),
1598 'itemspage_mobile_network',
1599 DI::config()->get('system', 'itemspage_network_mobile')
1602 $itemsPerPage = DI::pConfig()->get(
1603 DI::userSession()->getLocalUserId(),
1605 'itemspage_network',
1606 DI::config()->get('system', 'itemspage_network')
1610 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1612 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1614 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1615 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1616 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1622 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1623 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1625 if ($pager->getStart() == 0) {
1626 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1627 if (!empty($cdata['public'])) {
1628 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1629 $items = array_merge($items, $pinned);
1633 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1635 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1636 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1638 if ($pager->getStart() == 0) {
1639 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1640 if (!empty($cdata['public'])) {
1642 "`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1643 $cdata['public'], Post\Collection::FEATURED
1645 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1646 $items = array_merge($pinned, $items);
1650 $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS, $update);
1654 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1655 $o .= HTML::scrollLoader();
1657 $o .= $pager->renderMinimal(count($items));
1665 * Returns the account type name
1667 * The function can be called with either the user or the contact array
1669 * @param int $type type of contact or account
1672 public static function getAccountType(int $type): string
1675 case self::TYPE_ORGANISATION:
1676 $account_type = DI::l10n()->t("Organisation");
1679 case self::TYPE_NEWS:
1680 $account_type = DI::l10n()->t('News');
1683 case self::TYPE_COMMUNITY:
1684 $account_type = DI::l10n()->t("Group");
1692 return $account_type;
1698 * @param int $cid Contact id to block
1699 * @param string $reason Block reason
1700 * @return bool Whether it was successful
1702 public static function block(int $cid, string $reason = null): bool
1704 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1710 * Unblocks a contact
1712 * @param int $cid Contact id to unblock
1713 * @return bool Whether it was successful
1715 public static function unblock(int $cid): bool
1717 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1723 * Ensure that cached avatar exist
1725 * @param integer $cid Contact id
1727 public static function checkAvatarCache(int $cid)
1729 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1730 if (!DBA::isResult($contact)) {
1734 if (Network::isLocalLink($contact['url'])) {
1738 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1739 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1740 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1741 self::updateAvatar($cid, $contact['avatar'], true);
1744 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1745 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1746 self::updateAvatar($cid, $contact['avatar'], true);
1748 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1749 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1750 self::updateAvatar($cid, $contact['avatar'], true);
1756 * Return the photo path for a given contact array in the given size
1758 * @param array $contact contact array
1759 * @param string $size Size of the avatar picture
1760 * @param bool $no_update Don't perform an update if no cached avatar was found
1761 * @return string photo path
1763 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1765 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1767 if (DI::config()->get('system', 'avatar_cache')) {
1769 case Proxy::SIZE_MICRO:
1770 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1771 return $contact['micro'];
1774 case Proxy::SIZE_THUMB:
1775 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1776 return $contact['thumb'];
1779 case Proxy::SIZE_SMALL:
1780 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1781 return $contact['photo'];
1787 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1791 * Return the photo path for a given contact array
1793 * @param array $contact Contact array
1794 * @param bool $no_update Don't perform an update if no cached avatar was found
1795 * @return string photo path
1797 public static function getPhoto(array $contact, bool $no_update = false): string
1799 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1803 * Return the photo path (thumb size) for a given contact array
1805 * @param array $contact Contact array
1806 * @param bool $no_update Don't perform an update if no cached avatar was found
1807 * @return string photo path
1809 public static function getThumb(array $contact, bool $no_update = false): string
1811 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1815 * Return the photo path (micro size) for a given contact array
1817 * @param array $contact Contact array
1818 * @param bool $no_update Don't perform an update if no cached avatar was found
1819 * @return string photo path
1821 public static function getMicro(array $contact, bool $no_update = false): string
1823 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1827 * Check the given contact array for avatar cache fields
1829 * @param array $contact
1830 * @param bool $no_update Don't perform an update if no cached avatar was found
1831 * @return array contact array with avatar cache fields
1833 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1836 $contact_fields = [];
1837 $fields = ['photo', 'thumb', 'micro'];
1838 foreach ($fields as $field) {
1839 if (isset($contact[$field])) {
1840 $contact_fields[] = $field;
1842 if (isset($contact[$field]) && empty($contact[$field])) {
1847 if (!$update || $no_update) {
1851 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1853 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1854 self::updateAvatar($contact['id'], $contact['avatar'], true);
1856 $new_contact = self::getById($contact['id'], $contact_fields);
1857 if (DBA::isResult($new_contact)) {
1858 // We only update the cache fields
1859 $contact = array_merge($contact, $new_contact);
1861 } elseif ($local && !empty($contact['avatar'])) {
1865 /// add the default avatars if the fields aren't filled
1866 if (isset($contact['photo']) && empty($contact['photo'])) {
1867 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1869 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1870 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1872 if (isset($contact['micro']) && empty($contact['micro'])) {
1873 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1880 * Fetch the default header for the given contact
1882 * @param array $contact contact array
1883 * @return string avatar URL
1885 public static function getDefaultHeader(array $contact): string
1887 if (!empty($contact['header'])) {
1888 return $contact['header'];
1891 if (!empty($contact['gsid'])) {
1892 // Use default banners for certain platforms
1893 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1894 $platform = strtolower($gserver['platform'] ?? '');
1899 switch ($platform) {
1902 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1907 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1908 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1909 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1911 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1915 * Use a random picture.
1916 * The service provides random pictures from Unsplash.
1917 * @license https://unsplash.com/license
1919 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1927 * Fetch the default avatar for the given contact and size
1929 * @param array $contact contact array
1930 * @param string $size Size of the avatar picture
1931 * @return string avatar URL
1933 public static function getDefaultAvatar(array $contact, string $size): string
1936 case Proxy::SIZE_MICRO:
1937 $avatar['size'] = 48;
1938 $default = self::DEFAULT_AVATAR_MICRO;
1941 case Proxy::SIZE_THUMB:
1942 $avatar['size'] = 80;
1943 $default = self::DEFAULT_AVATAR_THUMB;
1946 case Proxy::SIZE_SMALL:
1948 $avatar['size'] = 300;
1949 $default = self::DEFAULT_AVATAR_PHOTO;
1953 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1955 $type = Contact::TYPE_PERSON;
1957 if (!empty($contact['id'])) {
1958 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1959 $platform = $account['platform'] ?? '';
1960 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1963 if (empty($platform) && !empty($contact['uri-id'])) {
1964 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1965 $platform = $account['platform'] ?? '';
1966 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1969 switch ($platform) {
1973 * @license GNU Affero General Public License v3.0
1974 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1976 $default = '/images/default/corgidon.png';
1982 * @license GNU Affero General Public License v3.0
1983 * @link https://github.com/diaspora/diaspora/
1985 $default = '/images/default/diaspora.png';
1991 * @license GNU Affero General Public License v3.0
1992 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1994 $default = '/images/default/gotosocial.svg';
2000 * @license GNU Affero General Public License v3.0
2001 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
2003 $default = '/images/default/hometown.png';
2009 * @license GNU Affero General Public License v3.0
2010 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
2012 $default = '/images/default/koyuspace.png';
2020 * @license GNU Affero General Public License v3.0
2021 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2023 $default = '/images/default/mastodon.png';
2027 if ($type == Contact::TYPE_COMMUNITY) {
2030 * @license GNU Affero General Public License v3.0
2031 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2033 $default = '/images/default/peertube-channel.png';
2037 * @license GNU Affero General Public License v3.0
2038 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2040 $default = '/images/default/peertube-account.png';
2047 * @license GNU Affero General Public License v3.0
2048 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2050 $default = '/images/default/pleroma.png';
2056 * @license GNU Affero General Public License v3.0
2057 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2059 $default = '/images/default/plume.png';
2062 return DI::baseUrl() . $default;
2065 if (!empty($contact['xmpp'])) {
2066 $avatar['email'] = $contact['xmpp'];
2067 } elseif (!empty($contact['addr'])) {
2068 $avatar['email'] = $contact['addr'];
2069 } elseif (!empty($contact['url'])) {
2070 $avatar['email'] = $contact['url'];
2072 return DI::baseUrl() . $default;
2075 $avatar['url'] = '';
2076 $avatar['success'] = false;
2078 Hook::callAll('avatar_lookup', $avatar);
2080 if ($avatar['success'] && !empty($avatar['url'])) {
2081 return $avatar['url'];
2084 return DI::baseUrl() . $default;
2088 * Get avatar link for given contact id
2090 * @param integer $cid contact id
2091 * @param string $size One of the Proxy::SIZE_* constants
2092 * @param string $updated Contact update date
2093 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2094 * @return string avatar link
2096 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2098 // We have to fetch the "updated" variable when it wasn't provided
2099 // The parameter can be provided to improve performance
2100 if (empty($updated)) {
2101 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2102 $updated = $account['updated'] ?? '';
2103 $guid = $account['guid'] ?? '';
2106 $guid = urlencode($guid);
2108 $url = DI::baseUrl() . '/photo/contact/';
2110 case Proxy::SIZE_MICRO:
2111 $url .= Proxy::PIXEL_MICRO . '/';
2113 case Proxy::SIZE_THUMB:
2114 $url .= Proxy::PIXEL_THUMB . '/';
2116 case Proxy::SIZE_SMALL:
2117 $url .= Proxy::PIXEL_SMALL . '/';
2119 case Proxy::SIZE_MEDIUM:
2120 $url .= Proxy::PIXEL_MEDIUM . '/';
2122 case Proxy::SIZE_LARGE:
2123 $url .= Proxy::PIXEL_LARGE . '/';
2128 $query_params['ts'] = strtotime($updated);
2131 $query_params['static'] = true;
2134 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2138 * Get avatar link for given contact URL
2140 * @param string $url contact url
2141 * @param integer $uid user id
2142 * @param string $size One of the Proxy::SIZE_* constants
2143 * @return string avatar link
2145 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2148 "`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2149 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0
2151 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2152 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2156 * Get header link for given contact id
2158 * @param integer $cid contact id
2159 * @param string $size One of the Proxy::SIZE_* constants
2160 * @param string $updated Contact update date
2161 * @param bool $static If "true" a parameter is added to convert the header to a static one
2162 * @return string header link
2164 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2166 // We have to fetch the "updated" variable when it wasn't provided
2167 // The parameter can be provided to improve performance
2168 if (empty($updated) || empty($guid)) {
2169 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2170 $updated = $account['updated'] ?? '';
2171 $guid = $account['guid'] ?? '';
2174 $guid = urlencode($guid);
2176 $url = DI::baseUrl() . '/photo/header/';
2178 case Proxy::SIZE_MICRO:
2179 $url .= Proxy::PIXEL_MICRO . '/';
2181 case Proxy::SIZE_THUMB:
2182 $url .= Proxy::PIXEL_THUMB . '/';
2184 case Proxy::SIZE_SMALL:
2185 $url .= Proxy::PIXEL_SMALL . '/';
2187 case Proxy::SIZE_MEDIUM:
2188 $url .= Proxy::PIXEL_MEDIUM . '/';
2190 case Proxy::SIZE_LARGE:
2191 $url .= Proxy::PIXEL_LARGE . '/';
2197 $query_params['ts'] = strtotime($updated);
2200 $query_params['static'] = true;
2203 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2207 * Updates the avatar links in a contact only if needed
2209 * @param int $cid Contact id
2210 * @param string $avatar Link to avatar picture
2211 * @param bool $force force picture update
2212 * @param bool $create_cache Enforces the creation of cached avatar fields
2215 * @throws HTTPException\InternalServerErrorException
2216 * @throws HTTPException\NotFoundException
2217 * @throws \ImagickException
2219 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2221 $contact = DBA::selectFirst(
2223 ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2224 ['id' => $cid, 'self' => false]
2226 if (!DBA::isResult($contact)) {
2230 if (!Network::isValidHttpUrl($avatar)) {
2231 Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
2235 $uid = $contact['uid'];
2237 // Only update the cached photo links of public contacts when they already are cached
2238 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2239 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2240 $update_fields = ['avatar' => $avatar];
2241 if (!Network::isLocalLink($avatar)) {
2243 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2245 $img_str = $fetchResult->getBody();
2246 if (!empty($img_str)) {
2247 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2248 if ($image->isValid()) {
2249 $update_fields['blurhash'] = $image->getBlurHash();
2254 } catch (\Exception $exception) {
2255 Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
2258 } elseif (!empty($contact['blurhash'])) {
2259 $update_fields['blurhash'] = null;
2264 self::update($update_fields, ['id' => $cid]);
2265 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2270 // User contacts use are updated through the public contacts
2271 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2272 $pcid = self::getIdForURL($contact['url'], 0, false);
2273 if (!empty($pcid)) {
2274 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2275 self::updateAvatar($pcid, $avatar, $force, true);
2280 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2282 if ($default_avatar) {
2283 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2286 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2288 // Local contact avatars don't need to be cached
2289 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2290 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2293 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2294 if (Avatar::deleteCache($contact)) {
2298 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2300 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2302 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2303 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)
2305 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2308 // Use the data from the self account
2309 if (empty($fields)) {
2310 $local_uid = User::getIdForURL($contact['url']);
2311 if (!empty($local_uid)) {
2312 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2313 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2317 if (empty($fields)) {
2318 $update = ($contact['avatar'] != $avatar) || $force;
2322 $contact['photo'] ?? '',
2323 $contact['thumb'] ?? '',
2324 $contact['micro'] ?? '',
2327 foreach ($data as $image_uri) {
2328 $image_rid = Photo::ridFromURI($image_uri);
2329 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2330 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2337 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2339 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2340 $update = !empty($fields);
2341 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2347 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2350 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2351 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2352 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2361 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2362 // Collect all user contacts of the given public contact
2363 $personal_contacts = DBA::select(
2366 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]
2368 while ($personal_contact = DBA::fetch($personal_contacts)) {
2369 $cids[] = $personal_contact['id'];
2370 $uids[] = $personal_contact['uid'];
2372 DBA::close($personal_contacts);
2374 if (!empty($cids)) {
2375 // Delete possibly existing cached user contact avatars
2376 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2382 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2383 self::update($fields, ['id' => $cids]);
2386 public static function deleteContactByUrl(string $url)
2388 // Update contact data for all users
2389 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2390 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2391 while ($contact = DBA::fetch($contacts)) {
2392 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2393 self::remove($contact['id']);
2398 * Helper function for "updateFromProbe". Updates personal and public contact
2400 * @param integer $id contact id
2401 * @param integer $uid user id
2402 * @param integer $uri_id Uri-Id
2403 * @param string $url The profile URL of the contact
2404 * @param array $fields The fields that are updated
2406 * @throws \Exception
2408 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2410 if (!self::update($fields, ['id' => $id])) {
2411 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2415 self::setAccountUser($id, $uid, $uri_id, $url);
2417 // Archive or unarchive the contact.
2418 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2419 if (!DBA::isResult($contact)) {
2420 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2424 if (isset($fields['failed'])) {
2425 if ($fields['failed']) {
2426 self::markForArchival($contact);
2428 self::unmarkForArchival($contact);
2432 if ($contact['uid'] != 0) {
2436 // Update contact data for all users
2437 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2439 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2441 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
2442 $condition['network'][] = $contact['network'];
2445 self::update($fields, $condition);
2447 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2448 $condition['network'] = Protocol::OSTATUS;
2450 // If the contact failed, propagate the update fields to all contacts
2451 if (empty($fields['failed'])) {
2452 unset($fields['last-update']);
2453 unset($fields['success_update']);
2454 unset($fields['failure_update']);
2457 if (empty($fields)) {
2461 self::update($fields, $condition);
2465 * Create or update an "account-user" entry
2467 * @param integer $id
2468 * @param integer $uid
2469 * @param integer $uri_id
2470 * @param string $url
2473 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2475 if (empty($uri_id)) {
2479 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2480 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2481 if ($account_user['uid'] == $uid) {
2482 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2483 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2485 // This should never happen
2486 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]);
2490 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2491 if (!empty($account_user['id'])) {
2492 if ($account_user['id'] == $id) {
2493 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2495 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2496 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2497 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2500 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2501 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2502 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2503 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2505 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2510 * Remove duplicated contacts
2512 * @param string $nurl Normalised contact url
2513 * @param integer $uid User id
2515 * @throws \Exception
2517 public static function removeDuplicates(string $nurl, int $uid)
2519 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2520 $count = DBA::count('contact', $condition);
2525 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2526 if (!DBA::isResult($first_contact)) {
2527 // Shouldn't happen - so we handle it
2531 $first = $first_contact['id'];
2532 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2534 // Find all duplicates
2535 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2536 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2537 while ($duplicate = DBA::fetch($duplicates)) {
2538 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2542 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2544 DBA::close($duplicates);
2545 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2550 * Perform a contact update if the contact is outdated
2552 * @param integer $id contact id
2555 public static function updateByIdIfNeeded(int $id): bool
2557 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2558 if (empty($contact['url'])) {
2562 if (self::isLocal($contact['url'])) {
2566 $stamp = (float)microtime(true);
2567 self::updateFromProbe($id);
2568 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
2573 * Perform a contact update if the contact is outdated
2575 * @param string $url contact url
2578 public static function updateByUrlIfNeeded(string $url): bool
2580 $id = self::getIdForURL($url, 0, false);
2582 return self::updateByIdIfNeeded($id);
2584 return (bool)self::getIdForURL($url);
2588 * Updates contact record by provided id and optional network
2590 * @param integer $id contact id
2591 * @param string $network Optional network we are probing for
2593 * @throws HTTPException\InternalServerErrorException
2594 * @throws \ImagickException
2596 public static function updateFromProbe(int $id, string $network = ''): bool
2598 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2599 if (!DBA::isResult($contact)) {
2603 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2605 if ($data['network'] == Protocol::DIASPORA) {
2607 DI::dsprContact()->updateFromProbeArray($data);
2608 } catch (HTTPException\NotFoundException $e) {
2609 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2610 } catch (\InvalidArgumentException $e) {
2611 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2613 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2615 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2616 } catch (HTTPException\NotFoundException $e) {
2617 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2618 } catch (\InvalidArgumentException $e) {
2619 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2623 return self::updateFromProbeArray($id, $data);
2627 * Checks if the given contact has got local data
2630 * @param array $contact
2634 private static function hasLocalData(int $id, array $contact): bool
2636 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2637 // User contacts with the same uri-id exist
2639 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2640 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2643 if (DBA::exists('post-tag', ['cid' => $id])) {
2644 // Is tagged in a post
2647 if (DBA::exists('user-contact', ['cid' => $id])) {
2648 // Has got user-contact data
2651 if (Post::exists(['author-id' => $id])) {
2652 // Posts with this author exist
2655 if (Post::exists(['owner-id' => $id])) {
2656 // Posts with this owner exist
2659 if (Post::exists(['causer-id' => $id])) {
2660 // Posts with this causer exist
2663 // We don't have got this contact locally
2668 * Updates contact record by provided id and probed data
2670 * @param integer $id contact id
2671 * @param array $ret Probed data
2673 * @throws HTTPException\InternalServerErrorException
2674 * @throws \ImagickException
2676 private static function updateFromProbeArray(int $id, array $ret): bool
2679 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2680 This will reliably kill your communication with old Friendica contacts.
2683 // These fields aren't updated by this routine:
2687 'uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2688 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2689 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2690 'created', 'last-update'
2692 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2693 if (!DBA::isResult($contact)) {
2697 if (self::isLocal($ret['url'])) {
2698 if ($contact['uid'] == 0) {
2699 Logger::info('Local contacts are not updated here.');
2701 self::updateFromPublicContact($id, $contact);
2706 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2707 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2710 // Delete all contacts with the same URL
2711 self::deleteContactByUrl($ret['url']);
2715 $has_local_data = self::hasLocalData($id, $contact);
2717 $uid = $contact['uid'];
2718 unset($contact['uid']);
2720 $uriid = $contact['uri-id'];
2721 unset($contact['uri-id']);
2723 $pubkey = $contact['pubkey'];
2724 unset($contact['pubkey']);
2726 $created = $contact['created'];
2727 unset($contact['created']);
2729 $last_update = $contact['last-update'];
2730 unset($contact['last-update']);
2732 $contact['photo'] = $contact['avatar'];
2733 unset($contact['avatar']);
2735 $updated = DateTimeFormat::utcNow();
2737 if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
2738 // Periodical checks are only done on federated contacts
2739 $failed_next_update = null;
2740 $success_next_update = null;
2741 } elseif ($has_local_data) {
2742 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2743 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2744 } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
2745 $failed_next_update = DateTimeFormat::utc('now +6 month');
2746 $success_next_update = DateTimeFormat::utc('now +1 month');
2748 // We don't check connector networks very often to not run into API rate limits
2749 $failed_next_update = DateTimeFormat::utc('now +12 month');
2750 $success_next_update = DateTimeFormat::utc('now +12 month');
2753 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2754 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2755 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]);
2759 // We must not try to update relay contacts via probe. They are no real contacts.
2760 // We check after the probing to be able to correct falsely detected contact types.
2761 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2762 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))
2764 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]);
2765 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2769 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2770 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2771 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]);
2775 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2776 $cid = self::getIdForURL($ret['url'], 0, false);
2777 if (!empty($cid) && ($cid != $id)) {
2778 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2779 return self::updateFromProbeArray($cid, $ret);
2783 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2784 $ret['unsearchable'] = $ret['hide'];
2787 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2788 $ret['forum'] = false;
2789 $ret['prv'] = false;
2790 $ret['contact-type'] = $ret['account-type'];
2791 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2792 $ret['forum'] = (bool)!$ret['manually-approve'];
2793 $ret['prv'] = (bool)!$ret['forum'];
2797 $new_pubkey = $ret['pubkey'] ?? '';
2799 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2800 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2801 $apcontact = APContact::getByURL($ret['url'], false);
2802 if (!empty($apcontact['featured'])) {
2803 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2807 $ret['last-item'] = Probe::getLastUpdate($ret);
2808 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2812 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? '');
2814 // make sure to not overwrite existing values with blank entries except some technical fields
2815 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2816 foreach ($ret as $key => $val) {
2817 if (!array_key_exists($key, $contact)) {
2819 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2820 $ret[$key] = $contact[$key];
2821 } elseif ($ret[$key] != $contact[$key]) {
2826 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2829 unset($ret['last-item']);
2832 if (empty($uriid)) {
2836 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2837 self::updateAvatar($id, $ret['photo'], $update);
2841 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]);
2843 if (Contact\Relation::isDiscoverable($ret['url'])) {
2844 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2847 // Update the public contact
2849 $contact = self::getByURL($ret['url'], false, ['id']);
2850 if (!empty($contact['id'])) {
2851 self::updateFromProbeArray($contact['id'], $ret);
2858 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2859 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2860 $ret['updated'] = $updated;
2861 $ret['failed'] = false;
2862 $ret['next-update'] = $success_next_update;
2863 $ret['local-data'] = $has_local_data;
2865 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2866 if (empty($pubkey) && !empty($new_pubkey)) {
2867 $ret['pubkey'] = $new_pubkey;
2870 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2871 $ret['uri-date'] = $updated;
2874 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2875 $ret['name-date'] = $updated;
2878 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2879 $ret['last-update'] = $updated;
2880 $ret['success_update'] = $updated;
2883 unset($ret['photo']);
2885 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2887 if (Contact\Relation::isDiscoverable($ret['url'])) {
2888 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2894 private static function updateFromPublicContact(int $id, array $contact)
2896 $public = self::getByURL($contact['url'], false);
2900 foreach ($contact as $field => $value) {
2901 if ($field == 'uid') {
2904 if ($public[$field] != $value) {
2905 $fields[$field] = $public[$field];
2908 if (!empty($fields)) {
2909 self::update($fields, ['id' => $id, 'self' => false]);
2910 Logger::info('Updating local contact', ['id' => $id]);
2915 * Updates contact record by provided URL
2917 * @param integer $url contact url
2918 * @return integer Contact id
2919 * @throws HTTPException\InternalServerErrorException
2920 * @throws \ImagickException
2922 public static function updateFromProbeByURL(string $url): int
2924 $id = self::getIdForURL($url);
2930 self::updateFromProbe($id);
2936 * Detects the communication protocol for a given contact url.
2937 * This is used to detect Friendica contacts that we can communicate via AP.
2939 * @param string $url contact url
2940 * @param string $network Network of that contact
2941 * @return string with protocol
2943 public static function getProtocol(string $url, string $network): string
2945 if ($network != Protocol::DFRN) {
2949 $apcontact = APContact::getByURL($url);
2950 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2951 return Protocol::ACTIVITYPUB;
2958 * Takes a $uid and a url/handle and adds a new contact
2960 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2961 * dfrn_request page.
2963 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2966 * $return['success'] boolean true if successful
2967 * $return['message'] error text if success is false.
2969 * Takes a $uid and a url/handle and adds a new contact
2971 * @param int $uid The user id the contact should be created for
2972 * @param string $url The profile URL of the contact
2973 * @param string $network
2975 * @throws HTTPException\InternalServerErrorException
2976 * @throws HTTPException\NotFoundException
2977 * @throws \ImagickException
2979 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2981 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2983 // remove ajax junk, e.g. Twitter
2984 $url = str_replace('/#!/', '/', $url);
2986 if (!Network::isUrlAllowed($url)) {
2987 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2991 if (Network::isUrlBlocked($url)) {
2992 $result['message'] = DI::l10n()->t('Blocked domain');
2997 $result['message'] = DI::l10n()->t('Connect URL missing.');
3001 $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
3003 Hook::callAll('follow', $arr);
3006 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
3010 if (!empty($arr['contact']['name'])) {
3012 $ret = $arr['contact'];
3015 $ret = Probe::uri($url, $network, $uid);
3017 // Ensure that the public contact exists
3018 if ($ret['network'] != Protocol::PHANTOM) {
3019 self::getIdForURL($url);
3023 if (($network != '') && ($ret['network'] != $network)) {
3024 $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
3028 // check if we already have a contact
3029 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
3030 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
3032 $protocol = self::getProtocol($ret['url'], $ret['network']);
3034 // This extra param just confuses things, remove it
3035 if ($protocol === Protocol::DIASPORA) {
3036 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
3039 // do we have enough information?
3040 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
3041 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
3042 if (empty($ret['poll'])) {
3043 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
3045 if (empty($ret['name'])) {
3046 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
3048 if (empty($ret['url'])) {
3049 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
3051 if (strpos($ret['url'], '@') !== false) {
3052 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
3053 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
3058 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3059 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3060 $ret['notify'] = '';
3063 if (!$ret['notify']) {
3064 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3067 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3069 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3071 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3074 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3075 $pending = (bool)$ret['manually-approve'];
3078 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3082 if (DBA::isResult($contact)) {
3084 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3086 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3088 if ($contact['pending'] && !empty($contact['hub-verify'])) {
3089 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3090 $fields['pending'] = false;
3093 self::update($fields, ['id' => $contact['id']]);
3095 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3097 // create contact record
3100 'created' => DateTimeFormat::utcNow(),
3101 'url' => $ret['url'],
3102 'nurl' => Strings::normaliseLink($ret['url']),
3103 'addr' => $ret['addr'],
3104 'alias' => $ret['alias'],
3105 'batch' => $ret['batch'],
3106 'notify' => $ret['notify'],
3107 'poll' => $ret['poll'],
3108 'poco' => $ret['poco'],
3109 'name' => $ret['name'],
3110 'nick' => $ret['nick'],
3111 'network' => $ret['network'],
3112 'baseurl' => $ret['baseurl'],
3113 'gsid' => $ret['gsid'] ?? null,
3114 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON,
3115 'protocol' => $protocol,
3116 'pubkey' => $ret['pubkey'],
3117 'rel' => $new_relation,
3118 'priority' => $ret['priority'],
3119 'writable' => $writeable,
3120 'hidden' => $hidden,
3123 'pending' => $pending,
3128 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3129 if (!DBA::isResult($contact)) {
3130 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3134 $contact_id = $contact['id'];
3135 $result['cid'] = $contact_id;
3137 if ($contact['contact-type'] == self::TYPE_COMMUNITY) {
3138 Circle::addMember(User::getDefaultGroupCircle($uid), $contact_id);
3140 Circle::addMember(User::getDefaultCircle($uid), $contact_id);
3143 // Update the avatar
3144 self::updateAvatar($contact_id, $ret['photo']);
3146 // pull feed and consume it, which should subscribe to the hub.
3147 if ($contact['network'] == Protocol::OSTATUS) {
3148 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3152 self::updateFromProbeArray($contact_id, $ret);
3155 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3156 } catch (\InvalidArgumentException $e) {
3157 Logger::notice($e->getMessage(), ['contact' => $contact]);
3161 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3167 * @param array $importer Owner (local user) data
3168 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3169 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3170 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3171 * @param string $note Introduction additional message
3172 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3173 * @throws HTTPException\InternalServerErrorException
3174 * @throws \ImagickException
3176 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3178 // Should always be set
3179 if (empty($datarray['author-id'])) {
3183 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3184 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3185 if (!DBA::isResult($pub_contact)) {
3186 // Should never happen
3190 // Contact is blocked at node-level
3191 if (self::isBlocked($datarray['author-id'])) {
3195 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3196 $name = $pub_contact['name'];
3197 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3198 $nick = $pub_contact['nick'];
3199 $network = $pub_contact['network'];
3201 // Ensure that we don't create a new contact when there already is one
3202 $cid = self::getIdForURL($url, $importer['uid']);
3204 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3207 self::clearFollowerFollowingEndpointCache($importer['uid']);
3209 if (!empty($contact)) {
3210 if (!empty($contact['pending'])) {
3211 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3215 // Contact is blocked at user-level
3217 !empty($contact['id']) && !empty($importer['id']) &&
3218 Contact\User::isBlocked($contact['id'], $importer['id'])
3223 // Make sure that the existing contact isn't archived
3224 self::unmarkForArchival($contact);
3226 if (($contact['rel'] == self::SHARING)
3227 || ($sharing && $contact['rel'] == self::FOLLOWER)
3230 ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3231 ['id' => $contact['id'], 'uid' => $importer['uid']]
3235 // Ensure to always have the correct network type, independent from the connection request method
3236 self::updateFromProbe($contact['id']);
3238 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3242 // send email notification to owner?
3243 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3244 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3248 // create contact record
3249 $contact_id = self::insert([
3250 'uid' => $importer['uid'],
3251 'created' => DateTimeFormat::utcNow(),
3253 'nurl' => Strings::normaliseLink($url),
3256 'network' => $network,
3257 'rel' => self::FOLLOWER,
3264 // Ensure to always have the correct network type, independent from the connection request method
3265 self::updateFromProbe($contact_id);
3267 self::updateAvatar($contact_id, $photo, true);
3269 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3271 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo', 'contact-type'], ['id' => $contact_id]);
3273 /// @TODO Encapsulate this into a function/method
3274 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3275 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3276 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3277 // create notification
3278 if (is_array($contact_record)) {
3279 $intro = DI::introFactory()->createNew(
3281 $contact_record['id'],
3284 DI::intro()->save($intro);
3287 if ($contact_record['contact-type'] == self::TYPE_COMMUNITY) {
3288 Circle::addMember(User::getDefaultGroupCircle($importer['uid']), $contact_record['id']);
3290 Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
3293 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3294 DI::notify()->createFromArray([
3295 'type' => Notification\Type::INTRO,
3296 'otype' => Notification\ObjectType::INTRO,
3297 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3298 'uid' => $user['uid'],
3299 'cid' => $contact_record['id'],
3300 'link' => DI::baseUrl() . '/notifications/intros',
3303 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3304 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3305 self::createFromProbeForUser($importer['uid'], $url, $network);
3308 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3309 $fields = ['pending' => false];
3310 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3311 $fields['rel'] = self::FRIEND;
3314 self::update($fields, $condition);
3324 * Update the local relationship when a local user loses a follower
3326 * @param array $contact User-specific contact (uid != 0) array
3328 * @throws HTTPException\InternalServerErrorException
3329 * @throws \ImagickException
3331 public static function removeFollower(array $contact)
3333 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3334 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3335 } elseif (!empty($contact['id'])) {
3336 self::remove($contact['id']);
3338 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3342 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3344 self::clearFollowerFollowingEndpointCache($contact['uid']);
3346 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3347 if (!empty($cdata['public'])) {
3348 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3353 * Update the local relationship when a local user unfollow a contact.
3354 * Removes the contact for sharing-only protocols (feed and mail).
3356 * @param array $contact User-specific contact (uid != 0) array
3357 * @throws HTTPException\InternalServerErrorException
3359 public static function removeSharer(array $contact)
3361 self::clearFollowerFollowingEndpointCache($contact['uid']);
3363 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3364 self::remove($contact['id']);
3366 self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
3369 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3373 * Create a birthday event.
3375 * Update the year and the birthday.
3377 public static function updateBirthdays()
3381 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3382 AND NOT `contact`.`pending`
3383 AND NOT `contact`.`hidden`
3384 AND NOT `contact`.`blocked`
3385 AND NOT `contact`.`archive`
3386 AND NOT `contact`.`deleted`',
3392 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3394 while ($contact = DBA::fetch($contacts)) {
3395 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3397 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3399 if (Event::createBirthday($contact, $nextbd)) {
3403 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3404 ['id' => $contact['id']]
3408 DBA::close($contacts);
3412 * Remove the unavailable contact ids from the provided list
3414 * @param array $contact_ids Contact id list
3416 * @throws \Exception
3418 public static function pruneUnavailable(array $contact_ids): array
3420 if (empty($contact_ids)) {
3424 $contacts = self::selectToArray(['id'], [
3425 'id' => $contact_ids,
3431 return array_column($contacts, 'id');
3435 * Returns a magic link to authenticate remote visitors
3437 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3439 * @param string $contact_url The address of the target contact profile
3440 * @param string $url An url that we will be redirected to after the authentication
3442 * @return string with "redir" link
3443 * @throws HTTPException\InternalServerErrorException
3444 * @throws \ImagickException
3446 public static function magicLink(string $contact_url, string $url = ''): string
3448 if (!DI::userSession()->isAuthenticated()) {
3449 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3452 $contact = self::getByURL($contact_url, false);
3453 if (empty($contact)) {
3454 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3457 // Prevents endless loop in case only a non-public contact exists for the contact URL
3458 unset($contact['uid']);
3460 return self::magicLinkByContact($contact, $url ?: $contact_url);
3464 * Returns a magic link to authenticate remote visitors
3466 * @param integer $cid The contact id of the target contact profile
3467 * @param string $url An url that we will be redirected to after the authentication
3469 * @return string with "redir" link
3470 * @throws HTTPException\InternalServerErrorException
3471 * @throws \ImagickException
3473 public static function magicLinkById(int $cid, string $url = ''): string
3475 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], ['id' => $cid]);
3477 return self::magicLinkByContact($contact, $url);
3481 * Returns a magic link to authenticate remote visitors
3483 * @param array $contact The contact array with "uid", "network" and "url"
3484 * @param string $url An url that we will be redirected to after the authentication
3486 * @return string with "redir" link
3487 * @throws HTTPException\InternalServerErrorException
3488 * @throws \ImagickException
3490 public static function magicLinkByContact(array $contact, string $url = ''): string
3492 $destination = $url ?: (!Network::isValidHttpUrl($contact['url']) && !empty($contact['alias']) && Network::isValidHttpUrl($contact['alias']) ? $contact['alias'] : $contact['url']);
3494 if (!DI::userSession()->isAuthenticated()) {
3495 return $destination;
3498 // Only redirections to the same host do make sense
3499 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3503 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3504 return 'contact/' . $contact['id'] . '/conversations';
3507 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3508 return $destination;
3511 if (empty($contact['id'])) {
3512 return $destination;
3515 $redirect = 'contact/redir/' . $contact['id'];
3517 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3518 $redirect .= '?url=' . $url;
3525 * Is the contact a group?
3527 * @param integer $contactid ID of the contact
3529 * @return boolean "true" if it is a group
3531 public static function isGroup(int $contactid): bool
3533 $fields = ['contact-type'];
3534 $condition = ['id' => $contactid];
3535 $contact = DBA::selectFirst('contact', $fields, $condition);
3536 if (!DBA::isResult($contact)) {
3541 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3545 * Can the remote contact receive private messages?
3547 * @param array $contact
3550 public static function canReceivePrivateMessages(array $contact): bool
3552 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3553 $self = $contact['self'] ?? false;
3555 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3559 * Search contact table by nick or name
3561 * @param string $search Name or nick
3562 * @param string $mode Search mode (e.g. "community")
3563 * @param bool $show_blocked Show users from blocked servers. Default is false
3564 * @param int $uid User ID
3565 * @param int $limit Maximum amount of returned values
3566 * @param int $offset Limit offset
3568 * @return array with search results
3569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3571 public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
3573 if (empty($search)) {
3577 // check supported networks
3578 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3579 if (DI::config()->get('system', 'diaspora_enabled')) {
3580 $networks[] = Protocol::DIASPORA;
3583 if (!DI::config()->get('system', 'ostatus_disabled')) {
3584 $networks[] = Protocol::OSTATUS;
3588 'network' => $networks,
3589 'server-failed' => false,
3592 'unsearchable' => false,
3596 if (!$show_blocked) {
3597 $condition['server-blocked'] = true;
3601 $condition['blocked'] = false;
3603 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3606 // check if we search only communities or every contact
3607 if ($mode === 'community') {
3608 $condition['contact-type'] = self::TYPE_COMMUNITY;
3615 if (!empty($limit) && !empty($offset)) {
3616 $params['limit'] = [$offset, $limit];
3617 } elseif (!empty($limit)) {
3618 $params['limit'] = $limit;
3621 $condition = DBA::mergeConditions(
3623 ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]
3626 return DBA::selectToArray('account-user-view', [], $condition, $params);
3630 * Add public contacts from an array
3632 * @param array $urls
3633 * @return array result "count", "added" and "updated"
3635 public static function addByUrls(array $urls): array
3642 foreach ($urls as $url) {
3643 if (empty($url) || !is_string($url)) {
3646 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3647 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3648 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3650 } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3652 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3654 } catch (\InvalidArgumentException $e) {
3655 Logger::notice($e->getMessage(), ['contact' => $contact]);
3663 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3667 * Returns a random, global contact array of the current node
3669 * @return array The profile array
3672 public static function getRandomContact(): array
3674 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], [
3675 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3676 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3677 ], ['order' => ['RAND()']]);
3679 if (DBA::isResult($contact)) {
3687 * Checks, if contacts with the given condition exists
3689 * @param array $condition
3692 * @throws \Exception
3694 public static function exists(array $condition): bool
3696 return DBA::exists('contact', $condition);