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\Content\Conversation As ConversationContent;
27 use Friendica\Content\Pager;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\Database;
36 use Friendica\Database\DBA;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Network\Probe;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy;
50 use Friendica\Util\Strings;
51 use Friendica\Worker\UpdateContact;
54 * functions for interacting with a contact
58 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
59 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
60 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
66 const LOCK_INSERT = 'contact-insert';
71 * TYPE_UNKNOWN - unknown type
73 * TYPE_PERSON - the account belongs to a person
74 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
76 * TYPE_ORGANISATION - the account belongs to an organisation
77 * Associated page type: PAGE_SOAPBOX
79 * TYPE_NEWS - the account is a news reflector
80 * Associated page type: PAGE_SOAPBOX
82 * TYPE_COMMUNITY - the account is community group
83 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
85 * TYPE_RELAY - the account is a relay
86 * This will only be assigned to contacts, not to user accounts
89 const TYPE_UNKNOWN = -1;
90 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
91 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
92 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
93 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
94 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
105 const NOTHING = 0; // There is no relationship between the contact and the user
106 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
107 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
108 const FRIEND = 3; // There is a mutual relationship between the contact and the user
109 const SELF = 4; // This is the user theirself
114 const MIRROR_DEACTIVATED = 0;
115 const MIRROR_FORWARDED = 1; // Deprecated, now does the same like MIRROR_OWN_POST
116 const MIRROR_OWN_POST = 2;
117 const MIRROR_NATIVE_RESHARE = 3;
120 * @param array $fields Array of selected fields, empty for all
121 * @param array $condition Array of fields for condition
122 * @param array $params Array of several parameters
126 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
128 return DBA::selectToArray('contact', $fields, $condition, $params);
132 * @param array $fields Array of selected fields, empty for all
133 * @param array $condition Array of fields for condition
134 * @param array $params Array of several parameters
138 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
140 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
146 * @param array $fields Array of selected fields, empty for all
147 * @param array $condition Array of fields for condition
148 * @param array $params Array of several parameters
152 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
154 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
158 * @param array $fields Array of selected fields, empty for all
159 * @param array $condition Array of fields for condition
160 * @param array $params Array of several parameters
164 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
166 return DBA::selectFirst('account-view', $fields, $condition, $params);
170 * Insert a row into the contact table
171 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
173 * @param array $fields field array
174 * @param int $duplicate_mode Do an update on a duplicate entry
176 * @return int id of the created contact
179 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
181 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
182 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
185 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
187 if (empty($fields['created'])) {
188 $fields['created'] = DateTimeFormat::utcNow();
191 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
192 DBA::insert('contact', $fields, $duplicate_mode);
193 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
194 if (!DBA::isResult($contact)) {
196 Logger::warning('Created contact could not be found', ['fields' => $fields]);
200 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
201 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
202 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
203 if (empty($account_user['id'])) {
204 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
205 } elseif ($account_user['id'] != $contact['id']) {
206 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
207 if (!empty($duplicate['id'])) {
208 $ret = Contact::deleteById($contact['id']);
209 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']]);
210 $contact = $duplicate;
212 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
213 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']]);
217 Contact\User::insertForContactArray($contact);
219 return $contact['id'];
223 * Delete contact by id
228 public static function deleteById(int $id): bool
230 Logger::debug('Delete contact', ['id' => $id]);
231 DBA::delete('account-user', ['id' => $id]);
232 return DBA::delete('contact', ['id' => $id]);
236 * Updates rows in the contact table
238 * @param array $fields contains the fields that are updated
239 * @param array $condition condition array with the key values
240 * @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)
242 * @return boolean was the update successful?
244 * @todo Let's get rid of boolean type of $old_fields
246 public static function update(array $fields, array $condition, $old_fields = []): bool
248 // Apply changes to the "user-contact" table on dedicated fields
249 Contact\User::updateByContactUpdate($fields, $condition);
251 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
252 return DBA::update('contact', $fields, $condition, $old_fields);
256 * @param integer $id Contact ID
257 * @param array $fields Array of selected fields, empty for all
258 * @return array|boolean Contact record if it exists, false otherwise
261 public static function getById(int $id, array $fields = [])
263 return DBA::selectFirst('contact', $fields, ['id' => $id]);
267 * Fetch the first contact with the provided uri-id.
269 * @param integer $uri_id uri-id of the contact
270 * @param array $fields Array of selected fields, empty for all
271 * @return array|boolean Contact record if it exists, false otherwise
274 public static function getByUriId(int $uri_id, array $fields = [])
276 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
280 * Fetch all remote contacts for a given contact url
282 * @param string $url The URL of the contact
283 * @param array $fields The wanted fields
285 * @return array all remote contacts
289 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
293 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
294 while ($contact = DBA::fetch($remote_contacts)) {
295 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
298 $remote[$contact['uid']] = $contact['id'];
300 DBA::close($remote_contacts);
306 * Fetches a contact by a given url
308 * @param string $url profile url
309 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
310 * @param array $fields Field list
311 * @param integer $uid User ID of the contact
312 * @return array contact array
314 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
316 if ($update || is_null($update)) {
317 $cid = self::getIdForURL($url, $uid, $update);
322 $contact = self::getById($cid, $fields);
323 if (empty($contact)) {
329 // Add internal fields
331 if (!empty($fields)) {
332 foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
333 if (!in_array($internal, $fields)) {
334 $fields[] = $internal;
335 $removal[] = $internal;
340 // We first try the nurl (http://server.tld/nick), most common case
341 $options = ['order' => ['id']];
342 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
344 // Then the addr (nick@server.tld)
345 if (!DBA::isResult($contact)) {
346 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
349 // Then the alias (which could be anything)
350 if (!DBA::isResult($contact)) {
351 // The link could be provided as http although we stored it as https
352 $ssl_url = str_replace('http://', 'https://', $url);
353 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
354 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
357 if (!DBA::isResult($contact)) {
361 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
363 // Update the contact in the background if needed
364 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
366 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
367 } catch (\InvalidArgumentException $e) {
368 Logger::notice($e->getMessage(), ['contact' => $contact]);
372 // Remove the internal fields
373 foreach ($removal as $internal) {
374 unset($contact[$internal]);
381 * Fetches a contact for a given user by a given url.
382 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
384 * @param string $url profile url
385 * @param integer $uid User ID of the contact
386 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
387 * @param array $fields Field list
388 * @return array contact array
390 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
393 $contact = self::getByURL($url, $update, $fields, $uid);
394 if (!empty($contact)) {
395 if (!empty($contact['id'])) {
396 $contact['cid'] = $contact['id'];
403 $contact = self::getByURL($url, $update, $fields);
404 if (!empty($contact['id'])) {
406 $contact['zid'] = $contact['id'];
412 * Checks if a contact uses a specific platform
415 * @param string $platform
418 public static function isPlatform(string $url, string $platform): bool
420 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
424 * Tests if the given contact is a follower
426 * @param int $cid Either public contact id or user's contact id
427 * @param int $uid User ID
428 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
430 * @return boolean is the contact id a follower?
431 * @throws HTTPException\InternalServerErrorException
432 * @throws \ImagickException
434 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
436 if (Contact\User::isBlocked($cid, $uid)) {
440 $cdata = self::getPublicAndUserContactID($cid, $uid);
441 if (empty($cdata['user'])) {
445 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
447 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
449 return DBA::exists('contact', $condition);
453 * Tests if the given contact url is a follower
455 * @param string $url Contact URL
456 * @param int $uid User ID
457 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
459 * @return boolean is the contact id a follower?
460 * @throws HTTPException\InternalServerErrorException
461 * @throws \ImagickException
463 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
465 $cid = self::getIdForURL($url, $uid);
471 return self::isFollower($cid, $uid, $strict);
475 * Tests if the given user shares with the given contact
477 * @param int $cid Either public contact id or user's contact id
478 * @param int $uid User ID
479 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
481 * @return boolean is the contact sharing with given user?
482 * @throws HTTPException\InternalServerErrorException
483 * @throws \ImagickException
485 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
487 if (Contact\User::isBlocked($cid, $uid)) {
491 $cdata = self::getPublicAndUserContactID($cid, $uid);
492 if (empty($cdata['user'])) {
496 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
498 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
500 return DBA::exists('contact', $condition);
504 * Tests if the given user follow the given contact url
506 * @param string $url Contact URL
507 * @param int $uid User ID
508 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
510 * @return boolean is the contact url being followed?
511 * @throws HTTPException\InternalServerErrorException
512 * @throws \ImagickException
514 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
516 $cid = self::getIdForURL($url, $uid);
522 return self::isSharing($cid, $uid, $strict);
526 * Get the basepath for a given contact link
528 * @param string $url The contact link
529 * @param boolean $dont_update Don't update the contact
531 * @return string basepath
532 * @throws HTTPException\InternalServerErrorException
533 * @throws \ImagickException
535 public static function getBasepath(string $url, bool $dont_update = false): string
537 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
538 if (!DBA::isResult($contact)) {
542 if (!empty($contact['baseurl'])) {
543 return $contact['baseurl'];
544 } elseif ($dont_update) {
548 // Update the existing contact
549 self::updateFromProbe($contact['id']);
551 // And fetch the result
552 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
553 if (empty($contact['baseurl'])) {
554 Logger::info('No baseurl for contact', ['url' => $url]);
558 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
559 return $contact['baseurl'];
563 * Check if the given contact url is on the same server
565 * @param string $url The contact link
567 * @return boolean Is it the same server?
569 public static function isLocal(string $url): bool
571 if (!parse_url($url, PHP_URL_SCHEME)) {
572 $addr_parts = explode('@', $url);
573 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
576 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
580 * Check if the given contact ID is on the same server
582 * @param string $url The contact link
583 * @return boolean Is it the same server?
585 public static function isLocalById(int $cid): bool
587 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
588 if (!DBA::isResult($contact)) {
592 if (empty($contact['baseurl'])) {
593 $baseurl = self::getBasepath($contact['url'], true);
595 $baseurl = $contact['baseurl'];
598 return Strings::compareLink($baseurl, DI::baseUrl());
602 * Returns the public contact id of the given user id
604 * @param integer $uid User ID
606 * @return integer|boolean Public contact id for given user id
609 public static function getPublicIdByUserId(int $uid)
611 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
612 if (!DBA::isResult($self)) {
615 return self::getIdForURL($self['url']);
619 * Returns the contact id for the user and the public contact id for a given contact id
621 * @param int $cid Either public contact id or user's contact id
622 * @param int $uid User ID
624 * @return array with public and user's contact id
625 * @throws HTTPException\InternalServerErrorException
626 * @throws \ImagickException
628 public static function getPublicAndUserContactID(int $cid, int $uid): array
630 // We have to use the legacy function as long as the post update hasn't finished
631 if (DI::keyValue()->get('post_update_version') < 1427) {
632 return self::legacyGetPublicAndUserContactID($cid, $uid);
635 if (empty($uid) || empty($cid)) {
639 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
640 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
644 $pcid = $contact['pid'];
645 if ($contact['uid'] == $uid) {
646 $ucid = $contact['id'];
648 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
649 if (DBA::isResult($contact)) {
650 $ucid = $contact['id'];
656 return ['public' => $pcid, 'user' => $ucid];
660 * Helper function for "getPublicAndUserContactID"
662 * @param int $cid Either public contact id or user's contact id
663 * @param int $uid User ID
664 * @return array with public and user's contact id
665 * @throws HTTPException\InternalServerErrorException
666 * @throws \ImagickException
668 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
670 if (empty($uid) || empty($cid)) {
674 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
675 if (!DBA::isResult($contact)) {
679 // We quit when the user id don't match the user id of the provided contact
680 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
684 if ($contact['uid'] != 0) {
685 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
689 $ucid = $contact['id'];
691 $pcid = $contact['id'];
692 $ucid = self::getIdForURL($contact['url'], $uid);
695 return ['public' => $pcid, 'user' => $ucid];
699 * Returns contact details for a given contact id in combination with a user id
701 * @param int $cid A contact ID
702 * @param int $uid The User ID
703 * @param array $fields The selected fields for the contact
704 * @return array The contact details
708 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
710 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
712 if (!DBA::isResult($contact)) {
720 * Creates the self-contact for the provided user id
723 * @return bool Operation success
724 * @throws HTTPException\InternalServerErrorException
726 public static function createSelfFromUserId(int $uid): bool
728 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
729 ['uid' => $uid, 'account_expired' => false]);
730 if (!DBA::isResult($user)) {
735 'uid' => $user['uid'],
736 'created' => DateTimeFormat::utcNow(),
738 'name' => $user['username'],
739 'nick' => $user['nickname'],
740 'pubkey' => $user['pubkey'],
741 'prvkey' => $user['prvkey'],
742 'photo' => User::getAvatarUrl($user),
743 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
744 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
747 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
748 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
749 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
750 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
751 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
752 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
753 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
754 'name-date' => DateTimeFormat::utcNow(),
755 'uri-date' => DateTimeFormat::utcNow(),
756 'avatar-date' => DateTimeFormat::utcNow(),
762 // Only create the entry if it doesn't exist yet
763 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
764 $return = (bool)self::insert($contact);
767 // Create the public contact
768 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
769 $contact['self'] = false;
771 $contact['prvkey'] = null;
773 self::insert($contact, Database::INSERT_IGNORE);
780 * Updates the self-contact for the provided user id
783 * @param bool $update_avatar Force the avatar update
784 * @return bool "true" if updated
785 * @throws HTTPException\InternalServerErrorException
787 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
789 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
790 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
791 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
792 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
793 if (!DBA::isResult($self)) {
797 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
798 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
799 if (!DBA::isResult($user)) {
803 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
804 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
805 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
806 if (!DBA::isResult($profile)) {
810 $file_suffix = 'jpg';
811 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
814 'name' => $profile['name'],
815 'nick' => $user['nickname'],
816 'avatar-date' => $self['avatar-date'],
817 'location' => Profile::formatLocation($profile),
818 'about' => $profile['about'],
819 'keywords' => $profile['pub_keywords'],
820 'contact-type' => $user['account-type'],
821 'prvkey' => $user['prvkey'],
822 'pubkey' => $user['pubkey'],
823 'xmpp' => $profile['xmpp'],
824 'matrix' => $profile['matrix'],
825 'network' => Protocol::DFRN,
827 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
828 'nurl' => Strings::normaliseLink($url),
829 'uri-id' => ItemURI::getIdByURI($url),
830 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
831 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
832 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
833 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
834 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
838 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
839 if (DBA::isResult($avatar)) {
840 if ($update_avatar) {
841 $fields['avatar-date'] = DateTimeFormat::utcNow();
844 // Creating the path to the avatar, beginning with the file suffix
845 $types = Images::supportedTypes();
846 if (isset($types[$avatar['type']])) {
847 $file_suffix = $types[$avatar['type']];
850 // We are adding a timestamp value so that other systems won't use cached content
851 $timestamp = strtotime($fields['avatar-date']);
853 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
854 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
856 $fields['photo'] = $prefix . '4' . $suffix;
857 $fields['thumb'] = $prefix . '5' . $suffix;
858 $fields['micro'] = $prefix . '6' . $suffix;
860 // We hadn't found a photo entry, so we use the default avatar
861 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
862 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
863 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
866 $fields['avatar'] = User::getAvatarUrl($user);
867 $fields['header'] = User::getBannerUrl($user);
868 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
869 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
870 $fields['unsearchable'] = !$profile['net-publish'];
871 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
875 foreach ($fields as $field => $content) {
876 if ($self[$field] != $content) {
882 if ($fields['name'] != $self['name']) {
883 $fields['name-date'] = DateTimeFormat::utcNow();
885 $fields['updated'] = DateTimeFormat::utcNow();
886 self::update($fields, ['id' => $self['id']]);
888 // Update the other contacts as well
889 unset($fields['prvkey']);
890 $fields['self'] = false;
891 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
893 // Update the profile
895 'photo' => User::getAvatarUrl($user),
896 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
899 DBA::update('profile', $fields, ['uid' => $uid]);
906 * Marks a contact for removal
908 * @param int $id contact id
910 * @throws HTTPException\InternalServerErrorException
912 public static function remove(int $id)
914 // We want just to make sure that we don't delete our "self" contact
915 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
916 if (!DBA::isResult($contact)) {
920 DBA::delete('account-user', ['id' => $id]);
922 self::clearFollowerFollowingEndpointCache($contact['uid']);
924 // Archive the contact
925 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
927 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
928 Avatar::deleteCache($contact);
931 // Delete it in the background
932 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
936 * Unfollow the remote contact
938 * @param array $contact Target user-specific contact (uid != 0) array
940 * @throws HTTPException\InternalServerErrorException
941 * @throws \ImagickException
943 public static function unfollow(array $contact): void
945 if (empty($contact['network'])) {
946 throw new \InvalidArgumentException('Empty network in contact array');
949 if (empty($contact['uid'])) {
950 throw new \InvalidArgumentException('Unexpected public contact record');
953 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
954 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
955 if (!empty($cdata['public'])) {
956 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
960 self::removeSharer($contact);
964 * Revoke follow privileges of the remote user contact
966 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
968 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
970 * @throws HTTPException\InternalServerErrorException
971 * @throws \ImagickException
973 public static function revokeFollow(array $contact): void
975 if (empty($contact['network'])) {
976 throw new \InvalidArgumentException('Empty network in contact array');
979 if (empty($contact['uid'])) {
980 throw new \InvalidArgumentException('Unexpected public contact record');
983 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
984 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
985 if (!empty($cdata['public'])) {
986 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
990 self::removeFollower($contact);
994 * Completely severs a relationship with a contact
996 * @param array $contact User-specific contact (uid != 0) array
998 * @throws HTTPException\InternalServerErrorException
999 * @throws \ImagickException
1001 public static function terminateFriendship(array $contact)
1003 if (empty($contact['network'])) {
1004 throw new \InvalidArgumentException('Empty network in contact array');
1007 if (empty($contact['uid'])) {
1008 throw new \InvalidArgumentException('Unexpected public contact record');
1011 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1013 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1014 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1017 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1018 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1021 self::remove($contact['id']);
1024 private static function clearFollowerFollowingEndpointCache(int $uid)
1030 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1031 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1035 * Marks a contact for archival after a communication issue delay
1037 * Contact has refused to recognise us as a friend. We will start a countdown.
1038 * If they still don't recognise us in 32 days, the relationship is over,
1039 * and we won't waste any more time trying to communicate with them.
1040 * This provides for the possibility that their database is temporarily messed
1041 * up or some other transient event and that there's a possibility we could recover from it.
1043 * @param array $contact contact to mark for archival
1045 * @throws HTTPException\InternalServerErrorException
1047 public static function markForArchival(array $contact)
1049 if (!isset($contact['url']) && !empty($contact['id'])) {
1050 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1051 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1052 if (!DBA::isResult($contact)) {
1055 } elseif (!isset($contact['url'])) {
1056 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1059 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1061 // Contact already archived or "self" contact? => nothing to do
1062 if ($contact['archive'] || $contact['self']) {
1066 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1067 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1068 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1071 * We really should send a notification to the owner after 2-3 weeks
1072 * so they won't be surprised when the contact vanishes and can take
1073 * remedial action if this was a serious mistake or glitch
1076 /// @todo Check for contact vitality via probing
1077 $archival_days = DI::config()->get('system', 'archival_days', 32);
1079 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1080 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1081 /* Relationship is really truly dead. archive them rather than
1082 * delete, though if the owner tries to unarchive them we'll start
1083 * the whole process over again.
1085 self::update(['archive' => true], ['id' => $contact['id']]);
1086 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1092 * Cancels the archival countdown
1094 * @see Contact::markForArchival()
1096 * @param array $contact contact to be unmarked for archival
1098 * @throws \Exception
1100 public static function unmarkForArchival(array $contact)
1102 // Always unarchive the relay contact entry
1103 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1104 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1105 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1106 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1107 self::update($fields, $condition);
1111 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1112 $exists = DBA::exists('contact', $condition);
1114 // We don't need to update, we never marked this contact for archival
1119 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1121 if (!isset($contact['url']) && !empty($contact['id'])) {
1122 $fields = ['id', 'url', 'batch'];
1123 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1124 if (!DBA::isResult($contact)) {
1129 // It's a miracle. Our dead contact has inexplicably come back to life.
1130 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1131 self::update($fields, ['id' => $contact['id']]);
1132 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1136 * Returns the data array for the photo menu of a given contact
1138 * @param array $contact contact
1139 * @param int $uid Visitor user id
1141 * @throws HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function photoMenu(array $contact, int $uid): array
1146 // Anonymous visitor
1148 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1155 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1156 $profile_link = 'contact/redir/' . $contact['id'];
1157 $status_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
1158 $photos_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
1159 $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
1161 $profile_link = $contact['url'];
1164 if ($profile_link === 'mailbox') {
1168 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1169 $pm_url = 'message/new/' . $contact['id'];
1172 $contact_url = 'contact/' . $contact['id'];
1173 $posts_link = 'contact/' . $contact['id'] . '/conversations';
1176 $unfollow_link = '';
1177 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1178 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1179 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1180 } elseif (!$contact['pending']) {
1181 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1187 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1189 if (empty($contact['uid'])) {
1191 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1192 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1193 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1194 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1195 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1199 'status' => [DI::l10n()->t('View Status') , $status_link , true ],
1200 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1201 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true ],
1202 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1203 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1204 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1205 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1206 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1209 if (!empty($contact['pending'])) {
1211 $intro = DI::intro()->selectForContact($contact['id']);
1212 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1213 } catch (IntroductionNotFoundException $exception) {
1214 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1219 $args = ['contact' => $contact, 'menu' => &$menu];
1221 Hook::callAll('contact_photo_menu', $args);
1223 $menucondensed = [];
1225 foreach ($menu as $menuname => $menuitem) {
1226 if ($menuitem[1] != '') {
1227 $menucondensed[$menuname] = $menuitem;
1231 return $menucondensed;
1235 * Fetch the contact id for a given URL and user
1237 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1238 * `addr` or `alias`.
1240 * If there's no record and we aren't looking for a public contact, we quit.
1241 * If there's one, we check that it isn't time to update the picture else we
1242 * directly return the found contact id.
1244 * Second, we probe the provided $url whether it's http://server.tld/profile or
1245 * nick@server.tld. We quit if we can't get any info back.
1247 * Third, we create the contact record if it doesn't exist
1249 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1250 * if there's any updates
1252 * @param string $url Contact URL
1253 * @param integer $uid The user id for the contact (0 = public contact)
1254 * @param boolean $update true = always update, false = never update, null = update when not found
1255 * @param array $default Default value for creating the contact when everything else fails
1257 * @return integer Contact ID
1258 * @throws HTTPException\InternalServerErrorException
1259 * @throws \ImagickException
1261 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1266 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1270 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
1272 if (!empty($contact)) {
1273 $contact_id = $contact['id'];
1275 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
1277 if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1279 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
1280 } catch (\InvalidArgumentException $e) {
1281 Logger::notice($e->getMessage(), ['contact' => $contact]);
1285 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1286 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1289 } elseif ($uid != 0) {
1290 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1292 } elseif (empty($default) && !is_null($update) && !$update) {
1293 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1299 if (empty($default['network']) || $update) {
1300 $data = Probe::uri($url, '', $uid);
1302 // Take the default values when probing failed
1303 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1304 $data = array_merge($data, $default);
1306 } elseif (!empty($default['network'])) {
1310 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1311 // Fetch data for the public contact via the first found personal contact
1312 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1313 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1314 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1315 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1317 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1318 if (!DBA::isResult($personal_contact)) {
1319 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1322 if (DBA::isResult($personal_contact)) {
1323 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1324 $data = $personal_contact;
1325 $data['photo'] = $personal_contact['avatar'];
1326 $data['account-type'] = $personal_contact['contact-type'];
1327 $data['hide'] = $personal_contact['unsearchable'];
1328 unset($data['avatar']);
1329 unset($data['contact-type']);
1330 unset($data['unsearchable']);
1334 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1335 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1339 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1340 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1345 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1346 if (!empty($data['alias'])) {
1347 $urls[] = Strings::normaliseLink($data['alias']);
1349 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1350 if (!empty($contact['id'])) {
1351 $contact_id = $contact['id'];
1352 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1357 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1360 'url' => $data['url'],
1361 'nurl' => Strings::normaliseLink($data['url']),
1362 'network' => $data['network'],
1363 'created' => DateTimeFormat::utcNow(),
1364 'rel' => self::SHARING,
1371 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1373 // Before inserting we do check if the entry does exist now.
1374 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1375 if (DBA::isResult($contact)) {
1376 $contact_id = $contact['id'];
1377 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1379 $contact_id = self::insert($fields);
1381 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1386 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1390 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1393 if ($data['network'] == Protocol::DIASPORA) {
1395 DI::dsprContact()->updateFromProbeArray($data);
1396 } catch (HTTPException\NotFoundException $e) {
1397 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1398 } catch (\InvalidArgumentException $e) {
1399 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1401 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1403 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1404 } catch (HTTPException\NotFoundException $e) {
1405 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1406 } catch (\InvalidArgumentException $e) {
1407 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1411 self::updateFromProbeArray($contact_id, $data);
1413 // Don't return a number for a deleted account
1414 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1415 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1423 * Checks if the contact is archived
1425 * @param int $cid contact id
1427 * @return boolean Is the contact archived?
1428 * @throws HTTPException\InternalServerErrorException
1430 public static function isArchived(int $cid): bool
1436 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1437 if (!DBA::isResult($contact)) {
1441 if ($contact['archive']) {
1445 // Check status of ActivityPub endpoints
1446 $apcontact = APContact::getByURL($contact['url'], false);
1447 if (!empty($apcontact)) {
1448 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1452 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1457 // Check status of Diaspora endpoints
1458 if (!empty($contact['batch'])) {
1459 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1460 return DBA::exists('contact', $condition);
1467 * Checks if the contact is blocked
1469 * @param int $cid contact id
1470 * @return boolean Is the contact blocked?
1471 * @throws HTTPException\InternalServerErrorException
1473 public static function isBlocked(int $cid): bool
1479 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1480 if (!DBA::isResult($blocked)) {
1484 if (Network::isUrlBlocked($blocked['url'])) {
1488 return (bool) $blocked['blocked'];
1492 * Checks if the contact is hidden
1494 * @param int $cid contact id
1495 * @return boolean Is the contact hidden?
1496 * @throws \Exception
1498 public static function isHidden(int $cid): bool
1504 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1505 if (!DBA::isResult($hidden)) {
1508 return (bool) $hidden['hidden'];
1512 * Returns posts from a given contact url
1514 * @param string $contact_url Contact URL
1515 * @param bool $thread_mode
1516 * @param int $update Update mode
1517 * @param int $parent Item parent ID for the update mode
1518 * @param bool $only_media Only display media content
1519 * @return string posts in HTML
1520 * @throws \Exception
1522 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1524 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1528 * Returns posts from a given contact id
1530 * @param int $cid Contact ID
1531 * @param bool $thread_mode
1532 * @param int $update Update mode
1533 * @param int $parent Item parent ID for the update mode
1534 * @param bool $only_media Only display media content
1535 * @return string posts in HTML
1536 * @throws \Exception
1538 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1540 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1541 if (!DBA::isResult($contact)) {
1545 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1546 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1551 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1554 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1555 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()];
1557 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1558 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1561 if (!empty($parent)) {
1562 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1564 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1565 if (!empty($last_received)) {
1566 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1571 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1572 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1575 if (DI::mode()->isMobile()) {
1576 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1577 DI::config()->get('system', 'itemspage_network_mobile'));
1579 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1580 DI::config()->get('system', 'itemspage_network'));
1583 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1585 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1587 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1588 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1589 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1595 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1596 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1598 if ($pager->getStart() == 0) {
1599 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1600 if (!empty($cdata['public'])) {
1601 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1602 $items = array_merge($items, $pinned);
1606 $o .= DI::conversation()->create($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1608 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1609 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1611 if ($pager->getStart() == 0) {
1612 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1613 if (!empty($cdata['public'])) {
1614 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1615 $cdata['public'], Post\Collection::FEATURED];
1616 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1617 $items = array_merge($pinned, $items);
1621 $o .= DI::conversation()->create($items, ConversationContent::MODE_CONTACT_POSTS, $update);
1625 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1626 $o .= HTML::scrollLoader();
1628 $o .= $pager->renderMinimal(count($items));
1636 * Returns the account type name
1638 * The function can be called with either the user or the contact array
1640 * @param int $type type of contact or account
1643 public static function getAccountType(int $type): string
1646 case self::TYPE_ORGANISATION:
1647 $account_type = DI::l10n()->t("Organisation");
1650 case self::TYPE_NEWS:
1651 $account_type = DI::l10n()->t('News');
1654 case self::TYPE_COMMUNITY:
1655 $account_type = DI::l10n()->t("Group");
1663 return $account_type;
1669 * @param int $cid Contact id to block
1670 * @param string $reason Block reason
1671 * @return bool Whether it was successful
1673 public static function block(int $cid, string $reason = null): bool
1675 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1681 * Unblocks a contact
1683 * @param int $cid Contact id to unblock
1684 * @return bool Whether it was successful
1686 public static function unblock(int $cid): bool
1688 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1694 * Ensure that cached avatar exist
1696 * @param integer $cid Contact id
1698 public static function checkAvatarCache(int $cid)
1700 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1701 if (!DBA::isResult($contact)) {
1705 if (Network::isLocalLink($contact['url'])) {
1709 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1710 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1711 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1712 self::updateAvatar($cid, $contact['avatar'], true);
1715 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1716 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1717 self::updateAvatar($cid, $contact['avatar'], true);
1719 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1720 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1721 self::updateAvatar($cid, $contact['avatar'], true);
1727 * Return the photo path for a given contact array in the given size
1729 * @param array $contact contact array
1730 * @param string $size Size of the avatar picture
1731 * @param bool $no_update Don't perform an update if no cached avatar was found
1732 * @return string photo path
1734 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1736 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1738 if (DI::config()->get('system', 'avatar_cache')) {
1740 case Proxy::SIZE_MICRO:
1741 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1742 return $contact['micro'];
1745 case Proxy::SIZE_THUMB:
1746 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1747 return $contact['thumb'];
1750 case Proxy::SIZE_SMALL:
1751 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1752 return $contact['photo'];
1758 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1762 * Return the photo path for a given contact array
1764 * @param array $contact Contact array
1765 * @param bool $no_update Don't perform an update if no cached avatar was found
1766 * @return string photo path
1768 public static function getPhoto(array $contact, bool $no_update = false): string
1770 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1774 * Return the photo path (thumb size) for a given contact array
1776 * @param array $contact Contact array
1777 * @param bool $no_update Don't perform an update if no cached avatar was found
1778 * @return string photo path
1780 public static function getThumb(array $contact, bool $no_update = false): string
1782 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1786 * Return the photo path (micro size) for a given contact array
1788 * @param array $contact Contact array
1789 * @param bool $no_update Don't perform an update if no cached avatar was found
1790 * @return string photo path
1792 public static function getMicro(array $contact, bool $no_update = false): string
1794 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1798 * Check the given contact array for avatar cache fields
1800 * @param array $contact
1801 * @param bool $no_update Don't perform an update if no cached avatar was found
1802 * @return array contact array with avatar cache fields
1804 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1807 $contact_fields = [];
1808 $fields = ['photo', 'thumb', 'micro'];
1809 foreach ($fields as $field) {
1810 if (isset($contact[$field])) {
1811 $contact_fields[] = $field;
1813 if (isset($contact[$field]) && empty($contact[$field])) {
1818 if (!$update || $no_update) {
1822 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1824 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1825 self::updateAvatar($contact['id'], $contact['avatar'], true);
1827 $new_contact = self::getById($contact['id'], $contact_fields);
1828 if (DBA::isResult($new_contact)) {
1829 // We only update the cache fields
1830 $contact = array_merge($contact, $new_contact);
1832 } elseif ($local && !empty($contact['avatar'])) {
1836 /// add the default avatars if the fields aren't filled
1837 if (isset($contact['photo']) && empty($contact['photo'])) {
1838 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1840 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1841 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1843 if (isset($contact['micro']) && empty($contact['micro'])) {
1844 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1851 * Fetch the default header for the given contact
1853 * @param array $contact contact array
1854 * @return string avatar URL
1856 public static function getDefaultHeader(array $contact): string
1858 if (!empty($contact['header'])) {
1859 return $contact['header'];
1862 if (!empty($contact['gsid'])) {
1863 // Use default banners for certain platforms
1864 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1865 $platform = strtolower($gserver['platform'] ?? '');
1870 switch ($platform) {
1875 * @author Lostinlight <https://mastodon.xyz/@lightone>
1876 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1877 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1879 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1884 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1885 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1886 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1888 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1892 * Use a random picture.
1893 * The service provides random pictures from Unsplash.
1894 * @license https://unsplash.com/license
1896 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1904 * Fetch the default avatar for the given contact and size
1906 * @param array $contact contact array
1907 * @param string $size Size of the avatar picture
1908 * @return string avatar URL
1910 public static function getDefaultAvatar(array $contact, string $size): string
1913 case Proxy::SIZE_MICRO:
1914 $avatar['size'] = 48;
1915 $default = self::DEFAULT_AVATAR_MICRO;
1918 case Proxy::SIZE_THUMB:
1919 $avatar['size'] = 80;
1920 $default = self::DEFAULT_AVATAR_THUMB;
1923 case Proxy::SIZE_SMALL:
1925 $avatar['size'] = 300;
1926 $default = self::DEFAULT_AVATAR_PHOTO;
1930 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1932 $type = Contact::TYPE_PERSON;
1934 if (!empty($contact['id'])) {
1935 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1936 $platform = $account['platform'] ?? '';
1937 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1940 if (empty($platform) && !empty($contact['uri-id'])) {
1941 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1942 $platform = $account['platform'] ?? '';
1943 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1946 switch ($platform) {
1950 * @license GNU Affero General Public License v3.0
1951 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1953 $default = '/images/default/corgidon.png';
1959 * @license GNU Affero General Public License v3.0
1960 * @link https://github.com/diaspora/diaspora/
1962 $default = '/images/default/diaspora.png';
1968 * @license GNU Affero General Public License v3.0
1969 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1971 $default = '/images/default/gotosocial.svg';
1977 * @license GNU Affero General Public License v3.0
1978 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1980 $default = '/images/default/hometown.png';
1986 * @license GNU Affero General Public License v3.0
1987 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1989 $default = '/images/default/koyuspace.png';
1997 * @license GNU Affero General Public License v3.0
1998 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2000 $default = '/images/default/mastodon.png';
2004 if ($type == Contact::TYPE_COMMUNITY) {
2007 * @license GNU Affero General Public License v3.0
2008 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2010 $default = '/images/default/peertube-channel.png';
2014 * @license GNU Affero General Public License v3.0
2015 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2017 $default = '/images/default/peertube-account.png';
2024 * @license GNU Affero General Public License v3.0
2025 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2027 $default = '/images/default/pleroma.png';
2033 * @license GNU Affero General Public License v3.0
2034 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2036 $default = '/images/default/plume.png';
2039 return DI::baseUrl() . $default;
2042 if (!empty($contact['xmpp'])) {
2043 $avatar['email'] = $contact['xmpp'];
2044 } elseif (!empty($contact['addr'])) {
2045 $avatar['email'] = $contact['addr'];
2046 } elseif (!empty($contact['url'])) {
2047 $avatar['email'] = $contact['url'];
2049 return DI::baseUrl() . $default;
2052 $avatar['url'] = '';
2053 $avatar['success'] = false;
2055 Hook::callAll('avatar_lookup', $avatar);
2057 if ($avatar['success'] && !empty($avatar['url'])) {
2058 return $avatar['url'];
2061 return DI::baseUrl() . $default;
2065 * Get avatar link for given contact id
2067 * @param integer $cid contact id
2068 * @param string $size One of the Proxy::SIZE_* constants
2069 * @param string $updated Contact update date
2070 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2071 * @return string avatar link
2073 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2075 // We have to fetch the "updated" variable when it wasn't provided
2076 // The parameter can be provided to improve performance
2077 if (empty($updated)) {
2078 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2079 $updated = $account['updated'] ?? '';
2080 $guid = $account['guid'] ?? '';
2083 $guid = urlencode($guid);
2085 $url = DI::baseUrl() . '/photo/contact/';
2087 case Proxy::SIZE_MICRO:
2088 $url .= Proxy::PIXEL_MICRO . '/';
2090 case Proxy::SIZE_THUMB:
2091 $url .= Proxy::PIXEL_THUMB . '/';
2093 case Proxy::SIZE_SMALL:
2094 $url .= Proxy::PIXEL_SMALL . '/';
2096 case Proxy::SIZE_MEDIUM:
2097 $url .= Proxy::PIXEL_MEDIUM . '/';
2099 case Proxy::SIZE_LARGE:
2100 $url .= Proxy::PIXEL_LARGE . '/';
2105 $query_params['ts'] = strtotime($updated);
2108 $query_params['static'] = true;
2111 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2115 * Get avatar link for given contact URL
2117 * @param string $url contact url
2118 * @param integer $uid user id
2119 * @param string $size One of the Proxy::SIZE_* constants
2120 * @return string avatar link
2122 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2124 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2125 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2126 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2127 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2131 * Get header link for given contact id
2133 * @param integer $cid contact id
2134 * @param string $size One of the Proxy::SIZE_* constants
2135 * @param string $updated Contact update date
2136 * @param bool $static If "true" a parameter is added to convert the header to a static one
2137 * @return string header link
2139 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2141 // We have to fetch the "updated" variable when it wasn't provided
2142 // The parameter can be provided to improve performance
2143 if (empty($updated) || empty($guid)) {
2144 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2145 $updated = $account['updated'] ?? '';
2146 $guid = $account['guid'] ?? '';
2149 $guid = urlencode($guid);
2151 $url = DI::baseUrl() . '/photo/header/';
2153 case Proxy::SIZE_MICRO:
2154 $url .= Proxy::PIXEL_MICRO . '/';
2156 case Proxy::SIZE_THUMB:
2157 $url .= Proxy::PIXEL_THUMB . '/';
2159 case Proxy::SIZE_SMALL:
2160 $url .= Proxy::PIXEL_SMALL . '/';
2162 case Proxy::SIZE_MEDIUM:
2163 $url .= Proxy::PIXEL_MEDIUM . '/';
2165 case Proxy::SIZE_LARGE:
2166 $url .= Proxy::PIXEL_LARGE . '/';
2172 $query_params['ts'] = strtotime($updated);
2175 $query_params['static'] = true;
2178 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2182 * Updates the avatar links in a contact only if needed
2184 * @param int $cid Contact id
2185 * @param string $avatar Link to avatar picture
2186 * @param bool $force force picture update
2187 * @param bool $create_cache Enforces the creation of cached avatar fields
2190 * @throws HTTPException\InternalServerErrorException
2191 * @throws HTTPException\NotFoundException
2192 * @throws \ImagickException
2194 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2196 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2197 ['id' => $cid, 'self' => false]);
2198 if (!DBA::isResult($contact)) {
2202 if (!Network::isValidHttpUrl($avatar)) {
2203 Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
2207 $uid = $contact['uid'];
2209 // Only update the cached photo links of public contacts when they already are cached
2210 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2211 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2212 $update_fields = ['avatar' => $avatar];
2213 if (!Network::isLocalLink($avatar)) {
2215 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2217 $img_str = $fetchResult->getBody();
2218 if (!empty($img_str)) {
2219 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2220 if ($image->isValid()) {
2221 $update_fields['blurhash'] = $image->getBlurHash();
2226 } catch (\Exception $exception) {
2227 Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
2230 } elseif (!empty($contact['blurhash'])) {
2231 $update_fields['blurhash'] = null;
2236 self::update($update_fields, ['id' => $cid]);
2237 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2242 // User contacts use are updated through the public contacts
2243 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2244 $pcid = self::getIdForURL($contact['url'], 0, false);
2245 if (!empty($pcid)) {
2246 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2247 self::updateAvatar($pcid, $avatar, $force, true);
2252 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2254 if ($default_avatar) {
2255 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2258 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2260 // Local contact avatars don't need to be cached
2261 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2262 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2265 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2266 if (Avatar::deleteCache($contact)) {
2270 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2271 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2273 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2274 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2275 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2278 // Use the data from the self account
2279 if (empty($fields)) {
2280 $local_uid = User::getIdForURL($contact['url']);
2281 if (!empty($local_uid)) {
2282 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2283 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2287 if (empty($fields)) {
2288 $update = ($contact['avatar'] != $avatar) || $force;
2292 $contact['photo'] ?? '',
2293 $contact['thumb'] ?? '',
2294 $contact['micro'] ?? '',
2297 foreach ($data as $image_uri) {
2298 $image_rid = Photo::ridFromURI($image_uri);
2299 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2300 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2307 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2309 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2310 $update = !empty($fields);
2311 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2317 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2320 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2321 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2322 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2331 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2332 // Collect all user contacts of the given public contact
2333 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2334 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2335 while ($personal_contact = DBA::fetch($personal_contacts)) {
2336 $cids[] = $personal_contact['id'];
2337 $uids[] = $personal_contact['uid'];
2339 DBA::close($personal_contacts);
2341 if (!empty($cids)) {
2342 // Delete possibly existing cached user contact avatars
2343 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2349 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2350 self::update($fields, ['id' => $cids]);
2353 public static function deleteContactByUrl(string $url)
2355 // Update contact data for all users
2356 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2357 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2358 while ($contact = DBA::fetch($contacts)) {
2359 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2360 self::remove($contact['id']);
2365 * Helper function for "updateFromProbe". Updates personal and public contact
2367 * @param integer $id contact id
2368 * @param integer $uid user id
2369 * @param integer $uri_id Uri-Id
2370 * @param string $url The profile URL of the contact
2371 * @param array $fields The fields that are updated
2373 * @throws \Exception
2375 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2377 if (!self::update($fields, ['id' => $id])) {
2378 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2382 self::setAccountUser($id, $uid, $uri_id, $url);
2384 // Archive or unarchive the contact.
2385 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2386 if (!DBA::isResult($contact)) {
2387 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2391 if (isset($fields['failed'])) {
2392 if ($fields['failed']) {
2393 self::markForArchival($contact);
2395 self::unmarkForArchival($contact);
2399 if ($contact['uid'] != 0) {
2403 // Update contact data for all users
2404 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2406 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2408 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
2409 $condition['network'][] = $contact['network'];
2412 self::update($fields, $condition);
2414 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2415 $condition['network'] = Protocol::OSTATUS;
2417 // If the contact failed, propagate the update fields to all contacts
2418 if (empty($fields['failed'])) {
2419 unset($fields['last-update']);
2420 unset($fields['success_update']);
2421 unset($fields['failure_update']);
2424 if (empty($fields)) {
2428 self::update($fields, $condition);
2432 * Create or update an "account-user" entry
2434 * @param integer $id
2435 * @param integer $uid
2436 * @param integer $uri_id
2437 * @param string $url
2440 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2442 if (empty($uri_id)) {
2446 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2447 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2448 if ($account_user['uid'] == $uid) {
2449 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2450 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2452 // This should never happen
2453 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]);
2457 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2458 if (!empty($account_user['id'])) {
2459 if ($account_user['id'] == $id) {
2460 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2462 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2463 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2464 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2467 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2468 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2469 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2470 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2472 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2477 * Remove duplicated contacts
2479 * @param string $nurl Normalised contact url
2480 * @param integer $uid User id
2482 * @throws \Exception
2484 public static function removeDuplicates(string $nurl, int $uid)
2486 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2487 $count = DBA::count('contact', $condition);
2492 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2493 if (!DBA::isResult($first_contact)) {
2494 // Shouldn't happen - so we handle it
2498 $first = $first_contact['id'];
2499 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2501 // Find all duplicates
2502 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2503 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2504 while ($duplicate = DBA::fetch($duplicates)) {
2505 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2509 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2511 DBA::close($duplicates);
2512 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2517 * Perform a contact update if the contact is outdated
2519 * @param integer $id contact id
2522 public static function updateByIdIfNeeded(int $id): bool
2524 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2525 if (empty($contact['url'])) {
2529 if (self::isLocal($contact['url'])) {
2533 $stamp = (float)microtime(true);
2534 self::updateFromProbe($id);
2535 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
2540 * Perform a contact update if the contact is outdated
2542 * @param string $url contact url
2545 public static function updateByUrlIfNeeded(string $url): bool
2547 $id = self::getIdForURL($url, 0, false);
2549 return self::updateByIdIfNeeded($id);
2551 return (bool)self::getIdForURL($url);
2555 * Updates contact record by provided id and optional network
2557 * @param integer $id contact id
2558 * @param string $network Optional network we are probing for
2560 * @throws HTTPException\InternalServerErrorException
2561 * @throws \ImagickException
2563 public static function updateFromProbe(int $id, string $network = '')
2565 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2566 if (!DBA::isResult($contact)) {
2570 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2572 if ($data['network'] == Protocol::DIASPORA) {
2574 DI::dsprContact()->updateFromProbeArray($data);
2575 } catch (HTTPException\NotFoundException $e) {
2576 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2577 } catch (\InvalidArgumentException $e) {
2578 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2580 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2582 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2583 } catch (HTTPException\NotFoundException $e) {
2584 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2585 } catch (\InvalidArgumentException $e) {
2586 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2590 return self::updateFromProbeArray($id, $data);
2594 * Checks if the given contact has got local data
2597 * @param array $contact
2601 private static function hasLocalData(int $id, array $contact): bool
2603 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2604 // User contacts with the same uri-id exist
2606 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2607 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2610 if (DBA::exists('post-tag', ['cid' => $id])) {
2611 // Is tagged in a post
2614 if (DBA::exists('user-contact', ['cid' => $id])) {
2615 // Has got user-contact data
2618 if (Post::exists(['author-id' => $id])) {
2619 // Posts with this author exist
2622 if (Post::exists(['owner-id' => $id])) {
2623 // Posts with this owner exist
2626 if (Post::exists(['causer-id' => $id])) {
2627 // Posts with this causer exist
2630 // We don't have got this contact locally
2635 * Updates contact record by provided id and probed data
2637 * @param integer $id contact id
2638 * @param array $ret Probed data
2640 * @throws HTTPException\InternalServerErrorException
2641 * @throws \ImagickException
2643 private static function updateFromProbeArray(int $id, array $ret): bool
2646 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2647 This will reliably kill your communication with old Friendica contacts.
2650 // These fields aren't updated by this routine:
2653 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2654 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2655 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2656 'created', 'last-update'];
2657 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2658 if (!DBA::isResult($contact)) {
2662 if (self::isLocal($ret['url'])) {
2663 if ($contact['uid'] == 0) {
2664 Logger::info('Local contacts are not updated here.');
2666 self::updateFromPublicContact($id, $contact);
2671 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2672 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2675 // Delete all contacts with the same URL
2676 self::deleteContactByUrl($ret['url']);
2680 $has_local_data = self::hasLocalData($id, $contact);
2682 $uid = $contact['uid'];
2683 unset($contact['uid']);
2685 $uriid = $contact['uri-id'];
2686 unset($contact['uri-id']);
2688 $pubkey = $contact['pubkey'];
2689 unset($contact['pubkey']);
2691 $created = $contact['created'];
2692 unset($contact['created']);
2694 $last_update = $contact['last-update'];
2695 unset($contact['last-update']);
2697 $contact['photo'] = $contact['avatar'];
2698 unset($contact['avatar']);
2700 $updated = DateTimeFormat::utcNow();
2702 if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
2703 // Periodical checks are only done on federated contacts
2704 $failed_next_update = null;
2705 $success_next_update = null;
2706 } elseif ($has_local_data) {
2707 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2708 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2709 } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
2710 $failed_next_update = DateTimeFormat::utc('now +6 month');
2711 $success_next_update = DateTimeFormat::utc('now +1 month');
2713 // We don't check connector networks very often to not run into API rate limits
2714 $failed_next_update = DateTimeFormat::utc('now +12 month');
2715 $success_next_update = DateTimeFormat::utc('now +12 month');
2718 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2719 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2720 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]);
2724 // We must not try to update relay contacts via probe. They are no real contacts.
2725 // We check after the probing to be able to correct falsely detected contact types.
2726 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2727 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2728 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]);
2729 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2733 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2734 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2735 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]);
2739 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2740 $cid = self::getIdForURL($ret['url'], 0, false);
2741 if (!empty($cid) && ($cid != $id)) {
2742 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2743 return self::updateFromProbeArray($cid, $ret);
2747 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2748 $ret['unsearchable'] = $ret['hide'];
2751 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2752 $ret['forum'] = false;
2753 $ret['prv'] = false;
2754 $ret['contact-type'] = $ret['account-type'];
2755 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2756 $ret['forum'] = (bool)!$ret['manually-approve'];
2757 $ret['prv'] = (bool)!$ret['forum'];
2761 $new_pubkey = $ret['pubkey'] ?? '';
2763 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2764 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2765 $apcontact = APContact::getByURL($ret['url'], false);
2766 if (!empty($apcontact['featured'])) {
2767 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2771 $ret['last-item'] = Probe::getLastUpdate($ret);
2772 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2776 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?: $ret['alias']);
2778 // make sure to not overwrite existing values with blank entries except some technical fields
2779 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2780 foreach ($ret as $key => $val) {
2781 if (!array_key_exists($key, $contact)) {
2783 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2784 $ret[$key] = $contact[$key];
2785 } elseif ($ret[$key] != $contact[$key]) {
2790 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2793 unset($ret['last-item']);
2796 if (empty($uriid)) {
2800 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2801 self::updateAvatar($id, $ret['photo'], $update);
2805 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]);
2807 if (Contact\Relation::isDiscoverable($ret['url'])) {
2808 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2811 // Update the public contact
2813 $contact = self::getByURL($ret['url'], false, ['id']);
2814 if (!empty($contact['id'])) {
2815 self::updateFromProbeArray($contact['id'], $ret);
2822 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2823 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2824 $ret['updated'] = $updated;
2825 $ret['failed'] = false;
2826 $ret['next-update'] = $success_next_update;
2827 $ret['local-data'] = $has_local_data;
2829 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2830 if (empty($pubkey) && !empty($new_pubkey)) {
2831 $ret['pubkey'] = $new_pubkey;
2834 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2835 $ret['uri-date'] = $updated;
2838 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2839 $ret['name-date'] = $updated;
2842 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2843 $ret['last-update'] = $updated;
2844 $ret['success_update'] = $updated;
2847 unset($ret['photo']);
2849 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2851 if (Contact\Relation::isDiscoverable($ret['url'])) {
2852 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2858 private static function updateFromPublicContact(int $id, array $contact)
2860 $public = self::getByURL($contact['url'], false);
2864 foreach ($contact as $field => $value) {
2865 if ($field == 'uid') {
2868 if ($public[$field] != $value) {
2869 $fields[$field] = $public[$field];
2872 if (!empty($fields)) {
2873 self::update($fields, ['id' => $id, 'self' => false]);
2874 Logger::info('Updating local contact', ['id' => $id]);
2879 * Updates contact record by provided URL
2881 * @param integer $url contact url
2882 * @return integer Contact id
2883 * @throws HTTPException\InternalServerErrorException
2884 * @throws \ImagickException
2886 public static function updateFromProbeByURL(string $url): int
2888 $id = self::getIdForURL($url);
2894 self::updateFromProbe($id);
2900 * Detects the communication protocol for a given contact url.
2901 * This is used to detect Friendica contacts that we can communicate via AP.
2903 * @param string $url contact url
2904 * @param string $network Network of that contact
2905 * @return string with protocol
2907 public static function getProtocol(string $url, string $network): string
2909 if ($network != Protocol::DFRN) {
2913 $apcontact = APContact::getByURL($url);
2914 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2915 return Protocol::ACTIVITYPUB;
2922 * Takes a $uid and a url/handle and adds a new contact
2924 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2925 * dfrn_request page.
2927 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2930 * $return['success'] boolean true if successful
2931 * $return['message'] error text if success is false.
2933 * Takes a $uid and a url/handle and adds a new contact
2935 * @param int $uid The user id the contact should be created for
2936 * @param string $url The profile URL of the contact
2937 * @param string $network
2939 * @throws HTTPException\InternalServerErrorException
2940 * @throws HTTPException\NotFoundException
2941 * @throws \ImagickException
2943 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2945 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2947 // remove ajax junk, e.g. Twitter
2948 $url = str_replace('/#!/', '/', $url);
2950 if (!Network::isUrlAllowed($url)) {
2951 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2955 if (Network::isUrlBlocked($url)) {
2956 $result['message'] = DI::l10n()->t('Blocked domain');
2961 $result['message'] = DI::l10n()->t('Connect URL missing.');
2965 $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
2967 Hook::callAll('follow', $arr);
2970 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2974 if (!empty($arr['contact']['name'])) {
2976 $ret = $arr['contact'];
2979 $ret = Probe::uri($url, $network, $uid);
2981 // Ensure that the public contact exists
2982 if ($ret['network'] != Protocol::PHANTOM) {
2983 self::getIdForURL($url);
2987 if (($network != '') && ($ret['network'] != $network)) {
2988 $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
2992 // check if we already have a contact
2993 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
2994 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
2996 $protocol = self::getProtocol($ret['url'], $ret['network']);
2998 // This extra param just confuses things, remove it
2999 if ($protocol === Protocol::DIASPORA) {
3000 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
3003 // do we have enough information?
3004 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
3005 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
3006 if (empty($ret['poll'])) {
3007 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
3009 if (empty($ret['name'])) {
3010 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
3012 if (empty($ret['url'])) {
3013 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
3015 if (strpos($ret['url'], '@') !== false) {
3016 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
3017 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
3022 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3023 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3024 $ret['notify'] = '';
3027 if (!$ret['notify']) {
3028 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3031 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3033 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3035 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3038 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3039 $pending = (bool)$ret['manually-approve'];
3042 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3046 if (DBA::isResult($contact)) {
3048 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3050 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3052 if ($contact['pending'] && !empty($contact['hub-verify'])) {
3053 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3054 $fields['pending'] = false;
3057 self::update($fields, ['id' => $contact['id']]);
3059 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3061 // create contact record
3064 'created' => DateTimeFormat::utcNow(),
3065 'url' => $ret['url'],
3066 'nurl' => Strings::normaliseLink($ret['url']),
3067 'addr' => $ret['addr'],
3068 'alias' => $ret['alias'],
3069 'batch' => $ret['batch'],
3070 'notify' => $ret['notify'],
3071 'poll' => $ret['poll'],
3072 'poco' => $ret['poco'],
3073 'name' => $ret['name'],
3074 'nick' => $ret['nick'],
3075 'network' => $ret['network'],
3076 'baseurl' => $ret['baseurl'],
3077 'gsid' => $ret['gsid'] ?? null,
3078 'protocol' => $protocol,
3079 'pubkey' => $ret['pubkey'],
3080 'rel' => $new_relation,
3081 'priority'=> $ret['priority'],
3082 'writable'=> $writeable,
3083 'hidden' => $hidden,
3086 'pending' => $pending,
3091 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3092 if (!DBA::isResult($contact)) {
3093 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3097 $contact_id = $contact['id'];
3098 $result['cid'] = $contact_id;
3100 Circle::addMember(User::getDefaultCircle($uid), $contact_id);
3102 // Update the avatar
3103 self::updateAvatar($contact_id, $ret['photo']);
3105 // pull feed and consume it, which should subscribe to the hub.
3106 if ($contact['network'] == Protocol::OSTATUS) {
3107 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3111 self::updateFromProbeArray($contact_id, $ret);
3114 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3115 } catch (\InvalidArgumentException $e) {
3116 Logger::notice($e->getMessage(), ['contact' => $contact]);
3120 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3126 * @param array $importer Owner (local user) data
3127 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3128 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3129 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3130 * @param string $note Introduction additional message
3131 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3132 * @throws HTTPException\InternalServerErrorException
3133 * @throws \ImagickException
3135 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3137 // Should always be set
3138 if (empty($datarray['author-id'])) {
3142 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3143 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3144 if (!DBA::isResult($pub_contact)) {
3145 // Should never happen
3149 // Contact is blocked at node-level
3150 if (self::isBlocked($datarray['author-id'])) {
3154 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3155 $name = $pub_contact['name'];
3156 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3157 $nick = $pub_contact['nick'];
3158 $network = $pub_contact['network'];
3160 // Ensure that we don't create a new contact when there already is one
3161 $cid = self::getIdForURL($url, $importer['uid']);
3163 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3166 self::clearFollowerFollowingEndpointCache($importer['uid']);
3168 if (!empty($contact)) {
3169 if (!empty($contact['pending'])) {
3170 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3174 // Contact is blocked at user-level
3175 if (!empty($contact['id']) && !empty($importer['id']) &&
3176 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3180 // Make sure that the existing contact isn't archived
3181 self::unmarkForArchival($contact);
3183 if (($contact['rel'] == self::SHARING)
3184 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3185 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3186 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3189 // Ensure to always have the correct network type, independent from the connection request method
3190 self::updateFromProbe($contact['id']);
3192 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3196 // send email notification to owner?
3197 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3198 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3202 // create contact record
3203 $contact_id = self::insert([
3204 'uid' => $importer['uid'],
3205 'created' => DateTimeFormat::utcNow(),
3207 'nurl' => Strings::normaliseLink($url),
3210 'network' => $network,
3211 'rel' => self::FOLLOWER,
3218 // Ensure to always have the correct network type, independent from the connection request method
3219 self::updateFromProbe($contact_id);
3221 self::updateAvatar($contact_id, $photo, true);
3223 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3225 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3227 /// @TODO Encapsulate this into a function/method
3228 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3229 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3230 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3231 // create notification
3232 if (is_array($contact_record)) {
3233 $intro = DI::introFactory()->createNew(
3235 $contact_record['id'],
3238 DI::intro()->save($intro);
3241 Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
3243 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3244 DI::notify()->createFromArray([
3245 'type' => Notification\Type::INTRO,
3246 'otype' => Notification\ObjectType::INTRO,
3247 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3248 'uid' => $user['uid'],
3249 'cid' => $contact_record['id'],
3250 'link' => DI::baseUrl() . '/notifications/intros',
3253 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3254 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3255 self::createFromProbeForUser($importer['uid'], $url, $network);
3258 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3259 $fields = ['pending' => false];
3260 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3261 $fields['rel'] = self::FRIEND;
3264 self::update($fields, $condition);
3274 * Update the local relationship when a local user loses a follower
3276 * @param array $contact User-specific contact (uid != 0) array
3278 * @throws HTTPException\InternalServerErrorException
3279 * @throws \ImagickException
3281 public static function removeFollower(array $contact)
3283 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3284 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3285 } elseif (!empty($contact['id'])) {
3286 self::remove($contact['id']);
3288 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3292 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3294 self::clearFollowerFollowingEndpointCache($contact['uid']);
3296 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3297 if (!empty($cdata['public'])) {
3298 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3303 * Update the local relationship when a local user unfollow a contact.
3304 * Removes the contact for sharing-only protocols (feed and mail).
3306 * @param array $contact User-specific contact (uid != 0) array
3307 * @throws HTTPException\InternalServerErrorException
3309 public static function removeSharer(array $contact)
3311 self::clearFollowerFollowingEndpointCache($contact['uid']);
3313 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3314 self::remove($contact['id']);
3316 self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
3319 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3323 * Create a birthday event.
3325 * Update the year and the birthday.
3327 public static function updateBirthdays()
3331 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3332 AND NOT `contact`.`pending`
3333 AND NOT `contact`.`hidden`
3334 AND NOT `contact`.`blocked`
3335 AND NOT `contact`.`archive`
3336 AND NOT `contact`.`deleted`',
3342 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3344 while ($contact = DBA::fetch($contacts)) {
3345 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3347 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3349 if (Event::createBirthday($contact, $nextbd)) {
3353 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3354 ['id' => $contact['id']]
3358 DBA::close($contacts);
3362 * Remove the unavailable contact ids from the provided list
3364 * @param array $contact_ids Contact id list
3366 * @throws \Exception
3368 public static function pruneUnavailable(array $contact_ids): array
3370 if (empty($contact_ids)) {
3374 $contacts = self::selectToArray(['id'], [
3375 'id' => $contact_ids,
3381 return array_column($contacts, 'id');
3385 * Returns a magic link to authenticate remote visitors
3387 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3389 * @param string $contact_url The address of the target contact profile
3390 * @param string $url An url that we will be redirected to after the authentication
3392 * @return string with "redir" link
3393 * @throws HTTPException\InternalServerErrorException
3394 * @throws \ImagickException
3396 public static function magicLink(string $contact_url, string $url = ''): string
3398 if (!DI::userSession()->isAuthenticated()) {
3399 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3402 $contact = self::getByURL($contact_url, false);
3403 if (empty($contact)) {
3404 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3407 // Prevents endless loop in case only a non-public contact exists for the contact URL
3408 unset($contact['uid']);
3410 return self::magicLinkByContact($contact, $url ?: $contact_url);
3414 * Returns a magic link to authenticate remote visitors
3416 * @param integer $cid The contact id of the target contact profile
3417 * @param string $url An url that we will be redirected to after the authentication
3419 * @return string with "redir" link
3420 * @throws HTTPException\InternalServerErrorException
3421 * @throws \ImagickException
3423 public static function magicLinkById(int $cid, string $url = ''): string
3425 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3427 return self::magicLinkByContact($contact, $url);
3431 * Returns a magic link to authenticate remote visitors
3433 * @param array $contact The contact array with "uid", "network" and "url"
3434 * @param string $url An url that we will be redirected to after the authentication
3436 * @return string with "redir" link
3437 * @throws HTTPException\InternalServerErrorException
3438 * @throws \ImagickException
3440 public static function magicLinkByContact(array $contact, string $url = ''): string
3442 $destination = $url ?: $contact['url'];
3444 if (!DI::userSession()->isAuthenticated()) {
3445 return $destination;
3448 // Only redirections to the same host do make sense
3449 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3453 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3454 return 'contact/' . $contact['id'] . '/conversations';
3457 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3458 return $destination;
3461 if (empty($contact['id'])) {
3462 return $destination;
3465 $redirect = 'contact/redir/' . $contact['id'];
3467 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3468 $redirect .= '?url=' . $url;
3475 * Is the contact a group?
3477 * @param integer $contactid ID of the contact
3479 * @return boolean "true" if it is a group
3481 public static function isGroup(int $contactid): bool
3483 $fields = ['contact-type'];
3484 $condition = ['id' => $contactid];
3485 $contact = DBA::selectFirst('contact', $fields, $condition);
3486 if (!DBA::isResult($contact)) {
3491 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3495 * Can the remote contact receive private messages?
3497 * @param array $contact
3500 public static function canReceivePrivateMessages(array $contact): bool
3502 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3503 $self = $contact['self'] ?? false;
3505 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3509 * Search contact table by nick or name
3511 * @param string $search Name or nick
3512 * @param string $mode Search mode (e.g. "community")
3513 * @param bool $show_blocked Show users from blocked servers. Default is false
3514 * @param int $uid User ID
3515 * @param int $limit Maximum amount of returned values
3516 * @param int $offset Limit offset
3518 * @return array with search results
3519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3521 public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
3523 if (empty($search)) {
3527 // check supported networks
3528 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3529 if (DI::config()->get('system', 'diaspora_enabled')) {
3530 $networks[] = Protocol::DIASPORA;
3533 if (!DI::config()->get('system', 'ostatus_disabled')) {
3534 $networks[] = Protocol::OSTATUS;
3538 'network' => $networks,
3539 'server-failed' => false,
3542 'unsearchable' => false,
3546 if (!$show_blocked) {
3547 $condition['server-blocked'] = true;
3551 $condition['blocked'] = false;
3553 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3556 // check if we search only communities or every contact
3557 if ($mode === 'community') {
3558 $condition['contact-type'] = self::TYPE_COMMUNITY;
3565 if (!empty($limit) && !empty($offset)) {
3566 $params['limit'] = [$offset, $limit];
3567 } elseif (!empty($limit)) {
3568 $params['limit'] = $limit;
3571 $condition = DBA::mergeConditions($condition,
3572 ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3574 return DBA::selectToArray('account-user-view', [], $condition, $params);
3578 * Add public contacts from an array
3580 * @param array $urls
3581 * @return array result "count", "added" and "updated"
3583 public static function addByUrls(array $urls): array
3590 foreach ($urls as $url) {
3591 if (empty($url) || !is_string($url)) {
3594 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3595 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3596 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3598 } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3600 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3602 } catch (\InvalidArgumentException $e) {
3603 Logger::notice($e->getMessage(), ['contact' => $contact]);
3611 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3615 * Returns a random, global contact array of the current node
3617 * @return array The profile array
3620 public static function getRandomContact(): array
3622 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3623 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3624 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3625 ], ['order' => ['RAND()']]);
3627 if (DBA::isResult($contact)) {
3635 * Checks, if contacts with the given condition exists
3637 * @param array $condition
3640 * @throws \Exception
3642 public static function exists(array $condition): bool
3644 return DBA::exists('contact', $condition);