3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Contact\Avatar;
25 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Content\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;
50 use Friendica\Worker\UpdateContact;
53 * functions for interacting with a contact
57 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
58 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
59 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
65 const LOCK_INSERT = 'contact-insert';
70 * TYPE_UNKNOWN - unknown type
72 * TYPE_PERSON - the account belongs to a person
73 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
75 * TYPE_ORGANISATION - the account belongs to an organisation
76 * Associated page type: PAGE_SOAPBOX
78 * TYPE_NEWS - the account is a news reflector
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_COMMUNITY - the account is community forum
82 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
84 * TYPE_RELAY - the account is a relay
85 * This will only be assigned to contacts, not to user accounts
88 const TYPE_UNKNOWN = -1;
89 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
90 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
91 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
92 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
93 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
104 const NOTHING = 0; // There is no relationship between the contact and the user
105 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
106 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
107 const FRIEND = 3; // There is a mutual relationship between the contact and the user
108 const SELF = 4; // This is the user theirself
113 const MIRROR_DEACTIVATED = 0;
114 const MIRROR_FORWARDED = 1; // Deprecated, now does the same like MIRROR_OWN_POST
115 const MIRROR_OWN_POST = 2;
116 const MIRROR_NATIVE_RESHARE = 3;
119 * @param array $fields Array of selected fields, empty for all
120 * @param array $condition Array of fields for condition
121 * @param array $params Array of several parameters
125 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
127 return DBA::selectToArray('contact', $fields, $condition, $params);
131 * @param array $fields Array of selected fields, empty for all
132 * @param array $condition Array of fields for condition
133 * @param array $params Array of several parameters
137 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
139 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
145 * @param array $fields Array of selected fields, empty for all
146 * @param array $condition Array of fields for condition
147 * @param array $params Array of several parameters
151 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
153 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
157 * @param array $fields Array of selected fields, empty for all
158 * @param array $condition Array of fields for condition
159 * @param array $params Array of several parameters
163 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
165 return DBA::selectFirst('account-view', $fields, $condition, $params);
169 * Insert a row into the contact table
170 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
172 * @param array $fields field array
173 * @param int $duplicate_mode Do an update on a duplicate entry
175 * @return int id of the created contact
178 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
180 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
181 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
184 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
186 if (empty($fields['created'])) {
187 $fields['created'] = DateTimeFormat::utcNow();
190 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
191 DBA::insert('contact', $fields, $duplicate_mode);
192 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
193 if (!DBA::isResult($contact)) {
195 Logger::warning('Created contact could not be found', ['fields' => $fields]);
199 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
200 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
201 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
202 if (empty($account_user['id'])) {
203 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
204 } elseif ($account_user['id'] != $contact['id']) {
205 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
206 if (!empty($duplicate['id'])) {
207 $ret = Contact::deleteById($contact['id']);
208 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']]);
209 $contact = $duplicate;
211 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
212 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']]);
216 Contact\User::insertForContactArray($contact);
218 return $contact['id'];
222 * Delete contact by id
227 public static function deleteById(int $id): bool
229 Logger::debug('Delete contact', ['id' => $id]);
230 DBA::delete('account-user', ['id' => $id]);
231 return DBA::delete('contact', ['id' => $id]);
235 * Updates rows in the contact table
237 * @param array $fields contains the fields that are updated
238 * @param array $condition condition array with the key values
239 * @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)
241 * @return boolean was the update successfull?
243 * @todo Let's get rid of boolean type of $old_fields
245 public static function update(array $fields, array $condition, $old_fields = [])
247 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
248 $ret = DBA::update('contact', $fields, $condition, $old_fields);
250 // Apply changes to the "user-contact" table on dedicated fields
251 Contact\User::updateByContactUpdate($fields, $condition);
257 * @param integer $id Contact ID
258 * @param array $fields Array of selected fields, empty for all
259 * @return array|boolean Contact record if it exists, false otherwise
262 public static function getById(int $id, array $fields = [])
264 return DBA::selectFirst('contact', $fields, ['id' => $id]);
268 * Fetch the first contact with the provided uri-id.
270 * @param integer $uri_id uri-id of the contact
271 * @param array $fields Array of selected fields, empty for all
272 * @return array|boolean Contact record if it exists, false otherwise
275 public static function getByUriId(int $uri_id, array $fields = [])
277 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
281 * Fetch all remote contacts for a given contact url
283 * @param string $url The URL of the contact
284 * @param array $fields The wanted fields
286 * @return array all remote contacts
290 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
294 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
295 while ($contact = DBA::fetch($remote_contacts)) {
296 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
299 $remote[$contact['uid']] = $contact['id'];
301 DBA::close($remote_contacts);
307 * Fetches a contact by a given url
309 * @param string $url profile url
310 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
311 * @param array $fields Field list
312 * @param integer $uid User ID of the contact
313 * @return array contact array
315 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
317 if ($update || is_null($update)) {
318 $cid = self::getIdForURL($url, $uid, $update);
323 $contact = self::getById($cid, $fields);
324 if (empty($contact)) {
330 // Add internal fields
332 if (!empty($fields)) {
333 foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
334 if (!in_array($internal, $fields)) {
335 $fields[] = $internal;
336 $removal[] = $internal;
341 // We first try the nurl (http://server.tld/nick), most common case
342 $options = ['order' => ['id']];
343 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
345 // Then the addr (nick@server.tld)
346 if (!DBA::isResult($contact)) {
347 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
350 // Then the alias (which could be anything)
351 if (!DBA::isResult($contact)) {
352 // The link could be provided as http although we stored it as https
353 $ssl_url = str_replace('http://', 'https://', $url);
354 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
355 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
358 if (!DBA::isResult($contact)) {
362 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
364 // Update the contact in the background if needed
365 if ($background_update && !self::isLocal($url) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
367 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
368 } catch (\InvalidArgumentException $e) {
369 Logger::notice($e->getMessage(), ['contact' => $contact]);
373 // Remove the internal fields
374 foreach ($removal as $internal) {
375 unset($contact[$internal]);
382 * Fetches a contact for a given user by a given url.
383 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
385 * @param string $url profile url
386 * @param integer $uid User ID of the contact
387 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
388 * @param array $fields Field list
389 * @return array contact array
391 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
394 $contact = self::getByURL($url, $update, $fields, $uid);
395 if (!empty($contact)) {
396 if (!empty($contact['id'])) {
397 $contact['cid'] = $contact['id'];
404 $contact = self::getByURL($url, $update, $fields);
405 if (!empty($contact['id'])) {
407 $contact['zid'] = $contact['id'];
413 * Checks if a contact uses a specific platform
416 * @param string $platform
419 public static function isPlatform(string $url, string $platform): bool
421 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
425 * Tests if the given contact is a follower
427 * @param int $cid Either public contact id or user's contact id
428 * @param int $uid User ID
429 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
431 * @return boolean is the contact id a follower?
432 * @throws HTTPException\InternalServerErrorException
433 * @throws \ImagickException
435 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
437 if (Contact\User::isBlocked($cid, $uid)) {
441 $cdata = self::getPublicAndUserContactID($cid, $uid);
442 if (empty($cdata['user'])) {
446 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
448 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
450 return DBA::exists('contact', $condition);
454 * Tests if the given contact url is a follower
456 * @param string $url Contact URL
457 * @param int $uid User ID
458 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
460 * @return boolean is the contact id a follower?
461 * @throws HTTPException\InternalServerErrorException
462 * @throws \ImagickException
464 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
466 $cid = self::getIdForURL($url, $uid);
472 return self::isFollower($cid, $uid, $strict);
476 * Tests if the given user shares with the given contact
478 * @param int $cid Either public contact id or user's contact id
479 * @param int $uid User ID
480 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
482 * @return boolean is the contact sharing with given user?
483 * @throws HTTPException\InternalServerErrorException
484 * @throws \ImagickException
486 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
488 if (Contact\User::isBlocked($cid, $uid)) {
492 $cdata = self::getPublicAndUserContactID($cid, $uid);
493 if (empty($cdata['user'])) {
497 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
499 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
501 return DBA::exists('contact', $condition);
505 * Tests if the given user follow the given contact url
507 * @param string $url Contact URL
508 * @param int $uid User ID
509 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
511 * @return boolean is the contact url being followed?
512 * @throws HTTPException\InternalServerErrorException
513 * @throws \ImagickException
515 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
517 $cid = self::getIdForURL($url, $uid);
523 return self::isSharing($cid, $uid, $strict);
527 * Get the basepath for a given contact link
529 * @param string $url The contact link
530 * @param boolean $dont_update Don't update the contact
532 * @return string basepath
533 * @throws HTTPException\InternalServerErrorException
534 * @throws \ImagickException
536 public static function getBasepath(string $url, bool $dont_update = false): string
538 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
539 if (!DBA::isResult($contact)) {
543 if (!empty($contact['baseurl'])) {
544 return $contact['baseurl'];
545 } elseif ($dont_update) {
549 // Update the existing contact
550 self::updateFromProbe($contact['id']);
552 // And fetch the result
553 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
554 if (empty($contact['baseurl'])) {
555 Logger::info('No baseurl for contact', ['url' => $url]);
559 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
560 return $contact['baseurl'];
564 * Check if the given contact url is on the same server
566 * @param string $url The contact link
568 * @return boolean Is it the same server?
570 public static function isLocal(string $url): bool
572 if (!parse_url($url, PHP_URL_SCHEME)) {
573 $addr_parts = explode('@', $url);
574 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
577 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
581 * Check if the given contact ID is on the same server
583 * @param string $url The contact link
584 * @return boolean Is it the same server?
586 public static function isLocalById(int $cid): bool
588 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
589 if (!DBA::isResult($contact)) {
593 if (empty($contact['baseurl'])) {
594 $baseurl = self::getBasepath($contact['url'], true);
596 $baseurl = $contact['baseurl'];
599 return Strings::compareLink($baseurl, DI::baseUrl());
603 * Returns the public contact id of the given user id
605 * @param integer $uid User ID
607 * @return integer|boolean Public contact id for given user id
610 public static function getPublicIdByUserId(int $uid)
612 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
613 if (!DBA::isResult($self)) {
616 return self::getIdForURL($self['url']);
620 * Returns the contact id for the user and the public contact id for a given contact id
622 * @param int $cid Either public contact id or user's contact id
623 * @param int $uid User ID
625 * @return array with public and user's contact id
626 * @throws HTTPException\InternalServerErrorException
627 * @throws \ImagickException
629 public static function getPublicAndUserContactID(int $cid, int $uid): array
631 // We have to use the legacy function as long as the post update hasn't finished
632 if (DI::keyValue()->get('post_update_version') < 1427) {
633 return self::legacyGetPublicAndUserContactID($cid, $uid);
636 if (empty($uid) || empty($cid)) {
640 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
641 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
645 $pcid = $contact['pid'];
646 if ($contact['uid'] == $uid) {
647 $ucid = $contact['id'];
649 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
650 if (DBA::isResult($contact)) {
651 $ucid = $contact['id'];
657 return ['public' => $pcid, 'user' => $ucid];
661 * Helper function for "getPublicAndUserContactID"
663 * @param int $cid Either public contact id or user's contact id
664 * @param int $uid User ID
665 * @return array with public and user's contact id
666 * @throws HTTPException\InternalServerErrorException
667 * @throws \ImagickException
669 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
671 if (empty($uid) || empty($cid)) {
675 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
676 if (!DBA::isResult($contact)) {
680 // We quit when the user id don't match the user id of the provided contact
681 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
685 if ($contact['uid'] != 0) {
686 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
690 $ucid = $contact['id'];
692 $pcid = $contact['id'];
693 $ucid = self::getIdForURL($contact['url'], $uid);
696 return ['public' => $pcid, 'user' => $ucid];
700 * Returns contact details for a given contact id in combination with a user id
702 * @param int $cid A contact ID
703 * @param int $uid The User ID
704 * @param array $fields The selected fields for the contact
705 * @return array The contact details
709 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
711 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
713 if (!DBA::isResult($contact)) {
721 * Creates the self-contact for the provided user id
724 * @return bool Operation success
725 * @throws HTTPException\InternalServerErrorException
727 public static function createSelfFromUserId(int $uid): bool
729 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
730 ['uid' => $uid, 'account_expired' => false]);
731 if (!DBA::isResult($user)) {
736 'uid' => $user['uid'],
737 'created' => DateTimeFormat::utcNow(),
739 'name' => $user['username'],
740 'nick' => $user['nickname'],
741 'pubkey' => $user['pubkey'],
742 'prvkey' => $user['prvkey'],
743 'photo' => User::getAvatarUrl($user),
744 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
745 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
748 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
749 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
750 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
751 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
752 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
753 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
754 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
755 'name-date' => DateTimeFormat::utcNow(),
756 'uri-date' => DateTimeFormat::utcNow(),
757 'avatar-date' => DateTimeFormat::utcNow(),
763 // Only create the entry if it doesn't exist yet
764 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
765 $return = (bool)self::insert($contact);
768 // Create the public contact
769 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
770 $contact['self'] = false;
772 $contact['prvkey'] = null;
774 self::insert($contact, Database::INSERT_IGNORE);
781 * Updates the self-contact for the provided user id
784 * @param bool $update_avatar Force the avatar update
785 * @return bool "true" if updated
786 * @throws HTTPException\InternalServerErrorException
788 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
790 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
791 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
792 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
793 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
794 if (!DBA::isResult($self)) {
798 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
799 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
800 if (!DBA::isResult($user)) {
804 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
805 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
806 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
807 if (!DBA::isResult($profile)) {
811 $file_suffix = 'jpg';
812 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
815 'name' => $profile['name'],
816 'nick' => $user['nickname'],
817 'avatar-date' => $self['avatar-date'],
818 'location' => Profile::formatLocation($profile),
819 'about' => $profile['about'],
820 'keywords' => $profile['pub_keywords'],
821 'contact-type' => $user['account-type'],
822 'prvkey' => $user['prvkey'],
823 'pubkey' => $user['pubkey'],
824 'xmpp' => $profile['xmpp'],
825 'matrix' => $profile['matrix'],
826 'network' => Protocol::DFRN,
828 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
829 'nurl' => Strings::normaliseLink($url),
830 'uri-id' => ItemURI::getIdByURI($url),
831 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
832 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
833 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
834 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
835 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
839 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
840 if (DBA::isResult($avatar)) {
841 if ($update_avatar) {
842 $fields['avatar-date'] = DateTimeFormat::utcNow();
845 // Creating the path to the avatar, beginning with the file suffix
846 $types = Images::supportedTypes();
847 if (isset($types[$avatar['type']])) {
848 $file_suffix = $types[$avatar['type']];
851 // We are adding a timestamp value so that other systems won't use cached content
852 $timestamp = strtotime($fields['avatar-date']);
854 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
855 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
857 $fields['photo'] = $prefix . '4' . $suffix;
858 $fields['thumb'] = $prefix . '5' . $suffix;
859 $fields['micro'] = $prefix . '6' . $suffix;
861 // We hadn't found a photo entry, so we use the default avatar
862 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
863 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
864 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
867 $fields['avatar'] = User::getAvatarUrl($user);
868 $fields['header'] = User::getBannerUrl($user);
869 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
870 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
871 $fields['unsearchable'] = !$profile['net-publish'];
872 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
876 foreach ($fields as $field => $content) {
877 if ($self[$field] != $content) {
883 if ($fields['name'] != $self['name']) {
884 $fields['name-date'] = DateTimeFormat::utcNow();
886 $fields['updated'] = DateTimeFormat::utcNow();
887 self::update($fields, ['id' => $self['id']]);
889 // Update the other contacts as well
890 unset($fields['prvkey']);
891 $fields['self'] = false;
892 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
894 // Update the profile
896 'photo' => User::getAvatarUrl($user),
897 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
900 DBA::update('profile', $fields, ['uid' => $uid]);
907 * Marks a contact for removal
909 * @param int $id contact id
911 * @throws HTTPException\InternalServerErrorException
913 public static function remove(int $id)
915 // We want just to make sure that we don't delete our "self" contact
916 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
917 if (!DBA::isResult($contact)) {
921 DBA::delete('account-user', ['id' => $id]);
923 self::clearFollowerFollowingEndpointCache($contact['uid']);
925 // Archive the contact
926 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
928 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
929 Avatar::deleteCache($contact);
932 // Delete it in the background
933 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
937 * Unfollow the remote contact
939 * @param array $contact Target user-specific contact (uid != 0) array
941 * @throws HTTPException\InternalServerErrorException
942 * @throws \ImagickException
944 public static function unfollow(array $contact): void
946 if (empty($contact['network'])) {
947 throw new \InvalidArgumentException('Empty network in contact array');
950 if (empty($contact['uid'])) {
951 throw new \InvalidArgumentException('Unexpected public contact record');
954 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
955 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
956 if (!empty($cdata['public'])) {
957 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
961 self::removeSharer($contact);
965 * Revoke follow privileges of the remote user contact
967 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
969 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
971 * @throws HTTPException\InternalServerErrorException
972 * @throws \ImagickException
974 public static function revokeFollow(array $contact): void
976 if (empty($contact['network'])) {
977 throw new \InvalidArgumentException('Empty network in contact array');
980 if (empty($contact['uid'])) {
981 throw new \InvalidArgumentException('Unexpected public contact record');
984 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
985 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
986 if (!empty($cdata['public'])) {
987 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
991 self::removeFollower($contact);
995 * Completely severs a relationship with a contact
997 * @param array $contact User-specific contact (uid != 0) array
999 * @throws HTTPException\InternalServerErrorException
1000 * @throws \ImagickException
1002 public static function terminateFriendship(array $contact)
1004 if (empty($contact['network'])) {
1005 throw new \InvalidArgumentException('Empty network in contact array');
1008 if (empty($contact['uid'])) {
1009 throw new \InvalidArgumentException('Unexpected public contact record');
1012 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1014 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1015 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1018 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1019 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1022 self::remove($contact['id']);
1025 private static function clearFollowerFollowingEndpointCache(int $uid)
1031 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1032 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1036 * Marks a contact for archival after a communication issue delay
1038 * Contact has refused to recognise us as a friend. We will start a countdown.
1039 * If they still don't recognise us in 32 days, the relationship is over,
1040 * and we won't waste any more time trying to communicate with them.
1041 * This provides for the possibility that their database is temporarily messed
1042 * up or some other transient event and that there's a possibility we could recover from it.
1044 * @param array $contact contact to mark for archival
1046 * @throws HTTPException\InternalServerErrorException
1048 public static function markForArchival(array $contact)
1050 if (!isset($contact['url']) && !empty($contact['id'])) {
1051 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1052 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1053 if (!DBA::isResult($contact)) {
1056 } elseif (!isset($contact['url'])) {
1057 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1060 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1062 // Contact already archived or "self" contact? => nothing to do
1063 if ($contact['archive'] || $contact['self']) {
1067 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1068 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1069 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1072 * We really should send a notification to the owner after 2-3 weeks
1073 * so they won't be surprised when the contact vanishes and can take
1074 * remedial action if this was a serious mistake or glitch
1077 /// @todo Check for contact vitality via probing
1078 $archival_days = DI::config()->get('system', 'archival_days', 32);
1080 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1081 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1082 /* Relationship is really truly dead. archive them rather than
1083 * delete, though if the owner tries to unarchive them we'll start
1084 * the whole process over again.
1086 self::update(['archive' => true], ['id' => $contact['id']]);
1087 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1093 * Cancels the archival countdown
1095 * @see Contact::markForArchival()
1097 * @param array $contact contact to be unmarked for archival
1099 * @throws \Exception
1101 public static function unmarkForArchival(array $contact)
1103 // Always unarchive the relay contact entry
1104 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1105 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1106 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1107 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1108 self::update($fields, $condition);
1112 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1113 $exists = DBA::exists('contact', $condition);
1115 // We don't need to update, we never marked this contact for archival
1120 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1122 if (!isset($contact['url']) && !empty($contact['id'])) {
1123 $fields = ['id', 'url', 'batch'];
1124 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1125 if (!DBA::isResult($contact)) {
1130 // It's a miracle. Our dead contact has inexplicably come back to life.
1131 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1132 self::update($fields, ['id' => $contact['id']]);
1133 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1137 * Returns the data array for the photo menu of a given contact
1139 * @param array $contact contact
1140 * @param int $uid Visitor user id
1142 * @throws HTTPException\InternalServerErrorException
1143 * @throws \ImagickException
1145 public static function photoMenu(array $contact, int $uid): array
1147 // Anonymous visitor
1149 return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
1157 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1159 $profile_link = 'contact/redir/' . $contact['id'];
1161 $profile_link = $contact['url'];
1164 if ($profile_link === 'mailbox') {
1169 $status_link = $profile_link . '/status';
1170 $photos_link = $profile_link . '/photos';
1171 $profile_link = $profile_link . '/profile';
1174 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1175 $pm_url = 'message/new/' . $contact['id'];
1178 $contact_url = 'contact/' . $contact['id'];
1179 $posts_link = 'contact/' . $contact['id'] . '/conversations';
1182 $unfollow_link = '';
1183 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1184 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1185 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1186 } elseif (!$contact['pending']) {
1187 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1193 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1195 if (empty($contact['uid'])) {
1197 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1198 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1199 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1200 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1201 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1205 'status' => [DI::l10n()->t('View Status') , $status_link , true ],
1206 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true ],
1207 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true ],
1208 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1209 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1210 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1211 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true ],
1212 'unfollow' => [DI::l10n()->t('Unfollow') , $unfollow_link, true ],
1215 if (!empty($contact['pending'])) {
1217 $intro = DI::intro()->selectForContact($contact['id']);
1218 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1219 } catch (IntroductionNotFoundException $exception) {
1220 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1225 $args = ['contact' => $contact, 'menu' => &$menu];
1227 Hook::callAll('contact_photo_menu', $args);
1229 $menucondensed = [];
1231 foreach ($menu as $menuname => $menuitem) {
1232 if ($menuitem[1] != '') {
1233 $menucondensed[$menuname] = $menuitem;
1237 return $menucondensed;
1241 * Fetch the contact id for a given URL and user
1243 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1244 * `addr` or `alias`.
1246 * If there's no record and we aren't looking for a public contact, we quit.
1247 * If there's one, we check that it isn't time to update the picture else we
1248 * directly return the found contact id.
1250 * Second, we probe the provided $url whether it's http://server.tld/profile or
1251 * nick@server.tld. We quit if we can't get any info back.
1253 * Third, we create the contact record if it doesn't exist
1255 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1256 * if there's any updates
1258 * @param string $url Contact URL
1259 * @param integer $uid The user id for the contact (0 = public contact)
1260 * @param boolean $update true = always update, false = never update, null = update when not found
1261 * @param array $default Default value for creating the contact when everything else fails
1263 * @return integer Contact ID
1264 * @throws HTTPException\InternalServerErrorException
1265 * @throws \ImagickException
1267 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1272 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1276 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
1278 if (!empty($contact)) {
1279 $contact_id = $contact['id'];
1281 $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
1283 if ($background_update && !self::isLocal($url) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1285 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
1286 } catch (\InvalidArgumentException $e) {
1287 Logger::notice($e->getMessage(), ['contact' => $contact]);
1291 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1292 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1295 } elseif ($uid != 0) {
1296 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1298 } elseif (empty($default) && !is_null($update) && !$update) {
1299 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1305 if (empty($default['network']) || $update) {
1306 $data = Probe::uri($url, '', $uid);
1308 // Take the default values when probing failed
1309 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1310 $data = array_merge($data, $default);
1312 } elseif (!empty($default['network'])) {
1316 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1317 // Fetch data for the public contact via the first found personal contact
1318 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1319 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1320 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1321 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1323 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1324 if (!DBA::isResult($personal_contact)) {
1325 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1328 if (DBA::isResult($personal_contact)) {
1329 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1330 $data = $personal_contact;
1331 $data['photo'] = $personal_contact['avatar'];
1332 $data['account-type'] = $personal_contact['contact-type'];
1333 $data['hide'] = $personal_contact['unsearchable'];
1334 unset($data['avatar']);
1335 unset($data['contact-type']);
1336 unset($data['unsearchable']);
1340 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1341 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1345 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1346 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1351 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1352 if (!empty($data['alias'])) {
1353 $urls[] = Strings::normaliseLink($data['alias']);
1355 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1356 if (!empty($contact['id'])) {
1357 $contact_id = $contact['id'];
1358 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1363 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1366 'url' => $data['url'],
1367 'nurl' => Strings::normaliseLink($data['url']),
1368 'network' => $data['network'],
1369 'created' => DateTimeFormat::utcNow(),
1370 'rel' => self::SHARING,
1377 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1379 // Before inserting we do check if the entry does exist now.
1380 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1381 if (DBA::isResult($contact)) {
1382 $contact_id = $contact['id'];
1383 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1385 $contact_id = self::insert($fields);
1387 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1392 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1396 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1399 if ($data['network'] == Protocol::DIASPORA) {
1401 DI::dsprContact()->updateFromProbeArray($data);
1402 } catch (HTTPException\NotFoundException $e) {
1403 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1404 } catch (\InvalidArgumentException $e) {
1405 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
1407 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
1409 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
1410 } catch (HTTPException\NotFoundException $e) {
1411 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1412 } catch (\InvalidArgumentException $e) {
1413 Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
1417 self::updateFromProbeArray($contact_id, $data);
1419 // Don't return a number for a deleted account
1420 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1421 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1429 * Checks if the contact is archived
1431 * @param int $cid contact id
1433 * @return boolean Is the contact archived?
1434 * @throws HTTPException\InternalServerErrorException
1436 public static function isArchived(int $cid): bool
1442 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1443 if (!DBA::isResult($contact)) {
1447 if ($contact['archive']) {
1451 // Check status of ActivityPub endpoints
1452 $apcontact = APContact::getByURL($contact['url'], false);
1453 if (!empty($apcontact)) {
1454 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1458 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1463 // Check status of Diaspora endpoints
1464 if (!empty($contact['batch'])) {
1465 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1466 return DBA::exists('contact', $condition);
1473 * Checks if the contact is blocked
1475 * @param int $cid contact id
1476 * @return boolean Is the contact blocked?
1477 * @throws HTTPException\InternalServerErrorException
1479 public static function isBlocked(int $cid): bool
1485 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1486 if (!DBA::isResult($blocked)) {
1490 if (Network::isUrlBlocked($blocked['url'])) {
1494 return (bool) $blocked['blocked'];
1498 * Checks if the contact is hidden
1500 * @param int $cid contact id
1501 * @return boolean Is the contact hidden?
1502 * @throws \Exception
1504 public static function isHidden(int $cid): bool
1510 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1511 if (!DBA::isResult($hidden)) {
1514 return (bool) $hidden['hidden'];
1518 * Returns posts from a given contact url
1520 * @param string $contact_url Contact URL
1521 * @param bool $thread_mode
1522 * @param int $update Update mode
1523 * @param int $parent Item parent ID for the update mode
1524 * @param bool $only_media Only display media content
1525 * @return string posts in HTML
1526 * @throws \Exception
1528 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1530 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1534 * Returns posts from a given contact id
1536 * @param int $cid Contact ID
1537 * @param bool $thread_mode
1538 * @param int $update Update mode
1539 * @param int $parent Item parent ID for the update mode
1540 * @param bool $only_media Only display media content
1541 * @return string posts in HTML
1542 * @throws \Exception
1544 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1546 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1547 if (!DBA::isResult($contact)) {
1551 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1552 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1557 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1560 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1561 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()];
1563 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1564 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1567 if (!empty($parent)) {
1568 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1570 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1571 if (!empty($last_received)) {
1572 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1577 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1578 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1581 if (DI::mode()->isMobile()) {
1582 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1583 DI::config()->get('system', 'itemspage_network_mobile'));
1585 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1586 DI::config()->get('system', 'itemspage_network'));
1589 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1591 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1593 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1594 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1595 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1601 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
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 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1608 $items = array_merge($items, $pinned);
1612 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1614 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1615 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1617 if ($pager->getStart() == 0) {
1618 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1619 if (!empty($cdata['public'])) {
1620 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1621 $cdata['public'], Post\Collection::FEATURED];
1622 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1623 $items = array_merge($pinned, $items);
1627 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1631 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1632 $o .= HTML::scrollLoader();
1634 $o .= $pager->renderMinimal(count($items));
1642 * Returns the account type name
1644 * The function can be called with either the user or the contact array
1646 * @param int $type type of contact or account
1649 public static function getAccountType(int $type): string
1652 case self::TYPE_ORGANISATION:
1653 $account_type = DI::l10n()->t("Organisation");
1656 case self::TYPE_NEWS:
1657 $account_type = DI::l10n()->t('News');
1660 case self::TYPE_COMMUNITY:
1661 $account_type = DI::l10n()->t("Forum");
1669 return $account_type;
1675 * @param int $cid Contact id to block
1676 * @param string $reason Block reason
1677 * @return bool Whether it was successful
1679 public static function block(int $cid, string $reason = null): bool
1681 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1687 * Unblocks a contact
1689 * @param int $cid Contact id to unblock
1690 * @return bool Whether it was successfull
1692 public static function unblock(int $cid): bool
1694 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1700 * Ensure that cached avatar exist
1702 * @param integer $cid Contact id
1704 public static function checkAvatarCache(int $cid)
1706 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1707 if (!DBA::isResult($contact)) {
1711 if (Network::isLocalLink($contact['url'])) {
1715 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1716 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1717 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1718 self::updateAvatar($cid, $contact['avatar'], true);
1721 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1722 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1723 self::updateAvatar($cid, $contact['avatar'], true);
1725 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1726 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1727 self::updateAvatar($cid, $contact['avatar'], true);
1733 * Return the photo path for a given contact array in the given size
1735 * @param array $contact contact array
1736 * @param string $size Size of the avatar picture
1737 * @param bool $no_update Don't perfom an update if no cached avatar was found
1738 * @return string photo path
1740 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1742 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1744 if (DI::config()->get('system', 'avatar_cache')) {
1746 case Proxy::SIZE_MICRO:
1747 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1748 return $contact['micro'];
1751 case Proxy::SIZE_THUMB:
1752 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1753 return $contact['thumb'];
1756 case Proxy::SIZE_SMALL:
1757 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1758 return $contact['photo'];
1764 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1768 * Return the photo path for a given contact array
1770 * @param array $contact Contact array
1771 * @param bool $no_update Don't perfom an update if no cached avatar was found
1772 * @return string photo path
1774 public static function getPhoto(array $contact, bool $no_update = false): string
1776 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1780 * Return the photo path (thumb size) for a given contact array
1782 * @param array $contact Contact array
1783 * @param bool $no_update Don't perfom an update if no cached avatar was found
1784 * @return string photo path
1786 public static function getThumb(array $contact, bool $no_update = false): string
1788 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1792 * Return the photo path (micro size) for a given contact array
1794 * @param array $contact Contact array
1795 * @param bool $no_update Don't perfom an update if no cached avatar was found
1796 * @return string photo path
1798 public static function getMicro(array $contact, bool $no_update = false): string
1800 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1804 * Check the given contact array for avatar cache fields
1806 * @param array $contact
1807 * @param bool $no_update Don't perfom an update if no cached avatar was found
1808 * @return array contact array with avatar cache fields
1810 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1813 $contact_fields = [];
1814 $fields = ['photo', 'thumb', 'micro'];
1815 foreach ($fields as $field) {
1816 if (isset($contact[$field])) {
1817 $contact_fields[] = $field;
1819 if (isset($contact[$field]) && empty($contact[$field])) {
1824 if (!$update || $no_update) {
1828 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1830 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1831 self::updateAvatar($contact['id'], $contact['avatar'], true);
1833 $new_contact = self::getById($contact['id'], $contact_fields);
1834 if (DBA::isResult($new_contact)) {
1835 // We only update the cache fields
1836 $contact = array_merge($contact, $new_contact);
1838 } elseif ($local && !empty($contact['avatar'])) {
1842 /// add the default avatars if the fields aren't filled
1843 if (isset($contact['photo']) && empty($contact['photo'])) {
1844 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1846 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1847 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1849 if (isset($contact['micro']) && empty($contact['micro'])) {
1850 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1857 * Fetch the default header for the given contact
1859 * @param array $contact contact array
1860 * @return string avatar URL
1862 public static function getDefaultHeader(array $contact): string
1864 if (!empty($contact['header'])) {
1865 return $contact['header'];
1868 if (!empty($contact['gsid'])) {
1869 // Use default banners for certain platforms
1870 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1871 $platform = strtolower($gserver['platform'] ?? '');
1876 switch ($platform) {
1881 * @author Lostinlight <https://mastodon.xyz/@lightone>
1882 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1883 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1885 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1890 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1891 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1892 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1894 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1898 * Use a random picture.
1899 * The service provides random pictures from Unsplash.
1900 * @license https://unsplash.com/license
1902 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1910 * Fetch the default avatar for the given contact and size
1912 * @param array $contact contact array
1913 * @param string $size Size of the avatar picture
1914 * @return string avatar URL
1916 public static function getDefaultAvatar(array $contact, string $size): string
1919 case Proxy::SIZE_MICRO:
1920 $avatar['size'] = 48;
1921 $default = self::DEFAULT_AVATAR_MICRO;
1924 case Proxy::SIZE_THUMB:
1925 $avatar['size'] = 80;
1926 $default = self::DEFAULT_AVATAR_THUMB;
1929 case Proxy::SIZE_SMALL:
1931 $avatar['size'] = 300;
1932 $default = self::DEFAULT_AVATAR_PHOTO;
1936 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1938 $type = Contact::TYPE_PERSON;
1940 if (!empty($contact['id'])) {
1941 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1942 $platform = $account['platform'] ?? '';
1943 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1946 if (empty($platform) && !empty($contact['uri-id'])) {
1947 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1948 $platform = $account['platform'] ?? '';
1949 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1952 switch ($platform) {
1956 * @license GNU Affero General Public License v3.0
1957 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1959 $default = '/images/default/corgidon.png';
1965 * @license GNU Affero General Public License v3.0
1966 * @link https://github.com/diaspora/diaspora/
1968 $default = '/images/default/diaspora.png';
1974 * @license GNU Affero General Public License v3.0
1975 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1977 $default = '/images/default/gotosocial.svg';
1983 * @license GNU Affero General Public License v3.0
1984 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1986 $default = '/images/default/hometown.png';
1992 * @license GNU Affero General Public License v3.0
1993 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1995 $default = '/images/default/koyuspace.png';
2003 * @license GNU Affero General Public License v3.0
2004 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2006 $default = '/images/default/mastodon.png';
2010 if ($type == Contact::TYPE_COMMUNITY) {
2013 * @license GNU Affero General Public License v3.0
2014 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2016 $default = '/images/default/peertube-channel.png';
2020 * @license GNU Affero General Public License v3.0
2021 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2023 $default = '/images/default/peertube-account.png';
2030 * @license GNU Affero General Public License v3.0
2031 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2033 $default = '/images/default/pleroma.png';
2039 * @license GNU Affero General Public License v3.0
2040 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2042 $default = '/images/default/plume.png';
2045 return DI::baseUrl() . $default;
2048 if (!empty($contact['xmpp'])) {
2049 $avatar['email'] = $contact['xmpp'];
2050 } elseif (!empty($contact['addr'])) {
2051 $avatar['email'] = $contact['addr'];
2052 } elseif (!empty($contact['url'])) {
2053 $avatar['email'] = $contact['url'];
2055 return DI::baseUrl() . $default;
2058 $avatar['url'] = '';
2059 $avatar['success'] = false;
2061 Hook::callAll('avatar_lookup', $avatar);
2063 if ($avatar['success'] && !empty($avatar['url'])) {
2064 return $avatar['url'];
2067 return DI::baseUrl() . $default;
2071 * Get avatar link for given contact id
2073 * @param integer $cid contact id
2074 * @param string $size One of the Proxy::SIZE_* constants
2075 * @param string $updated Contact update date
2076 * @param bool $static If "true" a parameter is added to convert the avatar to a static one
2077 * @return string avatar link
2079 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2081 // We have to fetch the "updated" variable when it wasn't provided
2082 // The parameter can be provided to improve performance
2083 if (empty($updated)) {
2084 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2085 $updated = $account['updated'] ?? '';
2086 $guid = $account['guid'] ?? '';
2089 $guid = urlencode($guid);
2091 $url = DI::baseUrl() . '/photo/contact/';
2093 case Proxy::SIZE_MICRO:
2094 $url .= Proxy::PIXEL_MICRO . '/';
2096 case Proxy::SIZE_THUMB:
2097 $url .= Proxy::PIXEL_THUMB . '/';
2099 case Proxy::SIZE_SMALL:
2100 $url .= Proxy::PIXEL_SMALL . '/';
2102 case Proxy::SIZE_MEDIUM:
2103 $url .= Proxy::PIXEL_MEDIUM . '/';
2105 case Proxy::SIZE_LARGE:
2106 $url .= Proxy::PIXEL_LARGE . '/';
2111 $query_params['ts'] = strtotime($updated);
2114 $query_params['static'] = true;
2117 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2121 * Get avatar link for given contact URL
2123 * @param string $url contact url
2124 * @param integer $uid user id
2125 * @param string $size One of the Proxy::SIZE_* constants
2126 * @return string avatar link
2128 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2130 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2131 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2132 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2133 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2137 * Get header link for given contact id
2139 * @param integer $cid contact id
2140 * @param string $size One of the Proxy::SIZE_* constants
2141 * @param string $updated Contact update date
2142 * @param bool $static If "true" a parameter is added to convert the header to a static one
2143 * @return string header link
2145 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2147 // We have to fetch the "updated" variable when it wasn't provided
2148 // The parameter can be provided to improve performance
2149 if (empty($updated) || empty($guid)) {
2150 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2151 $updated = $account['updated'] ?? '';
2152 $guid = $account['guid'] ?? '';
2155 $guid = urlencode($guid);
2157 $url = DI::baseUrl() . '/photo/header/';
2159 case Proxy::SIZE_MICRO:
2160 $url .= Proxy::PIXEL_MICRO . '/';
2162 case Proxy::SIZE_THUMB:
2163 $url .= Proxy::PIXEL_THUMB . '/';
2165 case Proxy::SIZE_SMALL:
2166 $url .= Proxy::PIXEL_SMALL . '/';
2168 case Proxy::SIZE_MEDIUM:
2169 $url .= Proxy::PIXEL_MEDIUM . '/';
2171 case Proxy::SIZE_LARGE:
2172 $url .= Proxy::PIXEL_LARGE . '/';
2178 $query_params['ts'] = strtotime($updated);
2181 $query_params['static'] = true;
2184 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2188 * Updates the avatar links in a contact only if needed
2190 * @param int $cid Contact id
2191 * @param string $avatar Link to avatar picture
2192 * @param bool $force force picture update
2193 * @param bool $create_cache Enforces the creation of cached avatar fields
2196 * @throws HTTPException\InternalServerErrorException
2197 * @throws HTTPException\NotFoundException
2198 * @throws \ImagickException
2200 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2202 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2203 ['id' => $cid, 'self' => false]);
2204 if (!DBA::isResult($contact)) {
2208 $uid = $contact['uid'];
2210 // Only update the cached photo links of public contacts when they already are cached
2211 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2212 if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2213 $update_fields = ['avatar' => $avatar];
2214 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2216 $img_str = $fetchResult->getBody();
2217 if (!empty($img_str)) {
2218 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2219 if ($image->isValid()) {
2220 $update_fields['blurhash'] = $image->getBlurHash();
2224 self::update($update_fields, ['id' => $cid]);
2225 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2230 // User contacts use are updated through the public contacts
2231 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2232 $pcid = self::getIdForURL($contact['url'], 0, false);
2233 if (!empty($pcid)) {
2234 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2235 self::updateAvatar($pcid, $avatar, $force, true);
2240 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2242 if ($default_avatar) {
2243 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2246 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2248 // Local contact avatars don't need to be cached
2249 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2250 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2253 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2254 Avatar::deleteCache($contact);
2256 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2257 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2259 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2260 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2261 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2264 // Use the data from the self account
2265 if (empty($fields)) {
2266 $local_uid = User::getIdForURL($contact['url']);
2267 if (!empty($local_uid)) {
2268 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2269 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2273 if (empty($fields)) {
2274 $update = ($contact['avatar'] != $avatar) || $force;
2278 $contact['photo'] ?? '',
2279 $contact['thumb'] ?? '',
2280 $contact['micro'] ?? '',
2283 foreach ($data as $image_uri) {
2284 $image_rid = Photo::ridFromURI($image_uri);
2285 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2286 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2293 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2295 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2296 $update = !empty($fields);
2297 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2303 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2306 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2307 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2308 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2317 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2318 // Collect all user contacts of the given public contact
2319 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2320 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2321 while ($personal_contact = DBA::fetch($personal_contacts)) {
2322 $cids[] = $personal_contact['id'];
2323 $uids[] = $personal_contact['uid'];
2325 DBA::close($personal_contacts);
2327 if (!empty($cids)) {
2328 // Delete possibly existing cached user contact avatars
2329 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2335 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2336 self::update($fields, ['id' => $cids]);
2339 public static function deleteContactByUrl(string $url)
2341 // Update contact data for all users
2342 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2343 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2344 while ($contact = DBA::fetch($contacts)) {
2345 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2346 self::remove($contact['id']);
2351 * Helper function for "updateFromProbe". Updates personal and public contact
2353 * @param integer $id contact id
2354 * @param integer $uid user id
2355 * @param integer $uri_id Uri-Id
2356 * @param string $url The profile URL of the contact
2357 * @param array $fields The fields that are updated
2359 * @throws \Exception
2361 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2363 if (!self::update($fields, ['id' => $id])) {
2364 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2368 self::setAccountUser($id, $uid, $uri_id, $url);
2370 // Archive or unarchive the contact.
2371 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2372 if (!DBA::isResult($contact)) {
2373 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2377 if (isset($fields['failed'])) {
2378 if ($fields['failed']) {
2379 self::markForArchival($contact);
2381 self::unmarkForArchival($contact);
2385 if ($contact['uid'] != 0) {
2389 // Update contact data for all users
2390 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2392 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2393 self::update($fields, $condition);
2395 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2396 $condition['network'] = Protocol::OSTATUS;
2398 // If the contact failed, propagate the update fields to all contacts
2399 if (empty($fields['failed'])) {
2400 unset($fields['last-update']);
2401 unset($fields['success_update']);
2402 unset($fields['failure_update']);
2405 if (empty($fields)) {
2409 self::update($fields, $condition);
2413 * Create or update an "account-user" entry
2415 * @param integer $id
2416 * @param integer $uid
2417 * @param integer $uri_id
2418 * @param string $url
2421 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2423 if (empty($uri_id)) {
2427 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2428 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2429 if ($account_user['uid'] == $uid) {
2430 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2431 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2433 // This should never happen
2434 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]);
2438 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2439 if (!empty($account_user['id'])) {
2440 if ($account_user['id'] == $id) {
2441 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2443 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2444 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2445 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2448 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2449 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2450 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2451 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2453 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2458 * Remove duplicated contacts
2460 * @param string $nurl Normalised contact url
2461 * @param integer $uid User id
2463 * @throws \Exception
2465 public static function removeDuplicates(string $nurl, int $uid)
2467 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2468 $count = DBA::count('contact', $condition);
2473 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2474 if (!DBA::isResult($first_contact)) {
2475 // Shouldn't happen - so we handle it
2479 $first = $first_contact['id'];
2480 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2482 // Find all duplicates
2483 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2484 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2485 while ($duplicate = DBA::fetch($duplicates)) {
2486 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2490 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2492 DBA::close($duplicates);
2493 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2498 * Perform a contact update if the contact is outdated
2500 * @param integer $id contact id
2503 public static function updateByIdIfNeeded(int $id): bool
2505 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2506 if (empty($contact['url'])) {
2510 if (self::isLocal($contact['url'])) {
2514 $stamp = (float)microtime(true);
2515 self::updateFromProbe($id);
2516 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
2521 * Perform a contact update if the contact is outdated
2523 * @param string $url contact url
2526 public static function updateByUrlIfNeeded(string $url): bool
2528 $id = self::getIdForURL($url, 0, false);
2530 return self::updateByIdIfNeeded($id);
2532 return (bool)self::getIdForURL($url);
2536 * Updates contact record by provided id and optional network
2538 * @param integer $id contact id
2539 * @param string $network Optional network we are probing for
2541 * @throws HTTPException\InternalServerErrorException
2542 * @throws \ImagickException
2544 public static function updateFromProbe(int $id, string $network = '')
2546 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2547 if (!DBA::isResult($contact)) {
2551 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2553 if ($data['network'] == Protocol::DIASPORA) {
2555 DI::dsprContact()->updateFromProbeArray($data);
2556 } catch (HTTPException\NotFoundException $e) {
2557 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2558 } catch (\InvalidArgumentException $e) {
2559 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2561 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2563 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2564 } catch (HTTPException\NotFoundException $e) {
2565 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2566 } catch (\InvalidArgumentException $e) {
2567 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2571 return self::updateFromProbeArray($id, $data);
2575 * Checks if the given contact has got local data
2578 * @param array $contact
2582 private static function hasLocalData(int $id, array $contact): bool
2584 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2585 // User contacts with the same uri-id exist
2587 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2588 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2591 if (DBA::exists('post-tag', ['cid' => $id])) {
2592 // Is tagged in a post
2595 if (DBA::exists('user-contact', ['cid' => $id])) {
2596 // Has got user-contact data
2599 if (Post::exists(['author-id' => $id])) {
2600 // Posts with this author exist
2603 if (Post::exists(['owner-id' => $id])) {
2604 // Posts with this owner exist
2607 if (Post::exists(['causer-id' => $id])) {
2608 // Posts with this causer exist
2611 // We don't have got this contact locally
2616 * Updates contact record by provided id and probed data
2618 * @param integer $id contact id
2619 * @param array $ret Probed data
2621 * @throws HTTPException\InternalServerErrorException
2622 * @throws \ImagickException
2624 private static function updateFromProbeArray(int $id, array $ret): bool
2627 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2628 This will reliably kill your communication with old Friendica contacts.
2631 // These fields aren't updated by this routine:
2634 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2635 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2636 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2637 'created', 'last-update'];
2638 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2639 if (!DBA::isResult($contact)) {
2643 if (self::isLocal($ret['url'])) {
2644 if ($contact['uid'] == 0) {
2645 Logger::info('Local contacts are not updated here.');
2647 self::updateFromPublicContact($id, $contact);
2652 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2653 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2656 // Delete all contacts with the same URL
2657 self::deleteContactByUrl($ret['url']);
2661 $uid = $contact['uid'];
2662 unset($contact['uid']);
2664 $uriid = $contact['uri-id'];
2665 unset($contact['uri-id']);
2667 $pubkey = $contact['pubkey'];
2668 unset($contact['pubkey']);
2670 $created = $contact['created'];
2671 unset($contact['created']);
2673 $last_update = $contact['last-update'];
2674 unset($contact['last-update']);
2676 $contact['photo'] = $contact['avatar'];
2677 unset($contact['avatar']);
2679 $updated = DateTimeFormat::utcNow();
2681 $has_local_data = self::hasLocalData($id, $contact);
2683 if (!Probe::isProbable($ret['network'])) {
2684 // Periodical checks are only done on federated contacts
2685 $failed_next_update = null;
2686 $success_next_update = null;
2687 } elseif ($has_local_data) {
2688 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2689 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2691 $failed_next_update = DateTimeFormat::utc('now +6 month');
2692 $success_next_update = DateTimeFormat::utc('now +1 month');
2695 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2696 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2697 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]);
2701 // We must not try to update relay contacts via probe. They are no real contacts.
2702 // We check after the probing to be able to correct falsely detected contact types.
2703 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2704 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2705 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]);
2706 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2710 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2711 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2712 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]);
2716 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2717 $cid = self::getIdForURL($ret['url'], 0, false);
2718 if (!empty($cid) && ($cid != $id)) {
2719 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2720 return self::updateFromProbeArray($cid, $ret);
2724 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2725 $ret['unsearchable'] = $ret['hide'];
2728 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2729 $ret['forum'] = false;
2730 $ret['prv'] = false;
2731 $ret['contact-type'] = $ret['account-type'];
2732 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2733 $ret['forum'] = (bool)!$ret['manually-approve'];
2734 $ret['prv'] = (bool)!$ret['forum'];
2738 $new_pubkey = $ret['pubkey'] ?? '';
2740 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2741 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2742 $apcontact = APContact::getByURL($ret['url'], false);
2743 if (!empty($apcontact['featured'])) {
2744 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2748 $ret['last-item'] = Probe::getLastUpdate($ret);
2749 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2753 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url']);
2755 // make sure to not overwrite existing values with blank entries except some technical fields
2756 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2757 foreach ($ret as $key => $val) {
2758 if (!array_key_exists($key, $contact)) {
2760 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2761 $ret[$key] = $contact[$key];
2762 } elseif ($ret[$key] != $contact[$key]) {
2767 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2770 unset($ret['last-item']);
2773 if (empty($uriid)) {
2777 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2778 self::updateAvatar($id, $ret['photo'], $update);
2782 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]);
2784 if (Contact\Relation::isDiscoverable($ret['url'])) {
2785 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2788 // Update the public contact
2790 $contact = self::getByURL($ret['url'], false, ['id']);
2791 if (!empty($contact['id'])) {
2792 self::updateFromProbeArray($contact['id'], $ret);
2799 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2800 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2801 $ret['updated'] = $updated;
2802 $ret['failed'] = false;
2803 $ret['next-update'] = $success_next_update;
2804 $ret['local-data'] = $has_local_data;
2806 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2807 if (empty($pubkey) && !empty($new_pubkey)) {
2808 $ret['pubkey'] = $new_pubkey;
2811 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2812 $ret['uri-date'] = $updated;
2815 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2816 $ret['name-date'] = $updated;
2819 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2820 $ret['last-update'] = $updated;
2821 $ret['success_update'] = $updated;
2824 unset($ret['photo']);
2826 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2828 if (Contact\Relation::isDiscoverable($ret['url'])) {
2829 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2835 private static function updateFromPublicContact(int $id, array $contact)
2837 $public = self::getByURL($contact['url'], false);
2841 foreach ($contact as $field => $value) {
2842 if ($field == 'uid') {
2845 if ($public[$field] != $value) {
2846 $fields[$field] = $public[$field];
2849 if (!empty($fields)) {
2850 self::update($fields, ['id' => $id, 'self' => false]);
2851 Logger::info('Updating local contact', ['id' => $id]);
2856 * Updates contact record by provided URL
2858 * @param integer $url contact url
2859 * @return integer Contact id
2860 * @throws HTTPException\InternalServerErrorException
2861 * @throws \ImagickException
2863 public static function updateFromProbeByURL(string $url): int
2865 $id = self::getIdForURL($url);
2871 self::updateFromProbe($id);
2877 * Detects the communication protocol for a given contact url.
2878 * This is used to detect Friendica contacts that we can communicate via AP.
2880 * @param string $url contact url
2881 * @param string $network Network of that contact
2882 * @return string with protocol
2884 public static function getProtocol(string $url, string $network): string
2886 if ($network != Protocol::DFRN) {
2890 $apcontact = APContact::getByURL($url);
2891 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2892 return Protocol::ACTIVITYPUB;
2899 * Takes a $uid and a url/handle and adds a new contact
2901 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2902 * dfrn_request page.
2904 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2907 * $return['success'] boolean true if successful
2908 * $return['message'] error text if success is false.
2910 * Takes a $uid and a url/handle and adds a new contact
2912 * @param int $uid The user id the contact should be created for
2913 * @param string $url The profile URL of the contact
2914 * @param string $network
2916 * @throws HTTPException\InternalServerErrorException
2917 * @throws HTTPException\NotFoundException
2918 * @throws \ImagickException
2920 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2922 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2924 // remove ajax junk, e.g. Twitter
2925 $url = str_replace('/#!/', '/', $url);
2927 if (!Network::isUrlAllowed($url)) {
2928 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2932 if (Network::isUrlBlocked($url)) {
2933 $result['message'] = DI::l10n()->t('Blocked domain');
2938 $result['message'] = DI::l10n()->t('Connect URL missing.');
2942 $arr = ['url' => $url, 'contact' => []];
2944 Hook::callAll('follow', $arr);
2947 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2951 if (!empty($arr['contact']['name'])) {
2953 $ret = $arr['contact'];
2956 $ret = Probe::uri($url, $network, $uid);
2958 // Ensure that the public contact exists
2959 if ($ret['network'] != Protocol::PHANTOM) {
2960 self::getIdForURL($url);
2964 if (($network != '') && ($ret['network'] != $network)) {
2965 $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
2969 // check if we already have a contact
2970 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url'])];
2971 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
2973 $protocol = self::getProtocol($ret['url'], $ret['network']);
2975 // This extra param just confuses things, remove it
2976 if ($protocol === Protocol::DIASPORA) {
2977 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2980 // do we have enough information?
2981 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2982 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
2983 if (empty($ret['poll'])) {
2984 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
2986 if (empty($ret['name'])) {
2987 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
2989 if (empty($ret['url'])) {
2990 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
2992 if (strpos($ret['url'], '@') !== false) {
2993 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
2994 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
2999 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3000 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3001 $ret['notify'] = '';
3004 if (!$ret['notify']) {
3005 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3008 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3010 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3012 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3015 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3016 $pending = (bool)$ret['manually-approve'];
3019 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3023 if (DBA::isResult($contact)) {
3025 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3027 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3029 if ($contact['pending'] && !empty($contact['hub-verify'])) {
3030 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3031 $fields['pending'] = false;
3034 self::update($fields, ['id' => $contact['id']]);
3036 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3038 // create contact record
3041 'created' => DateTimeFormat::utcNow(),
3042 'url' => $ret['url'],
3043 'nurl' => Strings::normaliseLink($ret['url']),
3044 'addr' => $ret['addr'],
3045 'alias' => $ret['alias'],
3046 'batch' => $ret['batch'],
3047 'notify' => $ret['notify'],
3048 'poll' => $ret['poll'],
3049 'poco' => $ret['poco'],
3050 'name' => $ret['name'],
3051 'nick' => $ret['nick'],
3052 'network' => $ret['network'],
3053 'baseurl' => $ret['baseurl'],
3054 'gsid' => $ret['gsid'] ?? null,
3055 'protocol' => $protocol,
3056 'pubkey' => $ret['pubkey'],
3057 'rel' => $new_relation,
3058 'priority'=> $ret['priority'],
3059 'writable'=> $writeable,
3060 'hidden' => $hidden,
3063 'pending' => $pending,
3068 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3069 if (!DBA::isResult($contact)) {
3070 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3074 $contact_id = $contact['id'];
3075 $result['cid'] = $contact_id;
3077 Group::addMember(User::getDefaultGroup($uid), $contact_id);
3079 // Update the avatar
3080 self::updateAvatar($contact_id, $ret['photo']);
3082 // pull feed and consume it, which should subscribe to the hub.
3083 if ($contact['network'] == Protocol::OSTATUS) {
3084 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3088 self::updateFromProbeArray($contact_id, $ret);
3091 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3092 } catch (\InvalidArgumentException $e) {
3093 Logger::notice($e->getMessage(), ['contact' => $contact]);
3097 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3103 * @param array $importer Owner (local user) data
3104 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3105 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3106 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3107 * @param string $note Introduction additional message
3108 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3109 * @throws HTTPException\InternalServerErrorException
3110 * @throws \ImagickException
3112 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3114 // Should always be set
3115 if (empty($datarray['author-id'])) {
3119 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3120 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3121 if (!DBA::isResult($pub_contact)) {
3122 // Should never happen
3126 // Contact is blocked at node-level
3127 if (self::isBlocked($datarray['author-id'])) {
3131 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3132 $name = $pub_contact['name'];
3133 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3134 $nick = $pub_contact['nick'];
3135 $network = $pub_contact['network'];
3137 // Ensure that we don't create a new contact when there already is one
3138 $cid = self::getIdForURL($url, $importer['uid']);
3140 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3143 self::clearFollowerFollowingEndpointCache($importer['uid']);
3145 if (!empty($contact)) {
3146 if (!empty($contact['pending'])) {
3147 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3151 // Contact is blocked at user-level
3152 if (!empty($contact['id']) && !empty($importer['id']) &&
3153 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3157 // Make sure that the existing contact isn't archived
3158 self::unmarkForArchival($contact);
3160 if (($contact['rel'] == self::SHARING)
3161 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3162 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3163 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3166 // Ensure to always have the correct network type, independent from the connection request method
3167 self::updateFromProbe($contact['id']);
3169 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3173 // send email notification to owner?
3174 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3175 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3179 // create contact record
3180 $contact_id = self::insert([
3181 'uid' => $importer['uid'],
3182 'created' => DateTimeFormat::utcNow(),
3184 'nurl' => Strings::normaliseLink($url),
3187 'network' => $network,
3188 'rel' => self::FOLLOWER,
3195 // Ensure to always have the correct network type, independent from the connection request method
3196 self::updateFromProbe($contact_id);
3198 self::updateAvatar($contact_id, $photo, true);
3200 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3202 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3204 /// @TODO Encapsulate this into a function/method
3205 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3206 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3207 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3208 // create notification
3209 if (is_array($contact_record)) {
3210 $intro = DI::introFactory()->createNew(
3212 $contact_record['id'],
3215 DI::intro()->save($intro);
3218 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3220 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3221 DI::notify()->createFromArray([
3222 'type' => Notification\Type::INTRO,
3223 'otype' => Notification\ObjectType::INTRO,
3224 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3225 'uid' => $user['uid'],
3226 'cid' => $contact_record['id'],
3227 'link' => DI::baseUrl() . '/notifications/intros',
3230 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3231 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3232 self::createFromProbeForUser($importer['uid'], $url, $network);
3235 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3236 $fields = ['pending' => false];
3237 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3238 $fields['rel'] = self::FRIEND;
3241 self::update($fields, $condition);
3251 * Update the local relationship when a local user loses a follower
3253 * @param array $contact User-specific contact (uid != 0) array
3255 * @throws HTTPException\InternalServerErrorException
3256 * @throws \ImagickException
3258 public static function removeFollower(array $contact)
3260 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3261 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3262 } elseif (!empty($contact['id'])) {
3263 self::remove($contact['id']);
3265 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3269 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3271 self::clearFollowerFollowingEndpointCache($contact['uid']);
3273 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3274 if (!empty($cdata['public'])) {
3275 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3280 * Update the local relationship when a local user unfollow a contact.
3281 * Removes the contact for sharing-only protocols (feed and mail).
3283 * @param array $contact User-specific contact (uid != 0) array
3284 * @throws HTTPException\InternalServerErrorException
3286 public static function removeSharer(array $contact)
3288 self::clearFollowerFollowingEndpointCache($contact['uid']);
3290 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3291 self::remove($contact['id']);
3293 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3296 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3300 * Create a birthday event.
3302 * Update the year and the birthday.
3304 public static function updateBirthdays()
3308 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3309 AND NOT `contact`.`pending`
3310 AND NOT `contact`.`hidden`
3311 AND NOT `contact`.`blocked`
3312 AND NOT `contact`.`archive`
3313 AND NOT `contact`.`deleted`',
3319 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3321 while ($contact = DBA::fetch($contacts)) {
3322 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3324 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3326 if (Event::createBirthday($contact, $nextbd)) {
3330 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3331 ['id' => $contact['id']]
3335 DBA::close($contacts);
3339 * Remove the unavailable contact ids from the provided list
3341 * @param array $contact_ids Contact id list
3343 * @throws \Exception
3345 public static function pruneUnavailable(array $contact_ids): array
3347 if (empty($contact_ids)) {
3351 $contacts = self::selectToArray(['id'], [
3352 'id' => $contact_ids,
3358 return array_column($contacts, 'id');
3362 * Returns a magic link to authenticate remote visitors
3364 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3366 * @param string $contact_url The address of the target contact profile
3367 * @param string $url An url that we will be redirected to after the authentication
3369 * @return string with "redir" link
3370 * @throws HTTPException\InternalServerErrorException
3371 * @throws \ImagickException
3373 public static function magicLink(string $contact_url, string $url = ''): string
3375 if (!DI::userSession()->isAuthenticated()) {
3376 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3379 $contact = self::getByURL($contact_url, false);
3380 if (empty($contact)) {
3381 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3384 // Prevents endless loop in case only a non-public contact exists for the contact URL
3385 unset($contact['uid']);
3387 return self::magicLinkByContact($contact, $url ?: $contact_url);
3391 * Returns a magic link to authenticate remote visitors
3393 * @param integer $cid The contact id of the target contact profile
3394 * @param string $url An url that we will be redirected to after the authentication
3396 * @return string with "redir" link
3397 * @throws HTTPException\InternalServerErrorException
3398 * @throws \ImagickException
3400 public static function magicLinkById(int $cid, string $url = ''): string
3402 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3404 return self::magicLinkByContact($contact, $url);
3408 * Returns a magic link to authenticate remote visitors
3410 * @param array $contact The contact array with "uid", "network" and "url"
3411 * @param string $url An url that we will be redirected to after the authentication
3413 * @return string with "redir" link
3414 * @throws HTTPException\InternalServerErrorException
3415 * @throws \ImagickException
3417 public static function magicLinkByContact(array $contact, string $url = ''): string
3419 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3421 if (!DI::userSession()->isAuthenticated()) {
3422 return $destination;
3425 // Only redirections to the same host do make sense
3426 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3430 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3431 return 'contact/' . $contact['id'] . '/conversations';
3434 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3435 return $destination;
3438 if (empty($contact['id'])) {
3439 return $destination;
3442 $redirect = 'contact/redir/' . $contact['id'];
3444 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3445 $redirect .= '?url=' . $url;
3452 * Is the contact a forum?
3454 * @param integer $contactid ID of the contact
3456 * @return boolean "true" if it is a forum
3458 public static function isForum(int $contactid): bool
3460 $fields = ['contact-type'];
3461 $condition = ['id' => $contactid];
3462 $contact = DBA::selectFirst('contact', $fields, $condition);
3463 if (!DBA::isResult($contact)) {
3468 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3472 * Can the remote contact receive private messages?
3474 * @param array $contact
3477 public static function canReceivePrivateMessages(array $contact): bool
3479 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3480 $self = $contact['self'] ?? false;
3482 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3486 * Search contact table by nick or name
3488 * @param string $search Name or nick
3489 * @param string $mode Search mode (e.g. "community")
3490 * @param int $uid User ID
3491 * @param int $limit Maximum amount of returned values
3492 * @param int $offset Limit offset
3494 * @return array with search results
3495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3497 public static function searchByName(string $search, string $mode = '', int $uid = 0, int $limit = 0, int $offset = 0): array
3499 if (empty($search)) {
3503 // check supported networks
3504 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3505 if (DI::config()->get('system', 'diaspora_enabled')) {
3506 $networks[] = Protocol::DIASPORA;
3509 if (!DI::config()->get('system', 'ostatus_disabled')) {
3510 $networks[] = Protocol::OSTATUS;
3513 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3516 $condition['blocked'] = false;
3518 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3521 // check if we search only communities or every contact
3522 if ($mode === 'community') {
3523 $condition['contact-type'] = self::TYPE_COMMUNITY;
3530 if (!empty($limit) && !empty($offset)) {
3531 $params['limit'] = [$offset, $limit];
3532 } elseif (!empty($limit)) {
3533 $params['limit'] = $limit;
3536 $condition = DBA::mergeConditions($condition,
3537 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3538 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3540 return self::selectToArray([], $condition, $params);
3544 * Add public contacts from an array
3546 * @param array $urls
3547 * @return array result "count", "added" and "updated"
3549 public static function addByUrls(array $urls): array
3556 foreach ($urls as $url) {
3557 if (empty($url) || !is_string($url)) {
3560 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3561 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3562 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3564 } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3566 UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3568 } catch (\InvalidArgumentException $e) {
3569 Logger::notice($e->getMessage(), ['contact' => $contact]);
3577 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3581 * Returns a random, global contact array of the current node
3583 * @return array The profile array
3586 public static function getRandomContact(): array
3588 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3589 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3590 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3591 ], ['order' => ['RAND()']]);
3593 if (DBA::isResult($contact)) {
3601 * Checks, if contacts with the given condition exists
3603 * @param array $condition
3606 * @throws \Exception
3608 public static function exists(array $condition): bool
3610 return DBA::exists('contact', $condition);