3 * @copyright Copyright (C) 2010-2022, 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\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Network\HTTPException;
40 use Friendica\Network\Probe;
41 use Friendica\Object\Image;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
52 * functions for interacting with a contact
56 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
57 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
58 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
64 const LOCK_INSERT = 'contact-insert';
69 * TYPE_UNKNOWN - unknown type
71 * TYPE_PERSON - the account belongs to a person
72 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
74 * TYPE_ORGANISATION - the account belongs to an organisation
75 * Associated page type: PAGE_SOAPBOX
77 * TYPE_NEWS - the account is a news reflector
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_COMMUNITY - the account is community forum
81 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
83 * TYPE_RELAY - the account is a relay
84 * This will only be assigned to contacts, not to user accounts
87 const TYPE_UNKNOWN = -1;
88 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
89 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
90 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
91 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
92 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
103 const NOTHING = 0; // There is no relationship between the contact and the user
104 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
105 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
106 const FRIEND = 3; // There is a mutual relationship between the contact and the user
107 const SELF = 4; // This is the user theirself
112 const MIRROR_DEACTIVATED = 0;
113 const MIRROR_FORWARDED = 1; // Deprecated, now does the same like MIRROR_OWN_POST
114 const MIRROR_OWN_POST = 2;
115 const MIRROR_NATIVE_RESHARE = 3;
118 * @param array $fields Array of selected fields, empty for all
119 * @param array $condition Array of fields for condition
120 * @param array $params Array of several parameters
124 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
126 return DBA::selectToArray('contact', $fields, $condition, $params);
130 * @param array $fields Array of selected fields, empty for all
131 * @param array $condition Array of fields for condition
132 * @param array $params Array of several parameters
136 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
138 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
144 * @param array $fields Array of selected fields, empty for all
145 * @param array $condition Array of fields for condition
146 * @param array $params Array of several parameters
150 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
152 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
156 * @param array $fields Array of selected fields, empty for all
157 * @param array $condition Array of fields for condition
158 * @param array $params Array of several parameters
162 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
164 return DBA::selectFirst('account-view', $fields, $condition, $params);
168 * Insert a row into the contact table
169 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
171 * @param array $fields field array
172 * @param int $duplicate_mode Do an update on a duplicate entry
174 * @return int id of the created contact
177 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
179 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
180 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
183 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
185 if (empty($fields['created'])) {
186 $fields['created'] = DateTimeFormat::utcNow();
189 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
190 DBA::insert('contact', $fields, $duplicate_mode);
191 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
192 if (!DBA::isResult($contact)) {
194 Logger::warning('Created contact could not be found', ['fields' => $fields]);
198 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
199 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
200 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
201 if (empty($account_user['id'])) {
202 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
203 } elseif ($account_user['id'] != $contact['id']) {
204 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
205 if (!empty($duplicate['id'])) {
206 $ret = Contact::deleteById($contact['id']);
207 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']]);
208 $contact = $duplicate;
210 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
211 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']]);
215 Contact\User::insertForContactArray($contact);
217 return $contact['id'];
221 * Delete contact by id
226 public static function deleteById(int $id): bool
228 Logger::debug('Delete contact', ['id' => $id]);
229 DBA::delete('account-user', ['id' => $id]);
230 return DBA::delete('contact', ['id' => $id]);
234 * Updates rows in the contact table
236 * @param array $fields contains the fields that are updated
237 * @param array $condition condition array with the key values
238 * @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)
240 * @return boolean was the update successfull?
242 * @todo Let's get rid of boolean type of $old_fields
244 public static function update(array $fields, array $condition, $old_fields = [])
246 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
247 $ret = DBA::update('contact', $fields, $condition, $old_fields);
249 // Apply changes to the "user-contact" table on dedicated fields
250 Contact\User::updateByContactUpdate($fields, $condition);
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'] 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 // Update the contact in the background if needed
362 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
363 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
366 // Remove the internal fields
367 foreach ($removal as $internal) {
368 unset($contact[$internal]);
375 * Fetches a contact for a given user by a given url.
376 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
378 * @param string $url profile url
379 * @param integer $uid User ID of the contact
380 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
381 * @param array $fields Field list
382 * @return array contact array
384 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
387 $contact = self::getByURL($url, $update, $fields, $uid);
388 if (!empty($contact)) {
389 if (!empty($contact['id'])) {
390 $contact['cid'] = $contact['id'];
397 $contact = self::getByURL($url, $update, $fields);
398 if (!empty($contact['id'])) {
400 $contact['zid'] = $contact['id'];
406 * Checks if a contact uses a specific platform
409 * @param string $platform
412 public static function isPlatform(string $url, string $platform): bool
414 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
418 * Tests if the given contact is a follower
420 * @param int $cid Either public contact id or user's contact id
421 * @param int $uid User ID
422 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
424 * @return boolean is the contact id a follower?
425 * @throws HTTPException\InternalServerErrorException
426 * @throws \ImagickException
428 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
430 if (Contact\User::isBlocked($cid, $uid)) {
434 $cdata = self::getPublicAndUserContactID($cid, $uid);
435 if (empty($cdata['user'])) {
439 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
441 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
443 return DBA::exists('contact', $condition);
447 * Tests if the given contact url is a follower
449 * @param string $url Contact URL
450 * @param int $uid User ID
451 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
453 * @return boolean is the contact id a follower?
454 * @throws HTTPException\InternalServerErrorException
455 * @throws \ImagickException
457 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
459 $cid = self::getIdForURL($url, $uid);
465 return self::isFollower($cid, $uid, $strict);
469 * Tests if the given user shares with the given contact
471 * @param int $cid Either public contact id or user's contact id
472 * @param int $uid User ID
473 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
475 * @return boolean is the contact sharing with given user?
476 * @throws HTTPException\InternalServerErrorException
477 * @throws \ImagickException
479 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
481 if (Contact\User::isBlocked($cid, $uid)) {
485 $cdata = self::getPublicAndUserContactID($cid, $uid);
486 if (empty($cdata['user'])) {
490 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
492 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
494 return DBA::exists('contact', $condition);
498 * Tests if the given user follow the given contact url
500 * @param string $url Contact URL
501 * @param int $uid User ID
502 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
504 * @return boolean is the contact url being followed?
505 * @throws HTTPException\InternalServerErrorException
506 * @throws \ImagickException
508 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
510 $cid = self::getIdForURL($url, $uid);
516 return self::isSharing($cid, $uid, $strict);
520 * Get the basepath for a given contact link
522 * @param string $url The contact link
523 * @param boolean $dont_update Don't update the contact
525 * @return string basepath
526 * @throws HTTPException\InternalServerErrorException
527 * @throws \ImagickException
529 public static function getBasepath(string $url, bool $dont_update = false): string
531 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
532 if (!DBA::isResult($contact)) {
536 if (!empty($contact['baseurl'])) {
537 return $contact['baseurl'];
538 } elseif ($dont_update) {
542 // Update the existing contact
543 self::updateFromProbe($contact['id']);
545 // And fetch the result
546 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
547 if (empty($contact['baseurl'])) {
548 Logger::info('No baseurl for contact', ['url' => $url]);
552 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
553 return $contact['baseurl'];
557 * Check if the given contact url is on the same server
559 * @param string $url The contact link
561 * @return boolean Is it the same server?
563 public static function isLocal(string $url): bool
565 if (!parse_url($url, PHP_URL_SCHEME)) {
566 $addr_parts = explode('@', $url);
567 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
570 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
574 * Check if the given contact ID is on the same server
576 * @param string $url The contact link
577 * @return boolean Is it the same server?
579 public static function isLocalById(int $cid): bool
581 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
582 if (!DBA::isResult($contact)) {
586 if (empty($contact['baseurl'])) {
587 $baseurl = self::getBasepath($contact['url'], true);
589 $baseurl = $contact['baseurl'];
592 return Strings::compareLink($baseurl, DI::baseUrl());
596 * Returns the public contact id of the given user id
598 * @param integer $uid User ID
600 * @return integer|boolean Public contact id for given user id
603 public static function getPublicIdByUserId(int $uid)
605 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
606 if (!DBA::isResult($self)) {
609 return self::getIdForURL($self['url']);
613 * Returns the contact id for the user and the public contact id for a given contact id
615 * @param int $cid Either public contact id or user's contact id
616 * @param int $uid User ID
618 * @return array with public and user's contact id
619 * @throws HTTPException\InternalServerErrorException
620 * @throws \ImagickException
622 public static function getPublicAndUserContactID(int $cid, int $uid): array
624 // We have to use the legacy function as long as the post update hasn't finished
625 if (DI::config()->get('system', 'post_update_version') < 1427) {
626 return self::legacyGetPublicAndUserContactID($cid, $uid);
629 if (empty($uid) || empty($cid)) {
633 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
634 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
638 $pcid = $contact['pid'];
639 if ($contact['uid'] == $uid) {
640 $ucid = $contact['id'];
642 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
643 if (DBA::isResult($contact)) {
644 $ucid = $contact['id'];
650 return ['public' => $pcid, 'user' => $ucid];
654 * Helper function for "getPublicAndUserContactID"
656 * @param int $cid Either public contact id or user's contact id
657 * @param int $uid User ID
658 * @return array with public and user's contact id
659 * @throws HTTPException\InternalServerErrorException
660 * @throws \ImagickException
662 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
664 if (empty($uid) || empty($cid)) {
668 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
669 if (!DBA::isResult($contact)) {
673 // We quit when the user id don't match the user id of the provided contact
674 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
678 if ($contact['uid'] != 0) {
679 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
683 $ucid = $contact['id'];
685 $pcid = $contact['id'];
686 $ucid = self::getIdForURL($contact['url'], $uid);
689 return ['public' => $pcid, 'user' => $ucid];
693 * Returns contact details for a given contact id in combination with a user id
695 * @param int $cid A contact ID
696 * @param int $uid The User ID
697 * @param array $fields The selected fields for the contact
698 * @return array The contact details
702 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
704 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
706 if (!DBA::isResult($contact)) {
714 * Creates the self-contact for the provided user id
717 * @return bool Operation success
718 * @throws HTTPException\InternalServerErrorException
720 public static function createSelfFromUserId(int $uid): bool
722 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
723 ['uid' => $uid, 'account_expired' => false]);
724 if (!DBA::isResult($user)) {
729 'uid' => $user['uid'],
730 'created' => DateTimeFormat::utcNow(),
732 'name' => $user['username'],
733 'nick' => $user['nickname'],
734 'pubkey' => $user['pubkey'],
735 'prvkey' => $user['prvkey'],
736 'photo' => User::getAvatarUrl($user),
737 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
738 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
741 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
742 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
743 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
744 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
745 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
746 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
747 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
748 'name-date' => DateTimeFormat::utcNow(),
749 'uri-date' => DateTimeFormat::utcNow(),
750 'avatar-date' => DateTimeFormat::utcNow(),
756 // Only create the entry if it doesn't exist yet
757 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
758 $return = (bool)self::insert($contact);
761 // Create the public contact
762 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
763 $contact['self'] = false;
765 $contact['prvkey'] = null;
767 self::insert($contact, Database::INSERT_IGNORE);
774 * Updates the self-contact for the provided user id
777 * @param bool $update_avatar Force the avatar update
778 * @return bool "true" if updated
779 * @throws HTTPException\InternalServerErrorException
781 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
783 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
784 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
785 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
786 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
787 if (!DBA::isResult($self)) {
791 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
792 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
793 if (!DBA::isResult($user)) {
797 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
798 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
799 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
800 if (!DBA::isResult($profile)) {
804 $file_suffix = 'jpg';
805 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
808 'name' => $profile['name'],
809 'nick' => $user['nickname'],
810 'avatar-date' => $self['avatar-date'],
811 'location' => Profile::formatLocation($profile),
812 'about' => $profile['about'],
813 'keywords' => $profile['pub_keywords'],
814 'contact-type' => $user['account-type'],
815 'prvkey' => $user['prvkey'],
816 'pubkey' => $user['pubkey'],
817 'xmpp' => $profile['xmpp'],
818 'matrix' => $profile['matrix'],
819 'network' => Protocol::DFRN,
821 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
822 'nurl' => Strings::normaliseLink($url),
823 'uri-id' => ItemURI::getIdByURI($url),
824 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
825 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
826 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
827 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
828 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
832 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
833 if (DBA::isResult($avatar)) {
834 if ($update_avatar) {
835 $fields['avatar-date'] = DateTimeFormat::utcNow();
838 // Creating the path to the avatar, beginning with the file suffix
839 $types = Images::supportedTypes();
840 if (isset($types[$avatar['type']])) {
841 $file_suffix = $types[$avatar['type']];
844 // We are adding a timestamp value so that other systems won't use cached content
845 $timestamp = strtotime($fields['avatar-date']);
847 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
848 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
850 $fields['photo'] = $prefix . '4' . $suffix;
851 $fields['thumb'] = $prefix . '5' . $suffix;
852 $fields['micro'] = $prefix . '6' . $suffix;
854 // We hadn't found a photo entry, so we use the default avatar
855 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
856 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
857 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
860 $fields['avatar'] = User::getAvatarUrl($user);
861 $fields['header'] = User::getBannerUrl($user);
862 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
863 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
864 $fields['unsearchable'] = !$profile['net-publish'];
865 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
869 foreach ($fields as $field => $content) {
870 if ($self[$field] != $content) {
876 if ($fields['name'] != $self['name']) {
877 $fields['name-date'] = DateTimeFormat::utcNow();
879 $fields['updated'] = DateTimeFormat::utcNow();
880 self::update($fields, ['id' => $self['id']]);
882 // Update the other contacts as well
883 unset($fields['prvkey']);
884 $fields['self'] = false;
885 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
887 // Update the profile
889 'photo' => User::getAvatarUrl($user),
890 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
893 DBA::update('profile', $fields, ['uid' => $uid]);
900 * Marks a contact for removal
902 * @param int $id contact id
904 * @throws HTTPException\InternalServerErrorException
906 public static function remove(int $id)
908 // We want just to make sure that we don't delete our "self" contact
909 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
910 if (!DBA::isResult($contact)) {
914 DBA::delete('account-user', ['id' => $id]);
916 self::clearFollowerFollowingEndpointCache($contact['uid']);
918 // Archive the contact
919 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
921 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
922 Avatar::deleteCache($contact);
925 // Delete it in the background
926 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
930 * Unfollow the remote contact
932 * @param array $contact Target user-specific contact (uid != 0) array
934 * @throws HTTPException\InternalServerErrorException
935 * @throws \ImagickException
937 public static function unfollow(array $contact): void
939 if (empty($contact['network'])) {
940 throw new \InvalidArgumentException('Empty network in contact array');
943 if (empty($contact['uid'])) {
944 throw new \InvalidArgumentException('Unexpected public contact record');
947 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
948 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
949 if (!empty($cdata['public'])) {
950 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
954 self::removeSharer($contact);
958 * Revoke follow privileges of the remote user contact
960 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
962 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
964 * @throws HTTPException\InternalServerErrorException
965 * @throws \ImagickException
967 public static function revokeFollow(array $contact): void
969 if (empty($contact['network'])) {
970 throw new \InvalidArgumentException('Empty network in contact array');
973 if (empty($contact['uid'])) {
974 throw new \InvalidArgumentException('Unexpected public contact record');
977 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
978 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
979 if (!empty($cdata['public'])) {
980 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
984 self::removeFollower($contact);
988 * Completely severs a relationship with a contact
990 * @param array $contact User-specific contact (uid != 0) array
992 * @throws HTTPException\InternalServerErrorException
993 * @throws \ImagickException
995 public static function terminateFriendship(array $contact)
997 if (empty($contact['network'])) {
998 throw new \InvalidArgumentException('Empty network in contact array');
1001 if (empty($contact['uid'])) {
1002 throw new \InvalidArgumentException('Unexpected public contact record');
1005 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1007 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1008 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1011 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1012 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1015 self::remove($contact['id']);
1018 private static function clearFollowerFollowingEndpointCache(int $uid)
1024 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1025 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1029 * Marks a contact for archival after a communication issue delay
1031 * Contact has refused to recognise us as a friend. We will start a countdown.
1032 * If they still don't recognise us in 32 days, the relationship is over,
1033 * and we won't waste any more time trying to communicate with them.
1034 * This provides for the possibility that their database is temporarily messed
1035 * up or some other transient event and that there's a possibility we could recover from it.
1037 * @param array $contact contact to mark for archival
1039 * @throws HTTPException\InternalServerErrorException
1041 public static function markForArchival(array $contact)
1043 if (!isset($contact['url']) && !empty($contact['id'])) {
1044 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1045 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1046 if (!DBA::isResult($contact)) {
1049 } elseif (!isset($contact['url'])) {
1050 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1053 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1055 // Contact already archived or "self" contact? => nothing to do
1056 if ($contact['archive'] || $contact['self']) {
1060 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1061 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1062 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1065 * We really should send a notification to the owner after 2-3 weeks
1066 * so they won't be surprised when the contact vanishes and can take
1067 * remedial action if this was a serious mistake or glitch
1070 /// @todo Check for contact vitality via probing
1071 $archival_days = DI::config()->get('system', 'archival_days', 32);
1073 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1074 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1075 /* Relationship is really truly dead. archive them rather than
1076 * delete, though if the owner tries to unarchive them we'll start
1077 * the whole process over again.
1079 self::update(['archive' => true], ['id' => $contact['id']]);
1080 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1086 * Cancels the archival countdown
1088 * @see Contact::markForArchival()
1090 * @param array $contact contact to be unmarked for archival
1092 * @throws \Exception
1094 public static function unmarkForArchival(array $contact)
1096 // Always unarchive the relay contact entry
1097 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1098 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1099 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1100 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1101 self::update($fields, $condition);
1105 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1106 $exists = DBA::exists('contact', $condition);
1108 // We don't need to update, we never marked this contact for archival
1113 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1115 if (!isset($contact['url']) && !empty($contact['id'])) {
1116 $fields = ['id', 'url', 'batch'];
1117 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1118 if (!DBA::isResult($contact)) {
1123 // It's a miracle. Our dead contact has inexplicably come back to life.
1124 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1125 self::update($fields, ['id' => $contact['id']]);
1126 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1130 * Returns the data array for the photo menu of a given contact
1132 * @param array $contact contact
1133 * @param int $uid Visitor user id
1135 * @throws HTTPException\InternalServerErrorException
1136 * @throws \ImagickException
1138 public static function photoMenu(array $contact, int $uid): array
1140 // Anonymous visitor
1142 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1150 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1152 $profile_link = 'contact/redir/' . $contact['id'];
1154 $profile_link = $contact['url'];
1157 if ($profile_link === 'mailbox') {
1162 $status_link = $profile_link . '/status';
1163 $photos_link = $profile_link . '/photos';
1164 $profile_link = $profile_link . '/profile';
1167 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1168 $pm_url = 'message/new/' . $contact['id'];
1171 $contact_url = 'contact/' . $contact['id'];
1172 $posts_link = 'contact/' . $contact['id'] . '/conversations';
1175 $unfollow_link = '';
1176 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1177 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1178 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1179 } elseif (!$contact['pending']) {
1180 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1186 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1188 if (empty($contact['uid'])) {
1190 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1191 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1192 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1193 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1194 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1198 'status' => [DI::l10n()->t('View Status') , $status_link , true ],
1199 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1200 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true ],
1201 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1202 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1203 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1204 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1205 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1208 if (!empty($contact['pending'])) {
1210 $intro = DI::intro()->selectForContact($contact['id']);
1211 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1212 } catch (IntroductionNotFoundException $exception) {
1213 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1218 $args = ['contact' => $contact, 'menu' => &$menu];
1220 Hook::callAll('contact_photo_menu', $args);
1222 $menucondensed = [];
1224 foreach ($menu as $menuname => $menuitem) {
1225 if ($menuitem[1] != '') {
1226 $menucondensed[$menuname] = $menuitem;
1230 return $menucondensed;
1234 * Fetch the contact id for a given URL and user
1236 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1237 * `addr` or `alias`.
1239 * If there's no record and we aren't looking for a public contact, we quit.
1240 * If there's one, we check that it isn't time to update the picture else we
1241 * directly return the found contact id.
1243 * Second, we probe the provided $url whether it's http://server.tld/profile or
1244 * nick@server.tld. We quit if we can't get any info back.
1246 * Third, we create the contact record if it doesn't exist
1248 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1249 * if there's any updates
1251 * @param string $url Contact URL
1252 * @param integer $uid The user id for the contact (0 = public contact)
1253 * @param boolean $update true = always update, false = never update, null = update when not found
1254 * @param array $default Default value for creating the contact when everything else fails
1256 * @return integer Contact ID
1257 * @throws HTTPException\InternalServerErrorException
1258 * @throws \ImagickException
1260 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1265 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1269 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1271 if (!empty($contact)) {
1272 $contact_id = $contact['id'];
1274 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1275 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1278 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1279 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1282 } elseif ($uid != 0) {
1283 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1285 } elseif (empty($default) && !is_null($update) && !$update) {
1286 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1292 if (empty($default['network']) || $update) {
1293 $data = Probe::uri($url, '', $uid);
1295 // Take the default values when probing failed
1296 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1297 $data = array_merge($data, $default);
1299 } elseif (!empty($default['network'])) {
1303 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1304 // Fetch data for the public contact via the first found personal contact
1305 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1306 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1307 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1308 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1310 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1311 if (!DBA::isResult($personal_contact)) {
1312 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1315 if (DBA::isResult($personal_contact)) {
1316 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1317 $data = $personal_contact;
1318 $data['photo'] = $personal_contact['avatar'];
1319 $data['account-type'] = $personal_contact['contact-type'];
1320 $data['hide'] = $personal_contact['unsearchable'];
1321 unset($data['avatar']);
1322 unset($data['contact-type']);
1323 unset($data['unsearchable']);
1327 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1328 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1332 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1333 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1338 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1339 if (!empty($data['alias'])) {
1340 $urls[] = Strings::normaliseLink($data['alias']);
1342 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1343 if (!empty($contact['id'])) {
1344 $contact_id = $contact['id'];
1345 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1350 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1353 'url' => $data['url'],
1354 'nurl' => Strings::normaliseLink($data['url']),
1355 'network' => $data['network'],
1356 'created' => DateTimeFormat::utcNow(),
1357 'rel' => self::SHARING,
1364 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1366 // Before inserting we do check if the entry does exist now.
1367 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1368 if (DBA::isResult($contact)) {
1369 $contact_id = $contact['id'];
1370 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1372 $contact_id = self::insert($fields);
1374 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1379 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1383 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1386 if ($data['network'] == Protocol::DIASPORA) {
1388 DI::dsprContact()->updateFromProbeArray($data);
1389 } catch (HTTPException\NotFoundException $e) {
1390 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1391 } catch (\InvalidArgumentException $e) {
1392 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1394 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1396 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1397 } catch (HTTPException\NotFoundException $e) {
1398 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1399 } catch (\InvalidArgumentException $e) {
1400 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1404 self::updateFromProbeArray($contact_id, $data);
1406 // Don't return a number for a deleted account
1407 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1408 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1416 * Checks if the contact is archived
1418 * @param int $cid contact id
1420 * @return boolean Is the contact archived?
1421 * @throws HTTPException\InternalServerErrorException
1423 public static function isArchived(int $cid): bool
1429 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1430 if (!DBA::isResult($contact)) {
1434 if ($contact['archive']) {
1438 // Check status of ActivityPub endpoints
1439 $apcontact = APContact::getByURL($contact['url'], false);
1440 if (!empty($apcontact)) {
1441 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1445 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1450 // Check status of Diaspora endpoints
1451 if (!empty($contact['batch'])) {
1452 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1453 return DBA::exists('contact', $condition);
1460 * Checks if the contact is blocked
1462 * @param int $cid contact id
1463 * @return boolean Is the contact blocked?
1464 * @throws HTTPException\InternalServerErrorException
1466 public static function isBlocked(int $cid): bool
1472 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1473 if (!DBA::isResult($blocked)) {
1477 if (Network::isUrlBlocked($blocked['url'])) {
1481 return (bool) $blocked['blocked'];
1485 * Checks if the contact is hidden
1487 * @param int $cid contact id
1488 * @return boolean Is the contact hidden?
1489 * @throws \Exception
1491 public static function isHidden(int $cid): bool
1497 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1498 if (!DBA::isResult($hidden)) {
1501 return (bool) $hidden['hidden'];
1505 * Returns posts from a given contact url
1507 * @param string $contact_url Contact URL
1508 * @param bool $thread_mode
1509 * @param int $update Update mode
1510 * @param int $parent Item parent ID for the update mode
1511 * @param bool $only_media Only display media content
1512 * @return string posts in HTML
1513 * @throws \Exception
1515 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1517 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1521 * Returns posts from a given contact id
1523 * @param int $cid Contact ID
1524 * @param bool $thread_mode
1525 * @param int $update Update mode
1526 * @param int $parent Item parent ID for the update mode
1527 * @param bool $only_media Only display media content
1528 * @return string posts in HTML
1529 * @throws \Exception
1531 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1533 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1534 if (!DBA::isResult($contact)) {
1538 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1539 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1544 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1547 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1548 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()];
1550 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1551 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1554 if (!empty($parent)) {
1555 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1557 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1558 if (!empty($last_received)) {
1559 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1564 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1565 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1568 if (DI::mode()->isMobile()) {
1569 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1570 DI::config()->get('system', 'itemspage_network_mobile'));
1572 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1573 DI::config()->get('system', 'itemspage_network'));
1576 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1578 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1580 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1581 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1582 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1588 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1589 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1591 if ($pager->getStart() == 0) {
1592 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1593 if (!empty($cdata['public'])) {
1594 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1595 $items = array_merge($items, $pinned);
1599 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1601 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1602 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1604 if ($pager->getStart() == 0) {
1605 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1606 if (!empty($cdata['public'])) {
1607 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1608 $cdata['public'], Post\Collection::FEATURED];
1609 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1610 $items = array_merge($pinned, $items);
1614 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1618 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1619 $o .= HTML::scrollLoader();
1621 $o .= $pager->renderMinimal(count($items));
1629 * Returns the account type name
1631 * The function can be called with either the user or the contact array
1633 * @param int $type type of contact or account
1636 public static function getAccountType(int $type): string
1639 case self::TYPE_ORGANISATION:
1640 $account_type = DI::l10n()->t("Organisation");
1643 case self::TYPE_NEWS:
1644 $account_type = DI::l10n()->t('News');
1647 case self::TYPE_COMMUNITY:
1648 $account_type = DI::l10n()->t("Forum");
1656 return $account_type;
1662 * @param int $cid Contact id to block
1663 * @param string $reason Block reason
1664 * @return bool Whether it was successful
1666 public static function block(int $cid, string $reason = null): bool
1668 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1674 * Unblocks a contact
1676 * @param int $cid Contact id to unblock
1677 * @return bool Whether it was successfull
1679 public static function unblock(int $cid): bool
1681 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1687 * Ensure that cached avatar exist
1689 * @param integer $cid Contact id
1691 public static function checkAvatarCache(int $cid)
1693 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1694 if (!DBA::isResult($contact)) {
1698 if (Network::isLocalLink($contact['url'])) {
1702 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1703 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1704 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1705 self::updateAvatar($cid, $contact['avatar'], true);
1708 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1709 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1710 self::updateAvatar($cid, $contact['avatar'], true);
1712 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1713 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1714 self::updateAvatar($cid, $contact['avatar'], true);
1720 * Return the photo path for a given contact array in the given size
1722 * @param array $contact contact array
1723 * @param string $size Size of the avatar picture
1724 * @param bool $no_update Don't perfom an update if no cached avatar was found
1725 * @return string photo path
1727 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1729 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1731 if (DI::config()->get('system', 'avatar_cache')) {
1733 case Proxy::SIZE_MICRO:
1734 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1735 return $contact['micro'];
1738 case Proxy::SIZE_THUMB:
1739 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1740 return $contact['thumb'];
1743 case Proxy::SIZE_SMALL:
1744 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1745 return $contact['photo'];
1751 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1755 * Return the photo path for a given contact array
1757 * @param array $contact Contact array
1758 * @param bool $no_update Don't perfom an update if no cached avatar was found
1759 * @return string photo path
1761 public static function getPhoto(array $contact, bool $no_update = false): string
1763 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1767 * Return the photo path (thumb size) for a given contact array
1769 * @param array $contact Contact array
1770 * @param bool $no_update Don't perfom an update if no cached avatar was found
1771 * @return string photo path
1773 public static function getThumb(array $contact, bool $no_update = false): string
1775 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1779 * Return the photo path (micro size) for a given contact array
1781 * @param array $contact Contact array
1782 * @param bool $no_update Don't perfom an update if no cached avatar was found
1783 * @return string photo path
1785 public static function getMicro(array $contact, bool $no_update = false): string
1787 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1791 * Check the given contact array for avatar cache fields
1793 * @param array $contact
1794 * @param bool $no_update Don't perfom an update if no cached avatar was found
1795 * @return array contact array with avatar cache fields
1797 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1800 $contact_fields = [];
1801 $fields = ['photo', 'thumb', 'micro'];
1802 foreach ($fields as $field) {
1803 if (isset($contact[$field])) {
1804 $contact_fields[] = $field;
1806 if (isset($contact[$field]) && empty($contact[$field])) {
1811 if (!$update || $no_update) {
1815 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1817 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1818 self::updateAvatar($contact['id'], $contact['avatar'], true);
1820 $new_contact = self::getById($contact['id'], $contact_fields);
1821 if (DBA::isResult($new_contact)) {
1822 // We only update the cache fields
1823 $contact = array_merge($contact, $new_contact);
1825 } elseif ($local && !empty($contact['avatar'])) {
1829 /// add the default avatars if the fields aren't filled
1830 if (isset($contact['photo']) && empty($contact['photo'])) {
1831 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1833 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1834 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1836 if (isset($contact['micro']) && empty($contact['micro'])) {
1837 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1844 * Fetch the default header for the given contact
1846 * @param array $contact contact array
1847 * @return string avatar URL
1849 public static function getDefaultHeader(array $contact): string
1851 if (!empty($contact['header'])) {
1852 return $contact['header'];
1855 if (!empty($contact['gsid'])) {
1856 // Use default banners for certain platforms
1857 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1858 $platform = strtolower($gserver['platform'] ?? '');
1863 switch ($platform) {
1868 * @author Lostinlight <https://mastodon.xyz/@lightone>
1869 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1870 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1872 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1877 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1878 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1879 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1881 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1885 * Use a random picture.
1886 * The service provides random pictures from Unsplash.
1887 * @license https://unsplash.com/license
1889 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1897 * Fetch the default avatar for the given contact and size
1899 * @param array $contact contact array
1900 * @param string $size Size of the avatar picture
1901 * @return string avatar URL
1903 public static function getDefaultAvatar(array $contact, string $size): string
1906 case Proxy::SIZE_MICRO:
1907 $avatar['size'] = 48;
1908 $default = self::DEFAULT_AVATAR_MICRO;
1911 case Proxy::SIZE_THUMB:
1912 $avatar['size'] = 80;
1913 $default = self::DEFAULT_AVATAR_THUMB;
1916 case Proxy::SIZE_SMALL:
1918 $avatar['size'] = 300;
1919 $default = self::DEFAULT_AVATAR_PHOTO;
1923 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1925 $type = Contact::TYPE_PERSON;
1927 if (!empty($contact['id'])) {
1928 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1929 $platform = $account['platform'] ?? '';
1930 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1933 if (empty($platform) && !empty($contact['uri-id'])) {
1934 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1935 $platform = $account['platform'] ?? '';
1936 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1939 switch ($platform) {
1943 * @license GNU Affero General Public License v3.0
1944 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1946 $default = '/images/default/corgidon.png';
1952 * @license GNU Affero General Public License v3.0
1953 * @link https://github.com/diaspora/diaspora/
1955 $default = '/images/default/diaspora.png';
1961 * @license GNU Affero General Public License v3.0
1962 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1964 $default = '/images/default/gotosocial.svg';
1970 * @license GNU Affero General Public License v3.0
1971 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1973 $default = '/images/default/hometown.png';
1979 * @license GNU Affero General Public License v3.0
1980 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1982 $default = '/images/default/koyuspace.png';
1990 * @license GNU Affero General Public License v3.0
1991 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1993 $default = '/images/default/mastodon.png';
1997 if ($type == Contact::TYPE_COMMUNITY) {
2000 * @license GNU Affero General Public License v3.0
2001 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2003 $default = '/images/default/peertube-channel.png';
2007 * @license GNU Affero General Public License v3.0
2008 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2010 $default = '/images/default/peertube-account.png';
2017 * @license GNU Affero General Public License v3.0
2018 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2020 $default = '/images/default/pleroma.png';
2026 * @license GNU Affero General Public License v3.0
2027 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2029 $default = '/images/default/plume.png';
2032 return DI::baseUrl() . $default;
2035 if (!empty($contact['xmpp'])) {
2036 $avatar['email'] = $contact['xmpp'];
2037 } elseif (!empty($contact['addr'])) {
2038 $avatar['email'] = $contact['addr'];
2039 } elseif (!empty($contact['url'])) {
2040 $avatar['email'] = $contact['url'];
2042 return DI::baseUrl() . $default;
2045 $avatar['url'] = '';
2046 $avatar['success'] = false;
2048 Hook::callAll('avatar_lookup', $avatar);
2050 if ($avatar['success'] && !empty($avatar['url'])) {
2051 return $avatar['url'];
2054 return DI::baseUrl() . $default;
2058 * Get avatar link for given contact id
2060 * @param integer $cid contact id
2061 * @param string $size One of the Proxy::SIZE_* constants
2062 * @param string $updated Contact update date
2063 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2064 * @return string avatar link
2066 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2068 // We have to fetch the "updated" variable when it wasn't provided
2069 // The parameter can be provided to improve performance
2070 if (empty($updated)) {
2071 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2072 $updated = $account['updated'] ?? '';
2073 $guid = $account['guid'] ?? '';
2076 $guid = urlencode($guid);
2078 $url = DI::baseUrl() . '/photo/contact/';
2080 case Proxy::SIZE_MICRO:
2081 $url .= Proxy::PIXEL_MICRO . '/';
2083 case Proxy::SIZE_THUMB:
2084 $url .= Proxy::PIXEL_THUMB . '/';
2086 case Proxy::SIZE_SMALL:
2087 $url .= Proxy::PIXEL_SMALL . '/';
2089 case Proxy::SIZE_MEDIUM:
2090 $url .= Proxy::PIXEL_MEDIUM . '/';
2092 case Proxy::SIZE_LARGE:
2093 $url .= Proxy::PIXEL_LARGE . '/';
2098 $query_params['ts'] = strtotime($updated);
2101 $query_params['static'] = true;
2104 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2108 * Get avatar link for given contact URL
2110 * @param string $url contact url
2111 * @param integer $uid user id
2112 * @param string $size One of the Proxy::SIZE_* constants
2113 * @return string avatar link
2115 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2117 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2118 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2119 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2120 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2124 * Get header link for given contact id
2126 * @param integer $cid contact id
2127 * @param string $size One of the Proxy::SIZE_* constants
2128 * @param string $updated Contact update date
2129 * @param bool $static If "true" a parameter is added to convert the header to a static one
2130 * @return string header link
2132 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2134 // We have to fetch the "updated" variable when it wasn't provided
2135 // The parameter can be provided to improve performance
2136 if (empty($updated) || empty($guid)) {
2137 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2138 $updated = $account['updated'] ?? '';
2139 $guid = $account['guid'] ?? '';
2142 $guid = urlencode($guid);
2144 $url = DI::baseUrl() . '/photo/header/';
2146 case Proxy::SIZE_MICRO:
2147 $url .= Proxy::PIXEL_MICRO . '/';
2149 case Proxy::SIZE_THUMB:
2150 $url .= Proxy::PIXEL_THUMB . '/';
2152 case Proxy::SIZE_SMALL:
2153 $url .= Proxy::PIXEL_SMALL . '/';
2155 case Proxy::SIZE_MEDIUM:
2156 $url .= Proxy::PIXEL_MEDIUM . '/';
2158 case Proxy::SIZE_LARGE:
2159 $url .= Proxy::PIXEL_LARGE . '/';
2165 $query_params['ts'] = strtotime($updated);
2168 $query_params['static'] = true;
2171 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2175 * Updates the avatar links in a contact only if needed
2177 * @param int $cid Contact id
2178 * @param string $avatar Link to avatar picture
2179 * @param bool $force force picture update
2180 * @param bool $create_cache Enforces the creation of cached avatar fields
2183 * @throws HTTPException\InternalServerErrorException
2184 * @throws HTTPException\NotFoundException
2185 * @throws \ImagickException
2187 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2189 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2190 ['id' => $cid, 'self' => false]);
2191 if (!DBA::isResult($contact)) {
2195 $uid = $contact['uid'];
2197 // Only update the cached photo links of public contacts when they already are cached
2198 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2199 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2200 $update_fields = ['avatar' => $avatar];
2201 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2203 $img_str = $fetchResult->getBody();
2204 if (!empty($img_str)) {
2205 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2206 if ($image->isValid()) {
2207 $update_fields['blurhash'] = $image->getBlurHash();
2211 self::update($update_fields, ['id' => $cid]);
2212 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2217 // User contacts use are updated through the public contacts
2218 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2219 $pcid = self::getIdForURL($contact['url'], 0, false);
2220 if (!empty($pcid)) {
2221 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2222 self::updateAvatar($pcid, $avatar, $force, true);
2227 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2229 if ($default_avatar) {
2230 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2233 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2235 // Local contact avatars don't need to be cached
2236 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2237 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2240 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2241 Avatar::deleteCache($contact);
2243 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2244 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2246 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2247 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2248 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2251 // Use the data from the self account
2252 if (empty($fields)) {
2253 $local_uid = User::getIdForURL($contact['url']);
2254 if (!empty($local_uid)) {
2255 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2256 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2260 if (empty($fields)) {
2261 $update = ($contact['avatar'] != $avatar) || $force;
2265 $contact['photo'] ?? '',
2266 $contact['thumb'] ?? '',
2267 $contact['micro'] ?? '',
2270 foreach ($data as $image_uri) {
2271 $image_rid = Photo::ridFromURI($image_uri);
2272 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2273 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2280 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2282 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2283 $update = !empty($fields);
2284 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2290 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2293 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2294 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2295 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2304 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2305 // Collect all user contacts of the given public contact
2306 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2307 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2308 while ($personal_contact = DBA::fetch($personal_contacts)) {
2309 $cids[] = $personal_contact['id'];
2310 $uids[] = $personal_contact['uid'];
2312 DBA::close($personal_contacts);
2314 if (!empty($cids)) {
2315 // Delete possibly existing cached user contact avatars
2316 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2322 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2323 self::update($fields, ['id' => $cids]);
2326 public static function deleteContactByUrl(string $url)
2328 // Update contact data for all users
2329 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2330 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2331 while ($contact = DBA::fetch($contacts)) {
2332 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2333 self::remove($contact['id']);
2338 * Helper function for "updateFromProbe". Updates personal and public contact
2340 * @param integer $id contact id
2341 * @param integer $uid user id
2342 * @param integer $uri_id Uri-Id
2343 * @param string $url The profile URL of the contact
2344 * @param array $fields The fields that are updated
2346 * @throws \Exception
2348 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2350 if (!self::update($fields, ['id' => $id])) {
2351 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2355 self::setAccountUser($id, $uid, $uri_id, $url);
2357 // Archive or unarchive the contact.
2358 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2359 if (!DBA::isResult($contact)) {
2360 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2364 if (isset($fields['failed'])) {
2365 if ($fields['failed']) {
2366 self::markForArchival($contact);
2368 self::unmarkForArchival($contact);
2372 if ($contact['uid'] != 0) {
2376 // Update contact data for all users
2377 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2379 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2380 self::update($fields, $condition);
2382 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2383 $condition['network'] = Protocol::OSTATUS;
2385 // If the contact failed, propagate the update fields to all contacts
2386 if (empty($fields['failed'])) {
2387 unset($fields['last-update']);
2388 unset($fields['success_update']);
2389 unset($fields['failure_update']);
2392 if (empty($fields)) {
2396 self::update($fields, $condition);
2400 * Create or update an "account-user" entry
2402 * @param integer $id
2403 * @param integer $uid
2404 * @param integer $uri_id
2405 * @param string $url
2408 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2410 if (empty($uri_id)) {
2414 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2415 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2416 if ($account_user['uid'] == $uid) {
2417 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2418 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2420 // This should never happen
2421 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]);
2425 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2426 if (!empty($account_user['id'])) {
2427 if ($account_user['id'] == $id) {
2428 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2430 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2431 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2432 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2435 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2436 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2437 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2438 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2440 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2445 * Remove duplicated contacts
2447 * @param string $nurl Normalised contact url
2448 * @param integer $uid User id
2450 * @throws \Exception
2452 public static function removeDuplicates(string $nurl, int $uid)
2454 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2455 $count = DBA::count('contact', $condition);
2460 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2461 if (!DBA::isResult($first_contact)) {
2462 // Shouldn't happen - so we handle it
2466 $first = $first_contact['id'];
2467 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2469 // Find all duplicates
2470 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2471 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2472 while ($duplicate = DBA::fetch($duplicates)) {
2473 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2477 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2479 DBA::close($duplicates);
2480 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2485 * Updates contact record by provided id and optional network
2487 * @param integer $id contact id
2488 * @param string $network Optional network we are probing for
2490 * @throws HTTPException\InternalServerErrorException
2491 * @throws \ImagickException
2493 public static function updateFromProbe(int $id, string $network = '')
2495 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2496 if (!DBA::isResult($contact)) {
2500 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2502 if ($data['network'] == Protocol::DIASPORA) {
2504 DI::dsprContact()->updateFromProbeArray($data);
2505 } catch (HTTPException\NotFoundException $e) {
2506 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2507 } catch (\InvalidArgumentException $e) {
2508 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2510 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2512 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2513 } catch (HTTPException\NotFoundException $e) {
2514 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2515 } catch (\InvalidArgumentException $e) {
2516 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2520 return self::updateFromProbeArray($id, $data);
2524 * Checks if the given contact has got local data
2527 * @param array $contact
2531 private static function hasLocalData(int $id, array $contact): bool
2533 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2534 // User contacts with the same uri-id exist
2536 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2537 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2540 if (DBA::exists('post-tag', ['cid' => $id])) {
2541 // Is tagged in a post
2544 if (DBA::exists('user-contact', ['cid' => $id])) {
2545 // Has got user-contact data
2548 if (Post::exists(['author-id' => $id])) {
2549 // Posts with this author exist
2552 if (Post::exists(['owner-id' => $id])) {
2553 // Posts with this owner exist
2556 if (Post::exists(['causer-id' => $id])) {
2557 // Posts with this causer exist
2560 // We don't have got this contact locally
2565 * Updates contact record by provided id and probed data
2567 * @param integer $id contact id
2568 * @param array $ret Probed data
2570 * @throws HTTPException\InternalServerErrorException
2571 * @throws \ImagickException
2573 private static function updateFromProbeArray(int $id, array $ret): bool
2576 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2577 This will reliably kill your communication with old Friendica contacts.
2580 // These fields aren't updated by this routine:
2583 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2584 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2585 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2586 'created', 'last-update'];
2587 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2588 if (!DBA::isResult($contact)) {
2592 if (self::isLocal($ret['url'])) {
2593 if ($contact['uid'] == 0) {
2594 Logger::info('Local contacts are not updated here.');
2596 self::updateFromPublicContact($id, $contact);
2601 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2602 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2605 // Delete all contacts with the same URL
2606 self::deleteContactByUrl($ret['url']);
2610 $uid = $contact['uid'];
2611 unset($contact['uid']);
2613 $uriid = $contact['uri-id'];
2614 unset($contact['uri-id']);
2616 $pubkey = $contact['pubkey'];
2617 unset($contact['pubkey']);
2619 $created = $contact['created'];
2620 unset($contact['created']);
2622 $last_update = $contact['last-update'];
2623 unset($contact['last-update']);
2625 $contact['photo'] = $contact['avatar'];
2626 unset($contact['avatar']);
2628 $updated = DateTimeFormat::utcNow();
2630 $has_local_data = self::hasLocalData($id, $contact);
2632 if (!Probe::isProbable($ret['network'])) {
2633 // Periodical checks are only done on federated contacts
2634 $failed_next_update = null;
2635 $success_next_update = null;
2636 } elseif ($has_local_data) {
2637 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2638 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2640 $failed_next_update = DateTimeFormat::utc('now +6 month');
2641 $success_next_update = DateTimeFormat::utc('now +1 month');
2644 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2645 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2646 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]);
2650 // We must not try to update relay contacts via probe. They are no real contacts.
2651 // We check after the probing to be able to correct falsely detected contact types.
2652 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2653 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2654 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]);
2655 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2659 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2660 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2661 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]);
2665 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2666 $cid = self::getIdForURL($ret['url'], 0, false);
2667 if (!empty($cid) && ($cid != $id)) {
2668 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2669 return self::updateFromProbeArray($cid, $ret);
2673 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2674 $ret['unsearchable'] = $ret['hide'];
2677 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2678 $ret['forum'] = false;
2679 $ret['prv'] = false;
2680 $ret['contact-type'] = $ret['account-type'];
2681 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2682 $ret['forum'] = (bool)!$ret['manually-approve'];
2683 $ret['prv'] = (bool)!$ret['forum'];
2687 $new_pubkey = $ret['pubkey'] ?? '';
2689 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2690 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2691 $apcontact = APContact::getByURL($ret['url'], false);
2692 if (!empty($apcontact['featured'])) {
2693 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2697 $ret['last-item'] = Probe::getLastUpdate($ret);
2698 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2702 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url']);
2704 // make sure to not overwrite existing values with blank entries except some technical fields
2705 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2706 foreach ($ret as $key => $val) {
2707 if (!array_key_exists($key, $contact)) {
2709 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2710 $ret[$key] = $contact[$key];
2711 } elseif ($ret[$key] != $contact[$key]) {
2716 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2719 unset($ret['last-item']);
2722 if (empty($uriid)) {
2726 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2727 self::updateAvatar($id, $ret['photo'], $update);
2731 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]);
2733 if (Contact\Relation::isDiscoverable($ret['url'])) {
2734 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2737 // Update the public contact
2739 $contact = self::getByURL($ret['url'], false, ['id']);
2740 if (!empty($contact['id'])) {
2741 self::updateFromProbeArray($contact['id'], $ret);
2748 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2749 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2750 $ret['updated'] = $updated;
2751 $ret['failed'] = false;
2752 $ret['next-update'] = $success_next_update;
2753 $ret['local-data'] = $has_local_data;
2755 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2756 if (empty($pubkey) && !empty($new_pubkey)) {
2757 $ret['pubkey'] = $new_pubkey;
2760 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2761 $ret['uri-date'] = $updated;
2764 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2765 $ret['name-date'] = $updated;
2768 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2769 $ret['last-update'] = $updated;
2770 $ret['success_update'] = $updated;
2773 unset($ret['photo']);
2775 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2777 if (Contact\Relation::isDiscoverable($ret['url'])) {
2778 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2784 private static function updateFromPublicContact(int $id, array $contact)
2786 $public = self::getByURL($contact['url'], false);
2790 foreach ($contact as $field => $value) {
2791 if ($field == 'uid') {
2794 if ($public[$field] != $value) {
2795 $fields[$field] = $public[$field];
2798 if (!empty($fields)) {
2799 self::update($fields, ['id' => $id, 'self' => false]);
2800 Logger::info('Updating local contact', ['id' => $id]);
2805 * Updates contact record by provided URL
2807 * @param integer $url contact url
2808 * @return integer Contact id
2809 * @throws HTTPException\InternalServerErrorException
2810 * @throws \ImagickException
2812 public static function updateFromProbeByURL(string $url): int
2814 $id = self::getIdForURL($url);
2820 self::updateFromProbe($id);
2826 * Detects the communication protocol for a given contact url.
2827 * This is used to detect Friendica contacts that we can communicate via AP.
2829 * @param string $url contact url
2830 * @param string $network Network of that contact
2831 * @return string with protocol
2833 public static function getProtocol(string $url, string $network): string
2835 if ($network != Protocol::DFRN) {
2839 $apcontact = APContact::getByURL($url);
2840 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2841 return Protocol::ACTIVITYPUB;
2848 * Takes a $uid and a url/handle and adds a new contact
2850 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2851 * dfrn_request page.
2853 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2856 * $return['success'] boolean true if successful
2857 * $return['message'] error text if success is false.
2859 * Takes a $uid and a url/handle and adds a new contact
2861 * @param int $uid The user id the contact should be created for
2862 * @param string $url The profile URL of the contact
2863 * @param string $network
2865 * @throws HTTPException\InternalServerErrorException
2866 * @throws HTTPException\NotFoundException
2867 * @throws \ImagickException
2869 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2871 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2873 // remove ajax junk, e.g. Twitter
2874 $url = str_replace('/#!/', '/', $url);
2876 if (!Network::isUrlAllowed($url)) {
2877 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2881 if (Network::isUrlBlocked($url)) {
2882 $result['message'] = DI::l10n()->t('Blocked domain');
2887 $result['message'] = DI::l10n()->t('Connect URL missing.');
2891 $arr = ['url' => $url, 'contact' => []];
2893 Hook::callAll('follow', $arr);
2896 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2900 if (!empty($arr['contact']['name'])) {
2902 $ret = $arr['contact'];
2905 $ret = Probe::uri($url, $network, $uid);
2907 // Ensure that the public contact exists
2908 if ($ret['network'] != Protocol::PHANTOM) {
2909 self::getIdForURL($url);
2913 if (($network != '') && ($ret['network'] != $network)) {
2914 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2918 // check if we already have a contact
2919 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url'])];
2920 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
2922 $protocol = self::getProtocol($ret['url'], $ret['network']);
2924 // This extra param just confuses things, remove it
2925 if ($protocol === Protocol::DIASPORA) {
2926 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2929 // do we have enough information?
2930 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2931 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
2932 if (empty($ret['poll'])) {
2933 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
2935 if (empty($ret['name'])) {
2936 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
2938 if (empty($ret['url'])) {
2939 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
2941 if (strpos($ret['url'], '@') !== false) {
2942 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
2943 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
2948 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2949 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
2950 $ret['notify'] = '';
2953 if (!$ret['notify']) {
2954 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
2957 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2959 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2961 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2964 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2965 $pending = (bool)$ret['manually-approve'];
2968 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2972 if (DBA::isResult($contact)) {
2974 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2976 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
2978 if ($contact['pending'] && !empty($contact['hub-verify'])) {
2979 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
2980 $fields['pending'] = false;
2983 self::update($fields, ['id' => $contact['id']]);
2985 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2987 // create contact record
2990 'created' => DateTimeFormat::utcNow(),
2991 'url' => $ret['url'],
2992 'nurl' => Strings::normaliseLink($ret['url']),
2993 'addr' => $ret['addr'],
2994 'alias' => $ret['alias'],
2995 'batch' => $ret['batch'],
2996 'notify' => $ret['notify'],
2997 'poll' => $ret['poll'],
2998 'poco' => $ret['poco'],
2999 'name' => $ret['name'],
3000 'nick' => $ret['nick'],
3001 'network' => $ret['network'],
3002 'baseurl' => $ret['baseurl'],
3003 'gsid' => $ret['gsid'] ?? null,
3004 'protocol' => $protocol,
3005 'pubkey' => $ret['pubkey'],
3006 'rel' => $new_relation,
3007 'priority'=> $ret['priority'],
3008 'writable'=> $writeable,
3009 'hidden' => $hidden,
3012 'pending' => $pending,
3017 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3018 if (!DBA::isResult($contact)) {
3019 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3023 $contact_id = $contact['id'];
3024 $result['cid'] = $contact_id;
3026 Group::addMember(User::getDefaultGroup($uid), $contact_id);
3028 // Update the avatar
3029 self::updateAvatar($contact_id, $ret['photo']);
3031 // pull feed and consume it, which should subscribe to the hub.
3032 if ($contact['network'] == Protocol::OSTATUS) {
3033 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3037 self::updateFromProbeArray($contact_id, $ret);
3039 Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
3042 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3048 * @param array $importer Owner (local user) data
3049 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3050 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3051 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3052 * @param string $note Introduction additional message
3053 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3054 * @throws HTTPException\InternalServerErrorException
3055 * @throws \ImagickException
3057 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3059 // Should always be set
3060 if (empty($datarray['author-id'])) {
3064 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3065 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3066 if (!DBA::isResult($pub_contact)) {
3067 // Should never happen
3071 // Contact is blocked at node-level
3072 if (self::isBlocked($datarray['author-id'])) {
3076 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3077 $name = $pub_contact['name'];
3078 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3079 $nick = $pub_contact['nick'];
3080 $network = $pub_contact['network'];
3082 // Ensure that we don't create a new contact when there already is one
3083 $cid = self::getIdForURL($url, $importer['uid']);
3085 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3088 self::clearFollowerFollowingEndpointCache($importer['uid']);
3090 if (!empty($contact)) {
3091 if (!empty($contact['pending'])) {
3092 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3096 // Contact is blocked at user-level
3097 if (!empty($contact['id']) && !empty($importer['id']) &&
3098 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3102 // Make sure that the existing contact isn't archived
3103 self::unmarkForArchival($contact);
3105 if (($contact['rel'] == self::SHARING)
3106 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3107 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3108 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3111 // Ensure to always have the correct network type, independent from the connection request method
3112 self::updateFromProbe($contact['id']);
3114 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3118 // send email notification to owner?
3119 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3120 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3124 // create contact record
3125 $contact_id = self::insert([
3126 'uid' => $importer['uid'],
3127 'created' => DateTimeFormat::utcNow(),
3129 'nurl' => Strings::normaliseLink($url),
3132 'network' => $network,
3133 'rel' => self::FOLLOWER,
3140 // Ensure to always have the correct network type, independent from the connection request method
3141 self::updateFromProbe($contact_id);
3143 self::updateAvatar($contact_id, $photo, true);
3145 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3147 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3149 /// @TODO Encapsulate this into a function/method
3150 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3151 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3152 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3153 // create notification
3154 if (is_array($contact_record)) {
3155 $intro = DI::introFactory()->createNew(
3157 $contact_record['id'],
3160 DI::intro()->save($intro);
3163 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3165 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3166 DI::notify()->createFromArray([
3167 'type' => Notification\Type::INTRO,
3168 'otype' => Notification\ObjectType::INTRO,
3169 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3170 'uid' => $user['uid'],
3171 'cid' => $contact_record['id'],
3172 'link' => DI::baseUrl() . '/notifications/intros',
3175 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3176 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3177 self::createFromProbeForUser($importer['uid'], $url, $network);
3180 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3181 $fields = ['pending' => false];
3182 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3183 $fields['rel'] = self::FRIEND;
3186 self::update($fields, $condition);
3196 * Update the local relationship when a local user loses a follower
3198 * @param array $contact User-specific contact (uid != 0) array
3200 * @throws HTTPException\InternalServerErrorException
3201 * @throws \ImagickException
3203 public static function removeFollower(array $contact)
3205 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3206 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3207 } elseif (!empty($contact['id'])) {
3208 self::remove($contact['id']);
3210 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3214 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3216 self::clearFollowerFollowingEndpointCache($contact['uid']);
3218 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3219 if (!empty($cdata['public'])) {
3220 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3225 * Update the local relationship when a local user unfollow a contact.
3226 * Removes the contact for sharing-only protocols (feed and mail).
3228 * @param array $contact User-specific contact (uid != 0) array
3229 * @throws HTTPException\InternalServerErrorException
3231 public static function removeSharer(array $contact)
3233 self::clearFollowerFollowingEndpointCache($contact['uid']);
3235 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3236 self::remove($contact['id']);
3238 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3241 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3245 * Create a birthday event.
3247 * Update the year and the birthday.
3249 public static function updateBirthdays()
3253 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3254 AND NOT `contact`.`pending`
3255 AND NOT `contact`.`hidden`
3256 AND NOT `contact`.`blocked`
3257 AND NOT `contact`.`archive`
3258 AND NOT `contact`.`deleted`',
3264 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3266 while ($contact = DBA::fetch($contacts)) {
3267 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3269 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3271 if (Event::createBirthday($contact, $nextbd)) {
3275 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3276 ['id' => $contact['id']]
3280 DBA::close($contacts);
3284 * Remove the unavailable contact ids from the provided list
3286 * @param array $contact_ids Contact id list
3288 * @throws \Exception
3290 public static function pruneUnavailable(array $contact_ids): array
3292 if (empty($contact_ids)) {
3296 $contacts = self::selectToArray(['id'], [
3297 'id' => $contact_ids,
3303 return array_column($contacts, 'id');
3307 * Returns a magic link to authenticate remote visitors
3309 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3311 * @param string $contact_url The address of the target contact profile
3312 * @param string $url An url that we will be redirected to after the authentication
3314 * @return string with "redir" link
3315 * @throws HTTPException\InternalServerErrorException
3316 * @throws \ImagickException
3318 public static function magicLink(string $contact_url, string $url = ''): string
3320 if (!DI::userSession()->isAuthenticated()) {
3321 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3324 $contact = self::getByURL($contact_url, false);
3325 if (empty($contact)) {
3326 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3329 // Prevents endless loop in case only a non-public contact exists for the contact URL
3330 unset($contact['uid']);
3332 return self::magicLinkByContact($contact, $url ?: $contact_url);
3336 * Returns a magic link to authenticate remote visitors
3338 * @param integer $cid The contact id of the target contact profile
3339 * @param string $url An url that we will be redirected to after the authentication
3341 * @return string with "redir" link
3342 * @throws HTTPException\InternalServerErrorException
3343 * @throws \ImagickException
3345 public static function magicLinkById(int $cid, string $url = ''): string
3347 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3349 return self::magicLinkByContact($contact, $url);
3353 * Returns a magic link to authenticate remote visitors
3355 * @param array $contact The contact array with "uid", "network" and "url"
3356 * @param string $url An url that we will be redirected to after the authentication
3358 * @return string with "redir" link
3359 * @throws HTTPException\InternalServerErrorException
3360 * @throws \ImagickException
3362 public static function magicLinkByContact(array $contact, string $url = ''): string
3364 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3366 if (!DI::userSession()->isAuthenticated()) {
3367 return $destination;
3370 // Only redirections to the same host do make sense
3371 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3375 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3376 return 'contact/' . $contact['id'] . '/conversations';
3379 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3380 return $destination;
3383 if (empty($contact['id'])) {
3384 return $destination;
3387 $redirect = 'contact/redir/' . $contact['id'];
3389 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3390 $redirect .= '?url=' . $url;
3397 * Is the contact a forum?
3399 * @param integer $contactid ID of the contact
3401 * @return boolean "true" if it is a forum
3403 public static function isForum(int $contactid): bool
3405 $fields = ['contact-type'];
3406 $condition = ['id' => $contactid];
3407 $contact = DBA::selectFirst('contact', $fields, $condition);
3408 if (!DBA::isResult($contact)) {
3413 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3417 * Can the remote contact receive private messages?
3419 * @param array $contact
3422 public static function canReceivePrivateMessages(array $contact): bool
3424 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3425 $self = $contact['self'] ?? false;
3427 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3431 * Search contact table by nick or name
3433 * @param string $search Name or nick
3434 * @param string $mode Search mode (e.g. "community")
3435 * @param int $uid User ID
3436 * @param int $limit Maximum amount of returned values
3437 * @param int $offset Limit offset
3439 * @return array with search results
3440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3442 public static function searchByName(string $search, string $mode = '', int $uid = 0, int $limit = 0, int $offset = 0): array
3444 if (empty($search)) {
3448 // check supported networks
3449 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3450 if (DI::config()->get('system', 'diaspora_enabled')) {
3451 $networks[] = Protocol::DIASPORA;
3454 if (!DI::config()->get('system', 'ostatus_disabled')) {
3455 $networks[] = Protocol::OSTATUS;
3458 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3461 $condition['blocked'] = false;
3463 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3466 // check if we search only communities or every contact
3467 if ($mode === 'community') {
3468 $condition['contact-type'] = self::TYPE_COMMUNITY;
3475 if (!empty($limit) && !empty($offset)) {
3476 $params['limit'] = [$offset, $limit];
3477 } elseif (!empty($limit)) {
3478 $params['limit'] = $limit;
3481 $condition = DBA::mergeConditions($condition,
3482 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3483 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3485 return self::selectToArray([], $condition, $params);
3489 * Add public contacts from an array
3491 * @param array $urls
3492 * @return array result "count", "added" and "updated"
3494 public static function addByUrls(array $urls): array
3501 foreach ($urls as $url) {
3502 if (empty($url) || !is_string($url)) {
3505 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3506 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3507 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3509 } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3510 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3518 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3522 * Returns a random, global contact array of the current node
3524 * @return array The profile array
3527 public static function getRandomContact(): array
3529 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3530 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3531 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3532 ], ['order' => ['RAND()']]);
3534 if (DBA::isResult($contact)) {
3542 * Checks, if contacts with the given condition exists
3544 * @param array $condition
3547 * @throws \Exception
3549 public static function exists(array $condition): bool
3551 return DBA::exists('contact', $condition);