3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Contact\Avatar;
25 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Session;
33 use Friendica\Core\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\Database;
36 use Friendica\Database\DBA;
38 use Friendica\Module\NoScrape;
39 use Friendica\Network\HTTPException;
40 use Friendica\Network\Probe;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
50 * functions for interacting with a contact
54 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
55 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
56 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
62 const LOCK_INSERT = 'contact-insert';
67 * TYPE_UNKNOWN - unknown type
69 * TYPE_PERSON - the account belongs to a person
70 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
72 * TYPE_ORGANISATION - the account belongs to an organisation
73 * Associated page type: PAGE_SOAPBOX
75 * TYPE_NEWS - the account is a news reflector
76 * Associated page type: PAGE_SOAPBOX
78 * TYPE_COMMUNITY - the account is community forum
79 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
81 * TYPE_RELAY - the account is a relay
82 * This will only be assigned to contacts, not to user accounts
85 const TYPE_UNKNOWN = -1;
86 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
87 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
88 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
89 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
90 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
110 const MIRROR_DEACTIVATED = 0;
111 const MIRROR_FORWARDED = 1;
112 const MIRROR_OWN_POST = 2;
113 const MIRROR_NATIVE_RESHARE = 3;
116 * @param array $fields Array of selected fields, empty for all
117 * @param array $condition Array of fields for condition
118 * @param array $params Array of several parameters
122 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
124 return DBA::selectToArray('contact', $fields, $condition, $params);
128 * @param array $fields Array of selected fields, empty for all
129 * @param array $condition Array of fields for condition
130 * @param array $params Array of several parameters
134 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
136 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
142 * Insert a row into the contact table
143 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
145 * @param array $fields field array
146 * @param int $duplicate_mode Do an update on a duplicate entry
148 * @return int id of the created contact
151 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
153 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
154 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
157 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
159 if (empty($fields['created'])) {
160 $fields['created'] = DateTimeFormat::utcNow();
163 DBA::insert('contact', $fields, $duplicate_mode);
164 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
165 if (!DBA::isResult($contact)) {
167 Logger::warning('Created contact could not be found', ['fields' => $fields]);
171 Contact\User::insertForContactArray($contact);
173 // Search for duplicated contacts and get rid of them
174 if (!$contact['self']) {
175 self::removeDuplicates($contact['nurl'], $contact['uid']);
178 return $contact['id'];
182 * Updates rows in the contact table
184 * @param array $fields contains the fields that are updated
185 * @param array $condition condition array with the key values
186 * @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)
188 * @return boolean was the update successfull?
190 * @todo Let's get rid of boolean type of $old_fields
192 public static function update(array $fields, array $condition, $old_fields = [])
194 $ret = DBA::update('contact', $fields, $condition, $old_fields);
196 // Apply changes to the "user-contact" table on dedicated fields
197 Contact\User::updateByContactUpdate($fields, $condition);
203 * @param integer $id Contact ID
204 * @param array $fields Array of selected fields, empty for all
205 * @return array|boolean Contact record if it exists, false otherwise
208 public static function getById(int $id, array $fields = [])
210 return DBA::selectFirst('contact', $fields, ['id' => $id]);
214 * Fetch the first contact with the provided uri-id.
216 * @param integer $uri_id uri-id of the contact
217 * @param array $fields Array of selected fields, empty for all
218 * @return array|boolean Contact record if it exists, false otherwise
221 public static function getByUriId(int $uri_id, array $fields = [])
223 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
227 * Fetches a contact by a given url
229 * @param string $url profile url
230 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
231 * @param array $fields Field list
232 * @param integer $uid User ID of the contact
233 * @return array contact array
235 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
237 if ($update || is_null($update)) {
238 $cid = self::getIdForURL($url, $uid, $update);
243 $contact = self::getById($cid, $fields);
244 if (empty($contact)) {
250 // Add internal fields
252 if (!empty($fields)) {
253 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
254 if (!in_array($internal, $fields)) {
255 $fields[] = $internal;
256 $removal[] = $internal;
261 // We first try the nurl (http://server.tld/nick), most common case
262 $options = ['order' => ['id']];
263 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
265 // Then the addr (nick@server.tld)
266 if (!DBA::isResult($contact)) {
267 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
270 // Then the alias (which could be anything)
271 if (!DBA::isResult($contact)) {
272 // The link could be provided as http although we stored it as https
273 $ssl_url = str_replace('http://', 'https://', $url);
274 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
275 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
278 if (!DBA::isResult($contact)) {
282 // Update the contact in the background if needed
283 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
284 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
285 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
288 // Remove the internal fields
289 foreach ($removal as $internal) {
290 unset($contact[$internal]);
297 * Fetches a contact for a given user by a given url.
298 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
300 * @param string $url profile url
301 * @param integer $uid User ID of the contact
302 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
303 * @param array $fields Field list
304 * @return array contact array
306 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
309 $contact = self::getByURL($url, $update, $fields, $uid);
310 if (!empty($contact)) {
311 if (!empty($contact['id'])) {
312 $contact['cid'] = $contact['id'];
319 $contact = self::getByURL($url, $update, $fields);
320 if (!empty($contact['id'])) {
322 $contact['zid'] = $contact['id'];
328 * Tests if the given contact is a follower
330 * @param int $cid Either public contact id or user's contact id
331 * @param int $uid User ID
333 * @return boolean is the contact id a follower?
334 * @throws HTTPException\InternalServerErrorException
335 * @throws \ImagickException
337 public static function isFollower(int $cid, int $uid): bool
339 if (Contact\User::isBlocked($cid, $uid)) {
343 $cdata = self::getPublicAndUserContactID($cid, $uid);
344 if (empty($cdata['user'])) {
348 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
349 return DBA::exists('contact', $condition);
353 * Tests if the given contact url is a follower
355 * @param string $url Contact URL
356 * @param int $uid User ID
358 * @return boolean is the contact id a follower?
359 * @throws HTTPException\InternalServerErrorException
360 * @throws \ImagickException
362 public static function isFollowerByURL(string $url, int $uid): bool
364 $cid = self::getIdForURL($url, $uid);
370 return self::isFollower($cid, $uid);
374 * Tests if the given user shares with the given contact
376 * @param int $cid Either public contact id or user's contact id
377 * @param int $uid User ID
379 * @return boolean is the contact sharing with given user?
380 * @throws HTTPException\InternalServerErrorException
381 * @throws \ImagickException
383 public static function isSharing(int $cid, int $uid): bool
385 if (Contact\User::isBlocked($cid, $uid)) {
389 $cdata = self::getPublicAndUserContactID($cid, $uid);
390 if (empty($cdata['user'])) {
394 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
395 return DBA::exists('contact', $condition);
399 * Tests if the given user follow the given contact url
401 * @param string $url Contact URL
402 * @param int $uid User ID
404 * @return boolean is the contact url being followed?
405 * @throws HTTPException\InternalServerErrorException
406 * @throws \ImagickException
408 public static function isSharingByURL(string $url, int $uid): bool
410 $cid = self::getIdForURL($url, $uid);
416 return self::isSharing($cid, $uid);
420 * Get the basepath for a given contact link
422 * @param string $url The contact link
423 * @param boolean $dont_update Don't update the contact
425 * @return string basepath
426 * @throws HTTPException\InternalServerErrorException
427 * @throws \ImagickException
429 public static function getBasepath(string $url, bool $dont_update = false): string
431 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
432 if (!DBA::isResult($contact)) {
436 if (!empty($contact['baseurl'])) {
437 return $contact['baseurl'];
438 } elseif ($dont_update) {
442 // Update the existing contact
443 self::updateFromProbe($contact['id']);
445 // And fetch the result
446 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
447 if (empty($contact['baseurl'])) {
448 Logger::info('No baseurl for contact', ['url' => $url]);
452 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
453 return $contact['baseurl'];
457 * Check if the given contact url is on the same server
459 * @param string $url The contact link
461 * @return boolean Is it the same server?
463 public static function isLocal(string $url): bool
465 if (!parse_url($url, PHP_URL_SCHEME)) {
466 $addr_parts = explode('@', $url);
467 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
470 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
474 * Check if the given contact ID is on the same server
476 * @param string $url The contact link
477 * @return boolean Is it the same server?
479 public static function isLocalById(int $cid): bool
481 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
482 if (!DBA::isResult($contact)) {
486 if (empty($contact['baseurl'])) {
487 $baseurl = self::getBasepath($contact['url'], true);
489 $baseurl = $contact['baseurl'];
492 return Strings::compareLink($baseurl, DI::baseUrl());
496 * Returns the public contact id of the given user id
498 * @param integer $uid User ID
500 * @return integer|boolean Public contact id for given user id
503 public static function getPublicIdByUserId(int $uid)
505 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
506 if (!DBA::isResult($self)) {
509 return self::getIdForURL($self['url']);
513 * Returns the contact id for the user and the public contact id for a given contact id
515 * @param int $cid Either public contact id or user's contact id
516 * @param int $uid User ID
518 * @return array with public and user's contact id
519 * @throws HTTPException\InternalServerErrorException
520 * @throws \ImagickException
522 public static function getPublicAndUserContactID(int $cid, int $uid): array
524 // We have to use the legacy function as long as the post update hasn't finished
525 if (DI::config()->get('system', 'post_update_version') < 1427) {
526 return self::legacyGetPublicAndUserContactID($cid, $uid);
529 if (empty($uid) || empty($cid)) {
533 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
534 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
538 $pcid = $contact['pid'];
539 if ($contact['uid'] == $uid) {
540 $ucid = $contact['id'];
542 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
543 if (DBA::isResult($contact)) {
544 $ucid = $contact['id'];
550 return ['public' => $pcid, 'user' => $ucid];
554 * Helper function for "getPublicAndUserContactID"
556 * @param int $cid Either public contact id or user's contact id
557 * @param int $uid User ID
558 * @return array with public and user's contact id
559 * @throws HTTPException\InternalServerErrorException
560 * @throws \ImagickException
562 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
564 if (empty($uid) || empty($cid)) {
568 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
569 if (!DBA::isResult($contact)) {
573 // We quit when the user id don't match the user id of the provided contact
574 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
578 if ($contact['uid'] != 0) {
579 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
583 $ucid = $contact['id'];
585 $pcid = $contact['id'];
586 $ucid = self::getIdForURL($contact['url'], $uid);
589 return ['public' => $pcid, 'user' => $ucid];
593 * Returns contact details for a given contact id in combination with a user id
595 * @param int $cid A contact ID
596 * @param int $uid The User ID
597 * @param array $fields The selected fields for the contact
598 * @return array The contact details
602 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
604 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
606 if (!DBA::isResult($contact)) {
614 * Creates the self-contact for the provided user id
617 * @return bool Operation success
618 * @throws HTTPException\InternalServerErrorException
620 public static function createSelfFromUserId(int $uid): bool
622 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
623 ['uid' => $uid, 'account_expired' => false]);
624 if (!DBA::isResult($user)) {
629 'uid' => $user['uid'],
630 'created' => DateTimeFormat::utcNow(),
632 'name' => $user['username'],
633 'nick' => $user['nickname'],
634 'pubkey' => $user['pubkey'],
635 'prvkey' => $user['prvkey'],
636 'photo' => User::getAvatarUrl($user),
637 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
638 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
641 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
642 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
643 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
644 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
645 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
646 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
647 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
648 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
649 'name-date' => DateTimeFormat::utcNow(),
650 'uri-date' => DateTimeFormat::utcNow(),
651 'avatar-date' => DateTimeFormat::utcNow(),
657 // Only create the entry if it doesn't exist yet
658 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
659 $return = (bool)self::insert($contact);
662 // Create the public contact
663 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
664 $contact['self'] = false;
666 $contact['prvkey'] = null;
668 self::insert($contact, Database::INSERT_IGNORE);
675 * Updates the self-contact for the provided user id
678 * @param bool $update_avatar Force the avatar update
679 * @return bool "true" if updated
680 * @throws HTTPException\InternalServerErrorException
682 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
684 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
685 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
686 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
687 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
688 if (!DBA::isResult($self)) {
692 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
693 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
694 if (!DBA::isResult($user)) {
698 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
699 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
700 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
701 if (!DBA::isResult($profile)) {
705 $file_suffix = 'jpg';
706 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
709 'name' => $profile['name'],
710 'nick' => $user['nickname'],
711 'avatar-date' => $self['avatar-date'],
712 'location' => Profile::formatLocation($profile),
713 'about' => $profile['about'],
714 'keywords' => $profile['pub_keywords'],
715 'contact-type' => $user['account-type'],
716 'prvkey' => $user['prvkey'],
717 'pubkey' => $user['pubkey'],
718 'xmpp' => $profile['xmpp'],
719 'matrix' => $profile['matrix'],
720 'network' => Protocol::DFRN,
722 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
723 'nurl' => Strings::normaliseLink($url),
724 'uri-id' => ItemURI::getIdByURI($url),
725 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
726 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
727 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
728 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
729 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
730 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
734 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
735 if (DBA::isResult($avatar)) {
736 if ($update_avatar) {
737 $fields['avatar-date'] = DateTimeFormat::utcNow();
740 // Creating the path to the avatar, beginning with the file suffix
741 $types = Images::supportedTypes();
742 if (isset($types[$avatar['type']])) {
743 $file_suffix = $types[$avatar['type']];
746 // We are adding a timestamp value so that other systems won't use cached content
747 $timestamp = strtotime($fields['avatar-date']);
749 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
750 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
752 $fields['photo'] = $prefix . '4' . $suffix;
753 $fields['thumb'] = $prefix . '5' . $suffix;
754 $fields['micro'] = $prefix . '6' . $suffix;
756 // We hadn't found a photo entry, so we use the default avatar
757 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
758 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
759 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
762 $fields['avatar'] = User::getAvatarUrl($user);
763 $fields['header'] = User::getBannerUrl($user);
764 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
765 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
766 $fields['unsearchable'] = !$profile['net-publish'];
767 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
771 foreach ($fields as $field => $content) {
772 if ($self[$field] != $content) {
778 if ($fields['name'] != $self['name']) {
779 $fields['name-date'] = DateTimeFormat::utcNow();
781 $fields['updated'] = DateTimeFormat::utcNow();
782 self::update($fields, ['id' => $self['id']]);
784 // Update the other contacts as well
785 unset($fields['prvkey']);
786 $fields['self'] = false;
787 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
789 // Update the profile
791 'photo' => User::getAvatarUrl($user),
792 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
795 DBA::update('profile', $fields, ['uid' => $uid]);
802 * Marks a contact for removal
804 * @param int $id contact id
806 * @throws HTTPException\InternalServerErrorException
808 public static function remove(int $id)
810 // We want just to make sure that we don't delete our "self" contact
811 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
812 if (!DBA::isResult($contact)) {
816 self::clearFollowerFollowingEndpointCache($contact['uid']);
818 // Archive the contact
819 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
821 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
822 Avatar::deleteCache($contact);
825 // Delete it in the background
826 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
830 * Unfollow the remote contact
832 * @param array $contact Target user-specific contact (uid != 0) array
834 * @throws HTTPException\InternalServerErrorException
835 * @throws \ImagickException
837 public static function unfollow(array $contact): void
839 if (empty($contact['network'])) {
840 throw new \InvalidArgumentException('Empty network in contact array');
843 if (empty($contact['uid'])) {
844 throw new \InvalidArgumentException('Unexpected public contact record');
847 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
848 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
849 if (!empty($cdata['public'])) {
850 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
854 self::removeSharer($contact);
858 * Revoke follow privileges of the remote user contact
860 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
862 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
864 * @throws HTTPException\InternalServerErrorException
865 * @throws \ImagickException
867 public static function revokeFollow(array $contact): void
869 if (empty($contact['network'])) {
870 throw new \InvalidArgumentException('Empty network in contact array');
873 if (empty($contact['uid'])) {
874 throw new \InvalidArgumentException('Unexpected public contact record');
877 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
878 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
879 if (!empty($cdata['public'])) {
880 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
884 self::removeFollower($contact);
888 * Completely severs a relationship with a contact
890 * @param array $contact User-specific contact (uid != 0) array
892 * @throws HTTPException\InternalServerErrorException
893 * @throws \ImagickException
895 public static function terminateFriendship(array $contact)
897 if (empty($contact['network'])) {
898 throw new \InvalidArgumentException('Empty network in contact array');
901 if (empty($contact['uid'])) {
902 throw new \InvalidArgumentException('Unexpected public contact record');
905 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
907 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
908 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
911 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
912 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
915 self::remove($contact['id']);
918 private static function clearFollowerFollowingEndpointCache(int $uid)
924 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
925 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
926 DI::cache()->delete(NoScrape::CACHEKEY . $uid);
930 * Marks a contact for archival after a communication issue delay
932 * Contact has refused to recognise us as a friend. We will start a countdown.
933 * If they still don't recognise us in 32 days, the relationship is over,
934 * and we won't waste any more time trying to communicate with them.
935 * This provides for the possibility that their database is temporarily messed
936 * up or some other transient event and that there's a possibility we could recover from it.
938 * @param array $contact contact to mark for archival
940 * @throws HTTPException\InternalServerErrorException
942 public static function markForArchival(array $contact)
944 if (!isset($contact['url']) && !empty($contact['id'])) {
945 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
946 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
947 if (!DBA::isResult($contact)) {
950 } elseif (!isset($contact['url'])) {
951 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
954 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
956 // Contact already archived or "self" contact? => nothing to do
957 if ($contact['archive'] || $contact['self']) {
961 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
962 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
963 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
966 * We really should send a notification to the owner after 2-3 weeks
967 * so they won't be surprised when the contact vanishes and can take
968 * remedial action if this was a serious mistake or glitch
971 /// @todo Check for contact vitality via probing
972 $archival_days = DI::config()->get('system', 'archival_days', 32);
974 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
975 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
976 /* Relationship is really truly dead. archive them rather than
977 * delete, though if the owner tries to unarchive them we'll start
978 * the whole process over again.
980 self::update(['archive' => true], ['id' => $contact['id']]);
981 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
987 * Cancels the archival countdown
989 * @see Contact::markForArchival()
991 * @param array $contact contact to be unmarked for archival
995 public static function unmarkForArchival(array $contact)
997 // Always unarchive the relay contact entry
998 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
999 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1000 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1001 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1002 self::update($fields, $condition);
1006 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1007 $exists = DBA::exists('contact', $condition);
1009 // We don't need to update, we never marked this contact for archival
1014 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1016 if (!isset($contact['url']) && !empty($contact['id'])) {
1017 $fields = ['id', 'url', 'batch'];
1018 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1019 if (!DBA::isResult($contact)) {
1024 // It's a miracle. Our dead contact has inexplicably come back to life.
1025 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1026 self::update($fields, ['id' => $contact['id']]);
1027 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1031 * Returns the data array for the photo menu of a given contact
1033 * @param array $contact contact
1034 * @param int $uid optional, default 0
1036 * @throws HTTPException\InternalServerErrorException
1037 * @throws \ImagickException
1039 public static function photoMenu(array $contact, int $uid = 0): array
1046 $uid = local_user();
1049 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1051 $profile_link = self::magicLinkByContact($contact);
1052 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1057 // Look for our own contact if the uid doesn't match and isn't public
1058 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1059 if (DBA::isResult($contact_own)) {
1060 return self::photoMenu($contact_own, $uid);
1065 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1067 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1069 $profile_link = $contact['url'];
1072 if ($profile_link === 'mailbox') {
1077 $status_link = $profile_link . '/status';
1078 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1079 $profile_link = $profile_link . '/profile';
1082 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1083 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1086 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1088 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1091 $unfollow_link = '';
1092 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1093 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1094 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1095 } elseif(!$contact['pending']) {
1096 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1102 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1104 if (empty($contact['uid'])) {
1106 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1107 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1108 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1109 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1110 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1114 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1115 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1116 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1117 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1118 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1119 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1120 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1121 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1124 if (!empty($contact['pending'])) {
1126 $intro = DI::intro()->selectForContact($contact['id']);
1127 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1128 } catch (IntroductionNotFoundException $exception) {
1129 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1134 $args = ['contact' => $contact, 'menu' => &$menu];
1136 Hook::callAll('contact_photo_menu', $args);
1138 $menucondensed = [];
1140 foreach ($menu as $menuname => $menuitem) {
1141 if ($menuitem[1] != '') {
1142 $menucondensed[$menuname] = $menuitem;
1146 return $menucondensed;
1150 * Fetch the contact id for a given URL and user
1152 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1153 * `addr` or `alias`.
1155 * If there's no record and we aren't looking for a public contact, we quit.
1156 * If there's one, we check that it isn't time to update the picture else we
1157 * directly return the found contact id.
1159 * Second, we probe the provided $url whether it's http://server.tld/profile or
1160 * nick@server.tld. We quit if we can't get any info back.
1162 * Third, we create the contact record if it doesn't exist
1164 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1165 * if there's any updates
1167 * @param string $url Contact URL
1168 * @param integer $uid The user id for the contact (0 = public contact)
1169 * @param boolean $update true = always update, false = never update, null = update when not found
1170 * @param array $default Default value for creating the contact when everything else fails
1172 * @return integer Contact ID
1173 * @throws HTTPException\InternalServerErrorException
1174 * @throws \ImagickException
1176 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1181 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1185 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1187 if (!empty($contact)) {
1188 $contact_id = $contact['id'];
1190 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1191 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1194 } elseif ($uid != 0) {
1195 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1197 } elseif (empty($default) && !is_null($update) && !$update) {
1198 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1204 if (empty($default['network']) || $update) {
1205 $data = Probe::uri($url, '', $uid);
1207 // Take the default values when probing failed
1208 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1209 $data = array_merge($data, $default);
1211 } elseif (!empty($default['network'])) {
1215 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1216 // Fetch data for the public contact via the first found personal contact
1217 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1218 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1219 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1220 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1222 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1223 if (!DBA::isResult($personal_contact)) {
1224 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1227 if (DBA::isResult($personal_contact)) {
1228 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1229 $data = $personal_contact;
1230 $data['photo'] = $personal_contact['avatar'];
1231 $data['account-type'] = $personal_contact['contact-type'];
1232 $data['hide'] = $personal_contact['unsearchable'];
1233 unset($data['avatar']);
1234 unset($data['contact-type']);
1235 unset($data['unsearchable']);
1239 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1240 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1245 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1246 if (!empty($data['alias'])) {
1247 $urls[] = Strings::normaliseLink($data['alias']);
1249 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1250 if (!empty($contact['id'])) {
1251 $contact_id = $contact['id'];
1252 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1257 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1260 'url' => $data['url'],
1261 'nurl' => Strings::normaliseLink($data['url']),
1262 'network' => $data['network'],
1263 'created' => DateTimeFormat::utcNow(),
1264 'rel' => self::SHARING,
1270 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1272 // Before inserting we do check if the entry does exist now.
1273 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1274 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1275 if (DBA::isResult($contact)) {
1276 $contact_id = $contact['id'];
1277 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1279 $contact_id = self::insert($fields);
1281 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1284 DI::lock()->release(self::LOCK_INSERT);
1286 Logger::warning('Contact lock had not been acquired');
1290 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1294 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1297 if ($data['network'] == Protocol::DIASPORA) {
1298 FContact::updateFromProbeArray($data);
1301 self::updateFromProbeArray($contact_id, $data);
1303 // Don't return a number for a deleted account
1304 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1305 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1313 * Checks if the contact is archived
1315 * @param int $cid contact id
1317 * @return boolean Is the contact archived?
1318 * @throws HTTPException\InternalServerErrorException
1320 public static function isArchived(int $cid): bool
1326 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1327 if (!DBA::isResult($contact)) {
1331 if ($contact['archive']) {
1335 // Check status of ActivityPub endpoints
1336 $apcontact = APContact::getByURL($contact['url'], false);
1337 if (!empty($apcontact)) {
1338 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1342 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1347 // Check status of Diaspora endpoints
1348 if (!empty($contact['batch'])) {
1349 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1350 return DBA::exists('contact', $condition);
1357 * Checks if the contact is blocked
1359 * @param int $cid contact id
1360 * @return boolean Is the contact blocked?
1361 * @throws HTTPException\InternalServerErrorException
1363 public static function isBlocked(int $cid): bool
1369 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1370 if (!DBA::isResult($blocked)) {
1374 if (Network::isUrlBlocked($blocked['url'])) {
1378 return (bool) $blocked['blocked'];
1382 * Checks if the contact is hidden
1384 * @param int $cid contact id
1385 * @return boolean Is the contact hidden?
1386 * @throws \Exception
1388 public static function isHidden(int $cid): bool
1394 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1395 if (!DBA::isResult($hidden)) {
1398 return (bool) $hidden['hidden'];
1402 * Returns posts from a given contact url
1404 * @param string $contact_url Contact URL
1405 * @param bool $thread_mode
1406 * @param int $update Update mode
1407 * @param int $parent Item parent ID for the update mode
1408 * @param bool $only_media Only display media content
1409 * @return string posts in HTML
1410 * @throws \Exception
1412 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1414 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1418 * Returns posts from a given contact id
1420 * @param int $cid Contact ID
1421 * @param bool $thread_mode
1422 * @param int $update Update mode
1423 * @param int $parent Item parent ID for the update mode
1424 * @param bool $only_media Only display media content
1425 * @return string posts in HTML
1426 * @throws \Exception
1428 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1430 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1431 if (!DBA::isResult($contact)) {
1435 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1436 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1441 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1444 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1445 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1447 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1448 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1451 if (!empty($parent)) {
1452 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1454 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1455 if (!empty($last_received)) {
1456 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1461 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1462 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1465 if (DI::mode()->isMobile()) {
1466 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1467 DI::config()->get('system', 'itemspage_network_mobile'));
1469 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1470 DI::config()->get('system', 'itemspage_network'));
1473 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1475 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1477 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1478 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1479 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1485 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1486 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1488 if ($pager->getStart() == 0) {
1489 $cdata = self::getPublicAndUserContactID($cid, local_user());
1490 if (!empty($cdata['public'])) {
1491 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1492 $items = array_merge($items, $pinned);
1496 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
1498 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1499 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1501 if ($pager->getStart() == 0) {
1502 $cdata = self::getPublicAndUserContactID($cid, local_user());
1503 if (!empty($cdata['public'])) {
1504 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1505 $cdata['public'], Post\Collection::FEATURED];
1506 $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1507 $items = array_merge($pinned, $items);
1511 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1515 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1516 $o .= HTML::scrollLoader();
1518 $o .= $pager->renderMinimal(count($items));
1526 * Returns the account type name
1528 * The function can be called with either the user or the contact array
1530 * @param int $type type of contact or account
1533 public static function getAccountType(int $type): string
1536 case self::TYPE_ORGANISATION:
1537 $account_type = DI::l10n()->t("Organisation");
1540 case self::TYPE_NEWS:
1541 $account_type = DI::l10n()->t('News');
1544 case self::TYPE_COMMUNITY:
1545 $account_type = DI::l10n()->t("Forum");
1553 return $account_type;
1559 * @param int $cid Contact id to block
1560 * @param string $reason Block reason
1561 * @return bool Whether it was successful
1563 public static function block(int $cid, string $reason = null): bool
1565 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1571 * Unblocks a contact
1573 * @param int $cid Contact id to unblock
1574 * @return bool Whether it was successfull
1576 public static function unblock(int $cid): bool
1578 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1584 * Ensure that cached avatar exist
1586 * @param integer $cid Contact id
1588 public static function checkAvatarCache(int $cid)
1590 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1591 if (!DBA::isResult($contact)) {
1595 if (Network::isLocalLink($contact['url'])) {
1599 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1600 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1601 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1602 self::updateAvatar($cid, $contact['avatar'], true);
1605 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1606 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1607 self::updateAvatar($cid, $contact['avatar'], true);
1609 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1610 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1611 self::updateAvatar($cid, $contact['avatar'], true);
1617 * Return the photo path for a given contact array in the given size
1619 * @param array $contact contact array
1620 * @param string $field Fieldname of the photo in the contact array
1621 * @param string $size Size of the avatar picture
1622 * @param string $avatar Avatar path that is displayed when no photo had been found
1623 * @param bool $no_update Don't perfom an update if no cached avatar was found
1624 * @return string photo path
1626 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1628 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1630 if (DI::config()->get('system', 'avatar_cache')) {
1632 case Proxy::SIZE_MICRO:
1633 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1634 return $contact['micro'];
1637 case Proxy::SIZE_THUMB:
1638 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1639 return $contact['thumb'];
1642 case Proxy::SIZE_SMALL:
1643 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1644 return $contact['photo'];
1650 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1654 * Return the photo path for a given contact array
1656 * @param array $contact Contact array
1657 * @param bool $no_update Don't perfom an update if no cached avatar was found
1658 * @return string photo path
1660 public static function getPhoto(array $contact, bool $no_update = false): string
1662 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1666 * Return the photo path (thumb size) for a given contact array
1668 * @param array $contact Contact array
1669 * @param bool $no_update Don't perfom an update if no cached avatar was found
1670 * @return string photo path
1672 public static function getThumb(array $contact, bool $no_update = false): string
1674 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1678 * Return the photo path (micro size) for a given contact array
1680 * @param array $contact Contact array
1681 * @param bool $no_update Don't perfom an update if no cached avatar was found
1682 * @return string photo path
1684 public static function getMicro(array $contact, bool $no_update = false): string
1686 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1690 * Check the given contact array for avatar cache fields
1692 * @param array $contact
1693 * @param bool $no_update Don't perfom an update if no cached avatar was found
1694 * @return array contact array with avatar cache fields
1696 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1699 $contact_fields = [];
1700 $fields = ['photo', 'thumb', 'micro'];
1701 foreach ($fields as $field) {
1702 if (isset($contact[$field])) {
1703 $contact_fields[] = $field;
1705 if (isset($contact[$field]) && empty($contact[$field])) {
1710 if (!$update || $no_update) {
1714 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1716 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1717 self::updateAvatar($contact['id'], $contact['avatar'], true);
1719 $new_contact = self::getById($contact['id'], $contact_fields);
1720 if (DBA::isResult($new_contact)) {
1721 // We only update the cache fields
1722 $contact = array_merge($contact, $new_contact);
1724 } elseif ($local && !empty($contact['avatar'])) {
1728 /// add the default avatars if the fields aren't filled
1729 if (isset($contact['photo']) && empty($contact['photo'])) {
1730 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1732 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1733 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1735 if (isset($contact['micro']) && empty($contact['micro'])) {
1736 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1743 * Fetch the default header for the given contact
1745 * @param array $contact contact array
1746 * @return string avatar URL
1748 public static function getDefaultHeader(array $contact): string
1750 if (!empty($contact['header'])) {
1751 return $contact['header'];
1754 if (!empty($contact['gsid'])) {
1755 // Use default banners for certain platforms
1756 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1757 $platform = strtolower($gserver['platform'] ?? '');
1762 switch ($platform) {
1767 * @author Lostinlight <https://mastodon.xyz/@lightone>
1768 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1769 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1771 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1776 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1777 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1778 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1780 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1784 * Use a random picture.
1785 * The service provides random pictures from Unsplash.
1786 * @license https://unsplash.com/license
1788 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1796 * Fetch the default avatar for the given contact and size
1798 * @param array $contact contact array
1799 * @param string $size Size of the avatar picture
1800 * @return string avatar URL
1802 public static function getDefaultAvatar(array $contact, string $size): string
1805 case Proxy::SIZE_MICRO:
1806 $avatar['size'] = 48;
1807 $default = self::DEFAULT_AVATAR_MICRO;
1810 case Proxy::SIZE_THUMB:
1811 $avatar['size'] = 80;
1812 $default = self::DEFAULT_AVATAR_THUMB;
1815 case Proxy::SIZE_SMALL:
1817 $avatar['size'] = 300;
1818 $default = self::DEFAULT_AVATAR_PHOTO;
1822 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1824 $type = Contact::TYPE_PERSON;
1826 if (!empty($contact['id'])) {
1827 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1828 $platform = $account['platform'] ?? '';
1829 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1832 if (empty($platform) && !empty($contact['uri-id'])) {
1833 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1834 $platform = $account['platform'] ?? '';
1835 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1838 switch ($platform) {
1842 * @license GNU Affero General Public License v3.0
1843 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1845 $default = '/images/default/corgidon.png';
1851 * @license GNU Affero General Public License v3.0
1852 * @link https://github.com/diaspora/diaspora/
1854 $default = '/images/default/diaspora.png';
1860 * @license GNU Affero General Public License v3.0
1861 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1863 $default = '/images/default/gotosocial.svg';
1869 * @license GNU Affero General Public License v3.0
1870 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1872 $default = '/images/default/hometown.png';
1878 * @license GNU Affero General Public License v3.0
1879 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1881 $default = '/images/default/koyuspace.png';
1889 * @license GNU Affero General Public License v3.0
1890 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1892 $default = '/images/default/mastodon.png';
1896 if ($type == Contact::TYPE_COMMUNITY) {
1899 * @license GNU Affero General Public License v3.0
1900 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1902 $default = '/images/default/peertube-channel.png';
1906 * @license GNU Affero General Public License v3.0
1907 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1909 $default = '/images/default/peertube-account.png';
1916 * @license GNU Affero General Public License v3.0
1917 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
1919 $default = '/images/default/pleroma.png';
1925 * @license GNU Affero General Public License v3.0
1926 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
1928 $default = '/images/default/plume.png';
1931 return DI::baseUrl() . $default;
1934 if (!empty($contact['xmpp'])) {
1935 $avatar['email'] = $contact['xmpp'];
1936 } elseif (!empty($contact['addr'])) {
1937 $avatar['email'] = $contact['addr'];
1938 } elseif (!empty($contact['url'])) {
1939 $avatar['email'] = $contact['url'];
1941 return DI::baseUrl() . $default;
1944 $avatar['url'] = '';
1945 $avatar['success'] = false;
1947 Hook::callAll('avatar_lookup', $avatar);
1949 if ($avatar['success'] && !empty($avatar['url'])) {
1950 return $avatar['url'];
1953 return DI::baseUrl() . $default;
1957 * Get avatar link for given contact id
1959 * @param integer $cid contact id
1960 * @param string $size One of the Proxy::SIZE_* constants
1961 * @param string $updated Contact update date
1962 * @return string avatar link
1964 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
1966 // We have to fetch the "updated" variable when it wasn't provided
1967 // The parameter can be provided to improve performance
1968 if (empty($updated)) {
1969 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1970 $updated = $account['updated'] ?? '';
1971 $guid = $account['guid'] ?? '';
1974 $guid = urlencode($guid);
1976 $url = DI::baseUrl() . '/photo/contact/';
1978 case Proxy::SIZE_MICRO:
1979 $url .= Proxy::PIXEL_MICRO . '/';
1981 case Proxy::SIZE_THUMB:
1982 $url .= Proxy::PIXEL_THUMB . '/';
1984 case Proxy::SIZE_SMALL:
1985 $url .= Proxy::PIXEL_SMALL . '/';
1987 case Proxy::SIZE_MEDIUM:
1988 $url .= Proxy::PIXEL_MEDIUM . '/';
1990 case Proxy::SIZE_LARGE:
1991 $url .= Proxy::PIXEL_LARGE . '/';
1994 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1998 * Get avatar link for given contact URL
2000 * @param string $url contact url
2001 * @param integer $uid user id
2002 * @param string $size One of the Proxy::SIZE_* constants
2003 * @return string avatar link
2005 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2007 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2008 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2009 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2010 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2014 * Get header link for given contact id
2016 * @param integer $cid contact id
2017 * @param string $size One of the Proxy::SIZE_* constants
2018 * @param string $updated Contact update date
2019 * @return string header link
2021 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2023 // We have to fetch the "updated" variable when it wasn't provided
2024 // The parameter can be provided to improve performance
2025 if (empty($updated) || empty($guid)) {
2026 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2027 $updated = $account['updated'] ?? '';
2028 $guid = $account['guid'] ?? '';
2031 $guid = urlencode($guid);
2033 $url = DI::baseUrl() . '/photo/header/';
2035 case Proxy::SIZE_MICRO:
2036 $url .= Proxy::PIXEL_MICRO . '/';
2038 case Proxy::SIZE_THUMB:
2039 $url .= Proxy::PIXEL_THUMB . '/';
2041 case Proxy::SIZE_SMALL:
2042 $url .= Proxy::PIXEL_SMALL . '/';
2044 case Proxy::SIZE_MEDIUM:
2045 $url .= Proxy::PIXEL_MEDIUM . '/';
2047 case Proxy::SIZE_LARGE:
2048 $url .= Proxy::PIXEL_LARGE . '/';
2052 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2056 * Updates the avatar links in a contact only if needed
2058 * @param int $cid Contact id
2059 * @param string $avatar Link to avatar picture
2060 * @param bool $force force picture update
2061 * @param bool $create_cache Enforces the creation of cached avatar fields
2064 * @throws HTTPException\InternalServerErrorException
2065 * @throws HTTPException\NotFoundException
2066 * @throws \ImagickException
2068 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2070 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2071 ['id' => $cid, 'self' => false]);
2072 if (!DBA::isResult($contact)) {
2076 $uid = $contact['uid'];
2078 // Only update the cached photo links of public contacts when they already are cached
2079 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2080 if ($contact['avatar'] != $avatar) {
2081 self::update(['avatar' => $avatar], ['id' => $cid]);
2082 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2087 // User contacts use are updated through the public contacts
2088 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2089 $pcid = self::getIdForURL($contact['url'], 0, false);
2090 if (!empty($pcid)) {
2091 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2092 self::updateAvatar($pcid, $avatar, $force, true);
2097 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2099 if ($default_avatar) {
2100 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2103 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2105 // Local contact avatars don't need to be cached
2106 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2107 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2110 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2111 Avatar::deleteCache($contact);
2113 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2114 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2116 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2117 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2118 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2121 // Use the data from the self account
2122 if (empty($fields)) {
2123 $local_uid = User::getIdForURL($contact['url']);
2124 if (!empty($local_uid)) {
2125 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2126 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2130 if (empty($fields)) {
2131 $update = ($contact['avatar'] != $avatar) || $force;
2135 $contact['photo'] ?? '',
2136 $contact['thumb'] ?? '',
2137 $contact['micro'] ?? '',
2140 foreach ($data as $image_uri) {
2141 $image_rid = Photo::ridFromURI($image_uri);
2142 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2143 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2150 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2152 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2153 $update = !empty($fields);
2154 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2160 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2163 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2164 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2165 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2174 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2175 // Collect all user contacts of the given public contact
2176 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2177 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2178 while ($personal_contact = DBA::fetch($personal_contacts)) {
2179 $cids[] = $personal_contact['id'];
2180 $uids[] = $personal_contact['uid'];
2182 DBA::close($personal_contacts);
2184 if (!empty($cids)) {
2185 // Delete possibly existing cached user contact avatars
2186 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2192 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2193 self::update($fields, ['id' => $cids]);
2196 public static function deleteContactByUrl(string $url)
2198 // Update contact data for all users
2199 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2200 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2201 while ($contact = DBA::fetch($contacts)) {
2202 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2203 self::remove($contact['id']);
2208 * Helper function for "updateFromProbe". Updates personal and public contact
2210 * @param integer $id contact id
2211 * @param integer $uid user id
2212 * @param string $old_url The previous profile URL of the contact
2213 * @param string $new_url The profile URL of the contact
2214 * @param array $fields The fields that are updated
2216 * @throws \Exception
2218 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
2220 if (!self::update($fields, ['id' => $id])) {
2221 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2225 // Search for duplicated contacts and get rid of them
2226 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
2230 // Archive or unarchive the contact.
2231 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2232 if (!DBA::isResult($contact)) {
2233 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2237 if (isset($fields['failed'])) {
2238 if ($fields['failed']) {
2239 self::markForArchival($contact);
2241 self::unmarkForArchival($contact);
2245 if ($contact['uid'] != 0) {
2249 // Update contact data for all users
2250 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
2252 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2253 self::update($fields, $condition);
2255 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2256 $condition['network'] = Protocol::OSTATUS;
2258 // If the contact failed, propagate the update fields to all contacts
2259 if (empty($fields['failed'])) {
2260 unset($fields['last-update']);
2261 unset($fields['success_update']);
2262 unset($fields['failure_update']);
2265 if (empty($fields)) {
2269 self::update($fields, $condition);
2273 * Remove duplicated contacts
2275 * @param string $nurl Normalised contact url
2276 * @param integer $uid User id
2278 * @throws \Exception
2280 public static function removeDuplicates(string $nurl, int $uid)
2282 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2283 $count = DBA::count('contact', $condition);
2288 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2289 if (!DBA::isResult($first_contact)) {
2290 // Shouldn't happen - so we handle it
2294 $first = $first_contact['id'];
2295 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2296 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2297 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2298 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2302 // Find all duplicates
2303 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2304 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2305 while ($duplicate = DBA::fetch($duplicates)) {
2306 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2310 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2312 DBA::close($duplicates);
2313 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2318 * Updates contact record by provided id and optional network
2320 * @param integer $id contact id
2321 * @param string $network Optional network we are probing for
2323 * @throws HTTPException\InternalServerErrorException
2324 * @throws \ImagickException
2326 public static function updateFromProbe(int $id, string $network = '')
2328 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2329 if (!DBA::isResult($contact)) {
2333 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2335 if ($ret['network'] == Protocol::DIASPORA) {
2336 FContact::updateFromProbeArray($ret);
2339 return self::updateFromProbeArray($id, $ret);
2343 * Checks if the given contact has got local data
2346 * @param array $contact
2350 private static function hasLocalData(int $id, array $contact): bool
2352 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2353 // User contacts with the same uri-id exist
2355 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2356 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2359 if (DBA::exists('post-tag', ['cid' => $id])) {
2360 // Is tagged in a post
2363 if (DBA::exists('user-contact', ['cid' => $id])) {
2364 // Has got user-contact data
2367 if (Post::exists(['author-id' => $id])) {
2368 // Posts with this author exist
2371 if (Post::exists(['owner-id' => $id])) {
2372 // Posts with this owner exist
2375 if (Post::exists(['causer-id' => $id])) {
2376 // Posts with this causer exist
2379 // We don't have got this contact locally
2384 * Updates contact record by provided id and probed data
2386 * @param integer $id contact id
2387 * @param array $ret Probed data
2389 * @throws HTTPException\InternalServerErrorException
2390 * @throws \ImagickException
2392 private static function updateFromProbeArray(int $id, array $ret): bool
2395 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2396 This will reliably kill your communication with old Friendica contacts.
2399 // These fields aren't updated by this routine:
2402 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2403 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2404 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2405 'created', 'last-update'];
2406 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2407 if (!DBA::isResult($contact)) {
2411 if (self::isLocal($ret['url'])) {
2412 if ($contact['uid'] == 0) {
2413 Logger::info('Local contacts are not updated here.');
2415 self::updateFromPublicContact($id, $contact);
2420 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2421 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2424 // Delete all contacts with the same URL
2425 self::deleteContactByUrl($ret['url']);
2429 $uid = $contact['uid'];
2430 unset($contact['uid']);
2432 $uriid = $contact['uri-id'];
2433 unset($contact['uri-id']);
2435 $pubkey = $contact['pubkey'];
2436 unset($contact['pubkey']);
2438 $created = $contact['created'];
2439 unset($contact['created']);
2441 $last_update = $contact['last-update'];
2442 unset($contact['last-update']);
2444 $contact['photo'] = $contact['avatar'];
2445 unset($contact['avatar']);
2447 $updated = DateTimeFormat::utcNow();
2449 $has_local_data = self::hasLocalData($id, $contact);
2451 if (!in_array($ret['network'], array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM]))) {
2452 // Periodical checks are only done on federated contacts
2453 $failed_next_update = null;
2454 $success_next_update = null;
2455 } elseif ($has_local_data) {
2456 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2457 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2459 $failed_next_update = DateTimeFormat::utc('now +6 month');
2460 $success_next_update = DateTimeFormat::utc('now +1 month');
2463 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2464 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2465 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2469 // We must not try to update relay contacts via probe. They are no real contacts.
2470 // We check after the probing to be able to correct falsely detected contact types.
2471 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2472 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2473 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2474 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2478 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2479 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2480 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2484 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2485 $cid = self::getIdForURL($ret['url'], 0, false);
2486 if (!empty($cid) && ($cid != $id)) {
2487 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2488 return self::updateFromProbeArray($cid, $ret);
2492 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2493 $ret['unsearchable'] = $ret['hide'];
2496 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2497 $ret['forum'] = false;
2498 $ret['prv'] = false;
2499 $ret['contact-type'] = $ret['account-type'];
2500 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2501 $ret['forum'] = (bool)!$ret['manually-approve'];
2502 $ret['prv'] = (bool)!$ret['forum'];
2506 $new_pubkey = $ret['pubkey'] ?? '';
2508 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2509 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2510 $apcontact = APContact::getByURL($ret['url'], false);
2511 if (!empty($apcontact['featured'])) {
2512 Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2516 $ret['last-item'] = Probe::getLastUpdate($ret);
2517 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2521 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2523 // make sure to not overwrite existing values with blank entries except some technical fields
2524 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2525 foreach ($ret as $key => $val) {
2526 if (!array_key_exists($key, $contact)) {
2528 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2529 $ret[$key] = $contact[$key];
2530 } elseif ($ret[$key] != $contact[$key]) {
2535 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2538 unset($ret['last-item']);
2541 if (empty($uriid)) {
2545 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2546 self::updateAvatar($id, $ret['photo'], $update);
2549 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2552 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2554 if (Contact\Relation::isDiscoverable($ret['url'])) {
2555 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2558 // Update the public contact
2560 $contact = self::getByURL($ret['url'], false, ['id']);
2561 if (!empty($contact['id'])) {
2562 self::updateFromProbeArray($contact['id'], $ret);
2569 $ret['uri-id'] = $uriid;
2570 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2571 $ret['updated'] = $updated;
2572 $ret['failed'] = false;
2573 $ret['next-update'] = $success_next_update;
2574 $ret['local-data'] = $has_local_data;
2576 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2577 if (empty($pubkey) && !empty($new_pubkey)) {
2578 $ret['pubkey'] = $new_pubkey;
2581 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2582 $ret['uri-date'] = $updated;
2585 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2586 $ret['name-date'] = $updated;
2589 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2590 $ret['last-update'] = $updated;
2591 $ret['success_update'] = $updated;
2594 unset($ret['photo']);
2596 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2598 if (Contact\Relation::isDiscoverable($ret['url'])) {
2599 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2605 private static function updateFromPublicContact(int $id, array $contact)
2607 $public = self::getByURL($contact['url'], false);
2611 foreach ($contact as $field => $value) {
2612 if ($field == 'uid') {
2615 if ($public[$field] != $value) {
2616 $fields[$field] = $public[$field];
2619 if (!empty($fields)) {
2620 self::update($fields, ['id' => $id, 'self' => false]);
2621 Logger::info('Updating local contact', ['id' => $id]);
2626 * Updates contact record by provided URL
2628 * @param integer $url contact url
2629 * @return integer Contact id
2630 * @throws HTTPException\InternalServerErrorException
2631 * @throws \ImagickException
2633 public static function updateFromProbeByURL(string $url): int
2635 $id = self::getIdForURL($url);
2641 self::updateFromProbe($id);
2647 * Detects the communication protocol for a given contact url.
2648 * This is used to detect Friendica contacts that we can communicate via AP.
2650 * @param string $url contact url
2651 * @param string $network Network of that contact
2652 * @return string with protocol
2654 public static function getProtocol(string $url, string $network): string
2656 if ($network != Protocol::DFRN) {
2660 $apcontact = APContact::getByURL($url);
2661 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2662 return Protocol::ACTIVITYPUB;
2669 * Takes a $uid and a url/handle and adds a new contact
2671 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2672 * dfrn_request page.
2674 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2677 * $return['success'] boolean true if successful
2678 * $return['message'] error text if success is false.
2680 * Takes a $uid and a url/handle and adds a new contact
2682 * @param int $uid The user id the contact should be created for
2683 * @param string $url The profile URL of the contact
2684 * @param string $network
2686 * @throws HTTPException\InternalServerErrorException
2687 * @throws HTTPException\NotFoundException
2688 * @throws \ImagickException
2690 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2692 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2694 // remove ajax junk, e.g. Twitter
2695 $url = str_replace('/#!/', '/', $url);
2697 if (!Network::isUrlAllowed($url)) {
2698 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2702 if (Network::isUrlBlocked($url)) {
2703 $result['message'] = DI::l10n()->t('Blocked domain');
2708 $result['message'] = DI::l10n()->t('Connect URL missing.');
2712 $arr = ['url' => $url, 'contact' => []];
2714 Hook::callAll('follow', $arr);
2717 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2721 if (!empty($arr['contact']['name'])) {
2723 $ret = $arr['contact'];
2726 $ret = Probe::uri($url, $network, $uid);
2728 // Ensure that the public contact exists
2729 if ($ret['network'] != Protocol::PHANTOM) {
2730 self::getIdForURL($url);
2734 if (($network != '') && ($ret['network'] != $network)) {
2735 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2739 // check if we already have a contact
2740 // the poll url is more reliable than the profile url, as we may have
2741 // indirect links or webfinger links
2743 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2744 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2745 if (!DBA::isResult($contact)) {
2746 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2747 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2750 $protocol = self::getProtocol($ret['url'], $ret['network']);
2752 // This extra param just confuses things, remove it
2753 if ($protocol === Protocol::DIASPORA) {
2754 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2757 // do we have enough information?
2758 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2759 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2760 if (empty($ret['poll'])) {
2761 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2763 if (empty($ret['name'])) {
2764 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2766 if (empty($ret['url'])) {
2767 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2769 if (strpos($ret['url'], '@') !== false) {
2770 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2771 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2776 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2777 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2778 $ret['notify'] = '';
2781 if (!$ret['notify']) {
2782 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2785 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2787 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2789 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2792 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2793 $pending = (bool)$ret['manually-approve'];
2796 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2800 if (DBA::isResult($contact)) {
2802 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2804 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2805 self::update($fields, ['id' => $contact['id']]);
2807 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2809 // create contact record
2812 'created' => DateTimeFormat::utcNow(),
2813 'url' => $ret['url'],
2814 'nurl' => Strings::normaliseLink($ret['url']),
2815 'addr' => $ret['addr'],
2816 'alias' => $ret['alias'],
2817 'batch' => $ret['batch'],
2818 'notify' => $ret['notify'],
2819 'poll' => $ret['poll'],
2820 'poco' => $ret['poco'],
2821 'name' => $ret['name'],
2822 'nick' => $ret['nick'],
2823 'network' => $ret['network'],
2824 'baseurl' => $ret['baseurl'],
2825 'gsid' => $ret['gsid'] ?? null,
2826 'protocol' => $protocol,
2827 'pubkey' => $ret['pubkey'],
2828 'rel' => $new_relation,
2829 'priority'=> $ret['priority'],
2830 'writable'=> $writeable,
2831 'hidden' => $hidden,
2834 'pending' => $pending,
2839 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2840 if (!DBA::isResult($contact)) {
2841 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2845 $contact_id = $contact['id'];
2846 $result['cid'] = $contact_id;
2848 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2850 // Update the avatar
2851 self::updateAvatar($contact_id, $ret['photo']);
2853 // pull feed and consume it, which should subscribe to the hub.
2854 if ($contact['network'] == Protocol::OSTATUS) {
2855 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2859 self::updateFromProbeArray($contact_id, $ret);
2861 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2864 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2870 * @param array $importer Owner (local user) data
2871 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2872 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2873 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2874 * @param string $note Introduction additional message
2875 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2876 * @throws HTTPException\InternalServerErrorException
2877 * @throws \ImagickException
2879 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
2881 // Should always be set
2882 if (empty($datarray['author-id'])) {
2886 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2887 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2888 if (!DBA::isResult($pub_contact)) {
2889 // Should never happen
2893 // Contact is blocked at node-level
2894 if (self::isBlocked($datarray['author-id'])) {
2898 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2899 $name = $pub_contact['name'];
2900 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2901 $nick = $pub_contact['nick'];
2902 $network = $pub_contact['network'];
2904 // Ensure that we don't create a new contact when there already is one
2905 $cid = self::getIdForURL($url, $importer['uid']);
2907 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2910 self::clearFollowerFollowingEndpointCache($importer['uid']);
2912 if (!empty($contact)) {
2913 if (!empty($contact['pending'])) {
2914 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2918 // Contact is blocked at user-level
2919 if (!empty($contact['id']) && !empty($importer['id']) &&
2920 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2924 // Make sure that the existing contact isn't archived
2925 self::unmarkForArchival($contact);
2927 if (($contact['rel'] == self::SHARING)
2928 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2929 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2930 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2933 // Ensure to always have the correct network type, independent from the connection request method
2934 self::updateFromProbe($contact['id']);
2936 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2940 // send email notification to owner?
2941 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2942 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2946 // create contact record
2947 $contact_id = self::insert([
2948 'uid' => $importer['uid'],
2949 'created' => DateTimeFormat::utcNow(),
2951 'nurl' => Strings::normaliseLink($url),
2954 'network' => $network,
2955 'rel' => self::FOLLOWER,
2962 // Ensure to always have the correct network type, independent from the connection request method
2963 self::updateFromProbe($contact_id);
2965 self::updateAvatar($contact_id, $photo, true);
2967 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2969 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2971 /// @TODO Encapsulate this into a function/method
2972 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2973 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2974 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2975 // create notification
2976 if (is_array($contact_record)) {
2977 $intro = DI::introFactory()->createNew(
2979 $contact_record['id'],
2982 DI::intro()->save($intro);
2985 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
2987 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
2988 DI::notify()->createFromArray([
2989 'type' => Notification\Type::INTRO,
2990 'otype' => Notification\ObjectType::INTRO,
2991 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2992 'uid' => $user['uid'],
2993 'cid' => $contact_record['id'],
2994 'link' => DI::baseUrl() . '/notifications/intros',
2997 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2998 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2999 self::createFromProbeForUser($importer['uid'], $url, $network);
3002 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3003 $fields = ['pending' => false];
3004 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3005 $fields['rel'] = self::FRIEND;
3008 self::update($fields, $condition);
3018 * Update the local relationship when a local user loses a follower
3020 * @param array $contact User-specific contact (uid != 0) array
3022 * @throws HTTPException\InternalServerErrorException
3023 * @throws \ImagickException
3025 public static function removeFollower(array $contact)
3027 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3028 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3029 } elseif (!empty($contact['id'])) {
3030 self::remove($contact['id']);
3032 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3036 self::clearFollowerFollowingEndpointCache($contact['uid']);
3038 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3040 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3044 * Update the local relationship when a local user unfollow a contact.
3045 * Removes the contact for sharing-only protocols (feed and mail).
3047 * @param array $contact User-specific contact (uid != 0) array
3048 * @throws HTTPException\InternalServerErrorException
3050 public static function removeSharer(array $contact)
3052 self::clearFollowerFollowingEndpointCache($contact['uid']);
3054 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3055 self::remove($contact['id']);
3057 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3062 * Create a birthday event.
3064 * Update the year and the birthday.
3066 public static function updateBirthdays()
3070 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3071 AND NOT `contact`.`pending`
3072 AND NOT `contact`.`hidden`
3073 AND NOT `contact`.`blocked`
3074 AND NOT `contact`.`archive`
3075 AND NOT `contact`.`deleted`',
3081 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3083 while ($contact = DBA::fetch($contacts)) {
3084 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3086 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3088 if (Event::createBirthday($contact, $nextbd)) {
3092 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3093 ['id' => $contact['id']]
3097 DBA::close($contacts);
3101 * Remove the unavailable contact ids from the provided list
3103 * @param array $contact_ids Contact id list
3105 * @throws \Exception
3107 public static function pruneUnavailable(array $contact_ids): array
3109 if (empty($contact_ids)) {
3113 $contacts = self::selectToArray(['id'], [
3114 'id' => $contact_ids,
3120 return array_column($contacts, 'id');
3124 * Returns a magic link to authenticate remote visitors
3126 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3128 * @param string $contact_url The address of the target contact profile
3129 * @param string $url An url that we will be redirected to after the authentication
3131 * @return string with "redir" link
3132 * @throws HTTPException\InternalServerErrorException
3133 * @throws \ImagickException
3135 public static function magicLink(string $contact_url, string $url = ''): string
3137 if (!Session::isAuthenticated()) {
3138 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3141 $contact = self::getByURL($contact_url, false);
3142 if (empty($contact)) {
3143 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3146 // Prevents endless loop in case only a non-public contact exists for the contact URL
3147 unset($contact['uid']);
3149 return self::magicLinkByContact($contact, $url ?: $contact_url);
3153 * Returns a magic link to authenticate remote visitors
3155 * @param integer $cid The contact id of the target contact profile
3156 * @param string $url An url that we will be redirected to after the authentication
3158 * @return string with "redir" link
3159 * @throws HTTPException\InternalServerErrorException
3160 * @throws \ImagickException
3162 public static function magicLinkById(int $cid, string $url = ''): string
3164 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3166 return self::magicLinkByContact($contact, $url);
3170 * Returns a magic link to authenticate remote visitors
3172 * @param array $contact The contact array with "uid", "network" and "url"
3173 * @param string $url An url that we will be redirected to after the authentication
3175 * @return string with "redir" link
3176 * @throws HTTPException\InternalServerErrorException
3177 * @throws \ImagickException
3179 public static function magicLinkByContact(array $contact, string $url = ''): string
3181 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3183 if (!Session::isAuthenticated()) {
3184 return $destination;
3187 // Only redirections to the same host do make sense
3188 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3192 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3193 return 'contact/' . $contact['id'] . '/conversations';
3196 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3197 return $destination;
3200 if (empty($contact['id'])) {
3201 return $destination;
3204 $redirect = 'redir/' . $contact['id'];
3206 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3207 $redirect .= '?url=' . $url;
3214 * Is the contact a forum?
3216 * @param integer $contactid ID of the contact
3218 * @return boolean "true" if it is a forum
3220 public static function isForum(int $contactid): bool
3222 $fields = ['contact-type'];
3223 $condition = ['id' => $contactid];
3224 $contact = DBA::selectFirst('contact', $fields, $condition);
3225 if (!DBA::isResult($contact)) {
3230 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3234 * Can the remote contact receive private messages?
3236 * @param array $contact
3239 public static function canReceivePrivateMessages(array $contact): bool
3241 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3242 $self = $contact['self'] ?? false;
3244 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3248 * Search contact table by nick or name
3250 * @param string $search Name or nick
3251 * @param string $mode Search mode (e.g. "community")
3252 * @param int $uid User ID
3254 * @return array with search results
3255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3257 public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3259 if (empty($search)) {
3263 // check supported networks
3264 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3265 if (DI::config()->get('system', 'diaspora_enabled')) {
3266 $networks[] = Protocol::DIASPORA;
3269 if (!DI::config()->get('system', 'ostatus_disabled')) {
3270 $networks[] = Protocol::OSTATUS;
3273 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3276 $condition['blocked'] = false;
3279 // check if we search only communities or every contact
3280 if ($mode === 'community') {
3281 $condition['contact-type'] = self::TYPE_COMMUNITY;
3286 $condition = DBA::mergeConditions($condition,
3287 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3288 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3290 $contacts = self::selectToArray([], $condition);
3295 * Add public contacts from an array
3297 * @param array $urls
3298 * @return array result "count", "added" and "updated"
3300 public static function addByUrls(array $urls): array
3307 foreach ($urls as $url) {
3308 if (empty($url) || !is_string($url)) {
3311 $contact = self::getByURL($url, false, ['id', 'updated']);
3312 if (empty($contact['id'])) {
3313 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3315 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3316 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3324 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3328 * Returns a random, global contact array of the current node
3330 * @return array The profile array
3333 public static function getRandomContact(): array
3335 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3336 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3337 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3338 ], ['order' => ['RAND()']]);
3340 if (DBA::isResult($contact)) {