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
332 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
334 * @return boolean is the contact id a follower?
335 * @throws HTTPException\InternalServerErrorException
336 * @throws \ImagickException
338 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
340 if (Contact\User::isBlocked($cid, $uid)) {
344 $cdata = self::getPublicAndUserContactID($cid, $uid);
345 if (empty($cdata['user'])) {
349 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
351 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
353 return DBA::exists('contact', $condition);
357 * Tests if the given contact url is a follower
359 * @param string $url Contact URL
360 * @param int $uid User ID
361 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
363 * @return boolean is the contact id a follower?
364 * @throws HTTPException\InternalServerErrorException
365 * @throws \ImagickException
367 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
369 $cid = self::getIdForURL($url, $uid);
375 return self::isFollower($cid, $uid, $strict);
379 * Tests if the given user shares with the given contact
381 * @param int $cid Either public contact id or user's contact id
382 * @param int $uid User ID
383 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
385 * @return boolean is the contact sharing with given user?
386 * @throws HTTPException\InternalServerErrorException
387 * @throws \ImagickException
389 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
391 if (Contact\User::isBlocked($cid, $uid)) {
395 $cdata = self::getPublicAndUserContactID($cid, $uid);
396 if (empty($cdata['user'])) {
400 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
402 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
404 return DBA::exists('contact', $condition);
408 * Tests if the given user follow the given contact url
410 * @param string $url Contact URL
411 * @param int $uid User ID
412 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
414 * @return boolean is the contact url being followed?
415 * @throws HTTPException\InternalServerErrorException
416 * @throws \ImagickException
418 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
420 $cid = self::getIdForURL($url, $uid);
426 return self::isSharing($cid, $uid, $strict);
430 * Get the basepath for a given contact link
432 * @param string $url The contact link
433 * @param boolean $dont_update Don't update the contact
435 * @return string basepath
436 * @throws HTTPException\InternalServerErrorException
437 * @throws \ImagickException
439 public static function getBasepath(string $url, bool $dont_update = false): string
441 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
442 if (!DBA::isResult($contact)) {
446 if (!empty($contact['baseurl'])) {
447 return $contact['baseurl'];
448 } elseif ($dont_update) {
452 // Update the existing contact
453 self::updateFromProbe($contact['id']);
455 // And fetch the result
456 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
457 if (empty($contact['baseurl'])) {
458 Logger::info('No baseurl for contact', ['url' => $url]);
462 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
463 return $contact['baseurl'];
467 * Check if the given contact url is on the same server
469 * @param string $url The contact link
471 * @return boolean Is it the same server?
473 public static function isLocal(string $url): bool
475 if (!parse_url($url, PHP_URL_SCHEME)) {
476 $addr_parts = explode('@', $url);
477 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
480 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
484 * Check if the given contact ID is on the same server
486 * @param string $url The contact link
487 * @return boolean Is it the same server?
489 public static function isLocalById(int $cid): bool
491 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
492 if (!DBA::isResult($contact)) {
496 if (empty($contact['baseurl'])) {
497 $baseurl = self::getBasepath($contact['url'], true);
499 $baseurl = $contact['baseurl'];
502 return Strings::compareLink($baseurl, DI::baseUrl());
506 * Returns the public contact id of the given user id
508 * @param integer $uid User ID
510 * @return integer|boolean Public contact id for given user id
513 public static function getPublicIdByUserId(int $uid)
515 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
516 if (!DBA::isResult($self)) {
519 return self::getIdForURL($self['url']);
523 * Returns the contact id for the user and the public contact id for a given contact id
525 * @param int $cid Either public contact id or user's contact id
526 * @param int $uid User ID
528 * @return array with public and user's contact id
529 * @throws HTTPException\InternalServerErrorException
530 * @throws \ImagickException
532 public static function getPublicAndUserContactID(int $cid, int $uid): array
534 // We have to use the legacy function as long as the post update hasn't finished
535 if (DI::config()->get('system', 'post_update_version') < 1427) {
536 return self::legacyGetPublicAndUserContactID($cid, $uid);
539 if (empty($uid) || empty($cid)) {
543 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
544 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
548 $pcid = $contact['pid'];
549 if ($contact['uid'] == $uid) {
550 $ucid = $contact['id'];
552 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
553 if (DBA::isResult($contact)) {
554 $ucid = $contact['id'];
560 return ['public' => $pcid, 'user' => $ucid];
564 * Helper function for "getPublicAndUserContactID"
566 * @param int $cid Either public contact id or user's contact id
567 * @param int $uid User ID
568 * @return array with public and user's contact id
569 * @throws HTTPException\InternalServerErrorException
570 * @throws \ImagickException
572 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
574 if (empty($uid) || empty($cid)) {
578 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
579 if (!DBA::isResult($contact)) {
583 // We quit when the user id don't match the user id of the provided contact
584 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
588 if ($contact['uid'] != 0) {
589 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
593 $ucid = $contact['id'];
595 $pcid = $contact['id'];
596 $ucid = self::getIdForURL($contact['url'], $uid);
599 return ['public' => $pcid, 'user' => $ucid];
603 * Returns contact details for a given contact id in combination with a user id
605 * @param int $cid A contact ID
606 * @param int $uid The User ID
607 * @param array $fields The selected fields for the contact
608 * @return array The contact details
612 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
614 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
616 if (!DBA::isResult($contact)) {
624 * Creates the self-contact for the provided user id
627 * @return bool Operation success
628 * @throws HTTPException\InternalServerErrorException
630 public static function createSelfFromUserId(int $uid): bool
632 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
633 ['uid' => $uid, 'account_expired' => false]);
634 if (!DBA::isResult($user)) {
639 'uid' => $user['uid'],
640 'created' => DateTimeFormat::utcNow(),
642 'name' => $user['username'],
643 'nick' => $user['nickname'],
644 'pubkey' => $user['pubkey'],
645 'prvkey' => $user['prvkey'],
646 'photo' => User::getAvatarUrl($user),
647 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
648 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
651 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
652 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
653 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
654 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
655 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
656 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
657 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
658 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
659 'name-date' => DateTimeFormat::utcNow(),
660 'uri-date' => DateTimeFormat::utcNow(),
661 'avatar-date' => DateTimeFormat::utcNow(),
667 // Only create the entry if it doesn't exist yet
668 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
669 $return = (bool)self::insert($contact);
672 // Create the public contact
673 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
674 $contact['self'] = false;
676 $contact['prvkey'] = null;
678 self::insert($contact, Database::INSERT_IGNORE);
685 * Updates the self-contact for the provided user id
688 * @param bool $update_avatar Force the avatar update
689 * @return bool "true" if updated
690 * @throws HTTPException\InternalServerErrorException
692 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
694 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
695 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
696 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
697 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
698 if (!DBA::isResult($self)) {
702 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
703 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
704 if (!DBA::isResult($user)) {
708 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
709 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
710 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
711 if (!DBA::isResult($profile)) {
715 $file_suffix = 'jpg';
716 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
719 'name' => $profile['name'],
720 'nick' => $user['nickname'],
721 'avatar-date' => $self['avatar-date'],
722 'location' => Profile::formatLocation($profile),
723 'about' => $profile['about'],
724 'keywords' => $profile['pub_keywords'],
725 'contact-type' => $user['account-type'],
726 'prvkey' => $user['prvkey'],
727 'pubkey' => $user['pubkey'],
728 'xmpp' => $profile['xmpp'],
729 'matrix' => $profile['matrix'],
730 'network' => Protocol::DFRN,
732 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
733 'nurl' => Strings::normaliseLink($url),
734 'uri-id' => ItemURI::getIdByURI($url),
735 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
736 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
737 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
738 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
739 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
740 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
744 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
745 if (DBA::isResult($avatar)) {
746 if ($update_avatar) {
747 $fields['avatar-date'] = DateTimeFormat::utcNow();
750 // Creating the path to the avatar, beginning with the file suffix
751 $types = Images::supportedTypes();
752 if (isset($types[$avatar['type']])) {
753 $file_suffix = $types[$avatar['type']];
756 // We are adding a timestamp value so that other systems won't use cached content
757 $timestamp = strtotime($fields['avatar-date']);
759 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
760 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
762 $fields['photo'] = $prefix . '4' . $suffix;
763 $fields['thumb'] = $prefix . '5' . $suffix;
764 $fields['micro'] = $prefix . '6' . $suffix;
766 // We hadn't found a photo entry, so we use the default avatar
767 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
768 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
769 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
772 $fields['avatar'] = User::getAvatarUrl($user);
773 $fields['header'] = User::getBannerUrl($user);
774 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
775 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
776 $fields['unsearchable'] = !$profile['net-publish'];
777 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
781 foreach ($fields as $field => $content) {
782 if ($self[$field] != $content) {
788 if ($fields['name'] != $self['name']) {
789 $fields['name-date'] = DateTimeFormat::utcNow();
791 $fields['updated'] = DateTimeFormat::utcNow();
792 self::update($fields, ['id' => $self['id']]);
794 // Update the other contacts as well
795 unset($fields['prvkey']);
796 $fields['self'] = false;
797 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
799 // Update the profile
801 'photo' => User::getAvatarUrl($user),
802 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
805 DBA::update('profile', $fields, ['uid' => $uid]);
812 * Marks a contact for removal
814 * @param int $id contact id
816 * @throws HTTPException\InternalServerErrorException
818 public static function remove(int $id)
820 // We want just to make sure that we don't delete our "self" contact
821 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
822 if (!DBA::isResult($contact)) {
826 self::clearFollowerFollowingEndpointCache($contact['uid']);
828 // Archive the contact
829 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
831 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
832 Avatar::deleteCache($contact);
835 // Delete it in the background
836 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
840 * Unfollow the remote contact
842 * @param array $contact Target user-specific contact (uid != 0) array
844 * @throws HTTPException\InternalServerErrorException
845 * @throws \ImagickException
847 public static function unfollow(array $contact): void
849 if (empty($contact['network'])) {
850 throw new \InvalidArgumentException('Empty network in contact array');
853 if (empty($contact['uid'])) {
854 throw new \InvalidArgumentException('Unexpected public contact record');
857 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
858 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
859 if (!empty($cdata['public'])) {
860 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
864 self::removeSharer($contact);
868 * Revoke follow privileges of the remote user contact
870 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
872 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
874 * @throws HTTPException\InternalServerErrorException
875 * @throws \ImagickException
877 public static function revokeFollow(array $contact): void
879 if (empty($contact['network'])) {
880 throw new \InvalidArgumentException('Empty network in contact array');
883 if (empty($contact['uid'])) {
884 throw new \InvalidArgumentException('Unexpected public contact record');
887 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
888 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
889 if (!empty($cdata['public'])) {
890 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
894 self::removeFollower($contact);
898 * Completely severs a relationship with a contact
900 * @param array $contact User-specific contact (uid != 0) array
902 * @throws HTTPException\InternalServerErrorException
903 * @throws \ImagickException
905 public static function terminateFriendship(array $contact)
907 if (empty($contact['network'])) {
908 throw new \InvalidArgumentException('Empty network in contact array');
911 if (empty($contact['uid'])) {
912 throw new \InvalidArgumentException('Unexpected public contact record');
915 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
917 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
918 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
921 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
922 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
925 self::remove($contact['id']);
928 private static function clearFollowerFollowingEndpointCache(int $uid)
934 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
935 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
936 DI::cache()->delete(NoScrape::CACHEKEY . $uid);
940 * Marks a contact for archival after a communication issue delay
942 * Contact has refused to recognise us as a friend. We will start a countdown.
943 * If they still don't recognise us in 32 days, the relationship is over,
944 * and we won't waste any more time trying to communicate with them.
945 * This provides for the possibility that their database is temporarily messed
946 * up or some other transient event and that there's a possibility we could recover from it.
948 * @param array $contact contact to mark for archival
950 * @throws HTTPException\InternalServerErrorException
952 public static function markForArchival(array $contact)
954 if (!isset($contact['url']) && !empty($contact['id'])) {
955 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
956 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
957 if (!DBA::isResult($contact)) {
960 } elseif (!isset($contact['url'])) {
961 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
964 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
966 // Contact already archived or "self" contact? => nothing to do
967 if ($contact['archive'] || $contact['self']) {
971 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
972 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
973 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
976 * We really should send a notification to the owner after 2-3 weeks
977 * so they won't be surprised when the contact vanishes and can take
978 * remedial action if this was a serious mistake or glitch
981 /// @todo Check for contact vitality via probing
982 $archival_days = DI::config()->get('system', 'archival_days', 32);
984 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
985 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
986 /* Relationship is really truly dead. archive them rather than
987 * delete, though if the owner tries to unarchive them we'll start
988 * the whole process over again.
990 self::update(['archive' => true], ['id' => $contact['id']]);
991 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
997 * Cancels the archival countdown
999 * @see Contact::markForArchival()
1001 * @param array $contact contact to be unmarked for archival
1003 * @throws \Exception
1005 public static function unmarkForArchival(array $contact)
1007 // Always unarchive the relay contact entry
1008 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1009 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1010 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1011 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1012 self::update($fields, $condition);
1016 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1017 $exists = DBA::exists('contact', $condition);
1019 // We don't need to update, we never marked this contact for archival
1024 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1026 if (!isset($contact['url']) && !empty($contact['id'])) {
1027 $fields = ['id', 'url', 'batch'];
1028 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1029 if (!DBA::isResult($contact)) {
1034 // It's a miracle. Our dead contact has inexplicably come back to life.
1035 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1036 self::update($fields, ['id' => $contact['id']]);
1037 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1041 * Returns the data array for the photo menu of a given contact
1043 * @param array $contact contact
1044 * @param int $uid optional, default 0
1046 * @throws HTTPException\InternalServerErrorException
1047 * @throws \ImagickException
1049 public static function photoMenu(array $contact, int $uid = 0): array
1056 $uid = local_user();
1059 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1061 $profile_link = self::magicLinkByContact($contact);
1062 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1067 // Look for our own contact if the uid doesn't match and isn't public
1068 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1069 if (DBA::isResult($contact_own)) {
1070 return self::photoMenu($contact_own, $uid);
1075 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1077 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1079 $profile_link = $contact['url'];
1082 if ($profile_link === 'mailbox') {
1087 $status_link = $profile_link . '/status';
1088 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1089 $profile_link = $profile_link . '/profile';
1092 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1093 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1096 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1098 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1101 $unfollow_link = '';
1102 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1103 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1104 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1105 } elseif(!$contact['pending']) {
1106 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1112 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1114 if (empty($contact['uid'])) {
1116 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1117 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1118 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1119 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1120 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1124 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1125 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1126 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1127 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1128 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1129 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1130 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1131 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1134 if (!empty($contact['pending'])) {
1136 $intro = DI::intro()->selectForContact($contact['id']);
1137 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1138 } catch (IntroductionNotFoundException $exception) {
1139 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1144 $args = ['contact' => $contact, 'menu' => &$menu];
1146 Hook::callAll('contact_photo_menu', $args);
1148 $menucondensed = [];
1150 foreach ($menu as $menuname => $menuitem) {
1151 if ($menuitem[1] != '') {
1152 $menucondensed[$menuname] = $menuitem;
1156 return $menucondensed;
1160 * Fetch the contact id for a given URL and user
1162 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1163 * `addr` or `alias`.
1165 * If there's no record and we aren't looking for a public contact, we quit.
1166 * If there's one, we check that it isn't time to update the picture else we
1167 * directly return the found contact id.
1169 * Second, we probe the provided $url whether it's http://server.tld/profile or
1170 * nick@server.tld. We quit if we can't get any info back.
1172 * Third, we create the contact record if it doesn't exist
1174 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1175 * if there's any updates
1177 * @param string $url Contact URL
1178 * @param integer $uid The user id for the contact (0 = public contact)
1179 * @param boolean $update true = always update, false = never update, null = update when not found
1180 * @param array $default Default value for creating the contact when everything else fails
1182 * @return integer Contact ID
1183 * @throws HTTPException\InternalServerErrorException
1184 * @throws \ImagickException
1186 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1191 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1195 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1197 if (!empty($contact)) {
1198 $contact_id = $contact['id'];
1200 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1201 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1204 } elseif ($uid != 0) {
1205 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1207 } elseif (empty($default) && !is_null($update) && !$update) {
1208 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1214 if (empty($default['network']) || $update) {
1215 $data = Probe::uri($url, '', $uid);
1217 // Take the default values when probing failed
1218 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1219 $data = array_merge($data, $default);
1221 } elseif (!empty($default['network'])) {
1225 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1226 // Fetch data for the public contact via the first found personal contact
1227 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1228 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1229 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1230 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1232 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1233 if (!DBA::isResult($personal_contact)) {
1234 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1237 if (DBA::isResult($personal_contact)) {
1238 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1239 $data = $personal_contact;
1240 $data['photo'] = $personal_contact['avatar'];
1241 $data['account-type'] = $personal_contact['contact-type'];
1242 $data['hide'] = $personal_contact['unsearchable'];
1243 unset($data['avatar']);
1244 unset($data['contact-type']);
1245 unset($data['unsearchable']);
1249 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1250 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1255 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1256 if (!empty($data['alias'])) {
1257 $urls[] = Strings::normaliseLink($data['alias']);
1259 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1260 if (!empty($contact['id'])) {
1261 $contact_id = $contact['id'];
1262 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1267 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1270 'url' => $data['url'],
1271 'nurl' => Strings::normaliseLink($data['url']),
1272 'network' => $data['network'],
1273 'created' => DateTimeFormat::utcNow(),
1274 'rel' => self::SHARING,
1280 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1282 // Before inserting we do check if the entry does exist now.
1283 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1284 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1285 if (DBA::isResult($contact)) {
1286 $contact_id = $contact['id'];
1287 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1289 $contact_id = self::insert($fields);
1291 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1294 DI::lock()->release(self::LOCK_INSERT);
1296 Logger::warning('Contact lock had not been acquired');
1300 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1304 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1307 if ($data['network'] == Protocol::DIASPORA) {
1308 FContact::updateFromProbeArray($data);
1311 self::updateFromProbeArray($contact_id, $data);
1313 // Don't return a number for a deleted account
1314 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1315 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1323 * Checks if the contact is archived
1325 * @param int $cid contact id
1327 * @return boolean Is the contact archived?
1328 * @throws HTTPException\InternalServerErrorException
1330 public static function isArchived(int $cid): bool
1336 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1337 if (!DBA::isResult($contact)) {
1341 if ($contact['archive']) {
1345 // Check status of ActivityPub endpoints
1346 $apcontact = APContact::getByURL($contact['url'], false);
1347 if (!empty($apcontact)) {
1348 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1352 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1357 // Check status of Diaspora endpoints
1358 if (!empty($contact['batch'])) {
1359 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1360 return DBA::exists('contact', $condition);
1367 * Checks if the contact is blocked
1369 * @param int $cid contact id
1370 * @return boolean Is the contact blocked?
1371 * @throws HTTPException\InternalServerErrorException
1373 public static function isBlocked(int $cid): bool
1379 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1380 if (!DBA::isResult($blocked)) {
1384 if (Network::isUrlBlocked($blocked['url'])) {
1388 return (bool) $blocked['blocked'];
1392 * Checks if the contact is hidden
1394 * @param int $cid contact id
1395 * @return boolean Is the contact hidden?
1396 * @throws \Exception
1398 public static function isHidden(int $cid): bool
1404 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1405 if (!DBA::isResult($hidden)) {
1408 return (bool) $hidden['hidden'];
1412 * Returns posts from a given contact url
1414 * @param string $contact_url Contact URL
1415 * @param bool $thread_mode
1416 * @param int $update Update mode
1417 * @param int $parent Item parent ID for the update mode
1418 * @param bool $only_media Only display media content
1419 * @return string posts in HTML
1420 * @throws \Exception
1422 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1424 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1428 * Returns posts from a given contact id
1430 * @param int $cid Contact ID
1431 * @param bool $thread_mode
1432 * @param int $update Update mode
1433 * @param int $parent Item parent ID for the update mode
1434 * @param bool $only_media Only display media content
1435 * @return string posts in HTML
1436 * @throws \Exception
1438 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1440 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1441 if (!DBA::isResult($contact)) {
1445 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1446 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1451 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1454 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1455 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1457 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1458 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1461 if (!empty($parent)) {
1462 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1464 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1465 if (!empty($last_received)) {
1466 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1471 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1472 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1475 if (DI::mode()->isMobile()) {
1476 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1477 DI::config()->get('system', 'itemspage_network_mobile'));
1479 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1480 DI::config()->get('system', 'itemspage_network'));
1483 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1485 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1487 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1488 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1489 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1495 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1496 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1498 if ($pager->getStart() == 0) {
1499 $cdata = self::getPublicAndUserContactID($cid, local_user());
1500 if (!empty($cdata['public'])) {
1501 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1502 $items = array_merge($items, $pinned);
1506 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
1508 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1509 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1511 if ($pager->getStart() == 0) {
1512 $cdata = self::getPublicAndUserContactID($cid, local_user());
1513 if (!empty($cdata['public'])) {
1514 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1515 $cdata['public'], Post\Collection::FEATURED];
1516 $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1517 $items = array_merge($pinned, $items);
1521 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1525 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1526 $o .= HTML::scrollLoader();
1528 $o .= $pager->renderMinimal(count($items));
1536 * Returns the account type name
1538 * The function can be called with either the user or the contact array
1540 * @param int $type type of contact or account
1543 public static function getAccountType(int $type): string
1546 case self::TYPE_ORGANISATION:
1547 $account_type = DI::l10n()->t("Organisation");
1550 case self::TYPE_NEWS:
1551 $account_type = DI::l10n()->t('News');
1554 case self::TYPE_COMMUNITY:
1555 $account_type = DI::l10n()->t("Forum");
1563 return $account_type;
1569 * @param int $cid Contact id to block
1570 * @param string $reason Block reason
1571 * @return bool Whether it was successful
1573 public static function block(int $cid, string $reason = null): bool
1575 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1581 * Unblocks a contact
1583 * @param int $cid Contact id to unblock
1584 * @return bool Whether it was successfull
1586 public static function unblock(int $cid): bool
1588 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1594 * Ensure that cached avatar exist
1596 * @param integer $cid Contact id
1598 public static function checkAvatarCache(int $cid)
1600 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1601 if (!DBA::isResult($contact)) {
1605 if (Network::isLocalLink($contact['url'])) {
1609 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1610 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1611 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1612 self::updateAvatar($cid, $contact['avatar'], true);
1615 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1616 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1617 self::updateAvatar($cid, $contact['avatar'], true);
1619 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1620 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1621 self::updateAvatar($cid, $contact['avatar'], true);
1627 * Return the photo path for a given contact array in the given size
1629 * @param array $contact contact array
1630 * @param string $field Fieldname of the photo in the contact array
1631 * @param string $size Size of the avatar picture
1632 * @param string $avatar Avatar path that is displayed when no photo had been found
1633 * @param bool $no_update Don't perfom an update if no cached avatar was found
1634 * @return string photo path
1636 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1638 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1640 if (DI::config()->get('system', 'avatar_cache')) {
1642 case Proxy::SIZE_MICRO:
1643 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1644 return $contact['micro'];
1647 case Proxy::SIZE_THUMB:
1648 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1649 return $contact['thumb'];
1652 case Proxy::SIZE_SMALL:
1653 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1654 return $contact['photo'];
1660 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1664 * Return the photo path for a given contact array
1666 * @param array $contact Contact array
1667 * @param bool $no_update Don't perfom an update if no cached avatar was found
1668 * @return string photo path
1670 public static function getPhoto(array $contact, bool $no_update = false): string
1672 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1676 * Return the photo path (thumb size) for a given contact array
1678 * @param array $contact Contact array
1679 * @param bool $no_update Don't perfom an update if no cached avatar was found
1680 * @return string photo path
1682 public static function getThumb(array $contact, bool $no_update = false): string
1684 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1688 * Return the photo path (micro size) for a given contact array
1690 * @param array $contact Contact array
1691 * @param bool $no_update Don't perfom an update if no cached avatar was found
1692 * @return string photo path
1694 public static function getMicro(array $contact, bool $no_update = false): string
1696 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1700 * Check the given contact array for avatar cache fields
1702 * @param array $contact
1703 * @param bool $no_update Don't perfom an update if no cached avatar was found
1704 * @return array contact array with avatar cache fields
1706 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1709 $contact_fields = [];
1710 $fields = ['photo', 'thumb', 'micro'];
1711 foreach ($fields as $field) {
1712 if (isset($contact[$field])) {
1713 $contact_fields[] = $field;
1715 if (isset($contact[$field]) && empty($contact[$field])) {
1720 if (!$update || $no_update) {
1724 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1726 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1727 self::updateAvatar($contact['id'], $contact['avatar'], true);
1729 $new_contact = self::getById($contact['id'], $contact_fields);
1730 if (DBA::isResult($new_contact)) {
1731 // We only update the cache fields
1732 $contact = array_merge($contact, $new_contact);
1734 } elseif ($local && !empty($contact['avatar'])) {
1738 /// add the default avatars if the fields aren't filled
1739 if (isset($contact['photo']) && empty($contact['photo'])) {
1740 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1742 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1743 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1745 if (isset($contact['micro']) && empty($contact['micro'])) {
1746 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1753 * Fetch the default header for the given contact
1755 * @param array $contact contact array
1756 * @return string avatar URL
1758 public static function getDefaultHeader(array $contact): string
1760 if (!empty($contact['header'])) {
1761 return $contact['header'];
1764 if (!empty($contact['gsid'])) {
1765 // Use default banners for certain platforms
1766 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1767 $platform = strtolower($gserver['platform'] ?? '');
1772 switch ($platform) {
1777 * @author Lostinlight <https://mastodon.xyz/@lightone>
1778 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1779 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1781 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1786 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1787 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1788 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1790 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1794 * Use a random picture.
1795 * The service provides random pictures from Unsplash.
1796 * @license https://unsplash.com/license
1798 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1806 * Fetch the default avatar for the given contact and size
1808 * @param array $contact contact array
1809 * @param string $size Size of the avatar picture
1810 * @return string avatar URL
1812 public static function getDefaultAvatar(array $contact, string $size): string
1815 case Proxy::SIZE_MICRO:
1816 $avatar['size'] = 48;
1817 $default = self::DEFAULT_AVATAR_MICRO;
1820 case Proxy::SIZE_THUMB:
1821 $avatar['size'] = 80;
1822 $default = self::DEFAULT_AVATAR_THUMB;
1825 case Proxy::SIZE_SMALL:
1827 $avatar['size'] = 300;
1828 $default = self::DEFAULT_AVATAR_PHOTO;
1832 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1834 $type = Contact::TYPE_PERSON;
1836 if (!empty($contact['id'])) {
1837 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1838 $platform = $account['platform'] ?? '';
1839 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1842 if (empty($platform) && !empty($contact['uri-id'])) {
1843 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1844 $platform = $account['platform'] ?? '';
1845 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1848 switch ($platform) {
1852 * @license GNU Affero General Public License v3.0
1853 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1855 $default = '/images/default/corgidon.png';
1861 * @license GNU Affero General Public License v3.0
1862 * @link https://github.com/diaspora/diaspora/
1864 $default = '/images/default/diaspora.png';
1870 * @license GNU Affero General Public License v3.0
1871 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1873 $default = '/images/default/gotosocial.svg';
1879 * @license GNU Affero General Public License v3.0
1880 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1882 $default = '/images/default/hometown.png';
1888 * @license GNU Affero General Public License v3.0
1889 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1891 $default = '/images/default/koyuspace.png';
1899 * @license GNU Affero General Public License v3.0
1900 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1902 $default = '/images/default/mastodon.png';
1906 if ($type == Contact::TYPE_COMMUNITY) {
1909 * @license GNU Affero General Public License v3.0
1910 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1912 $default = '/images/default/peertube-channel.png';
1916 * @license GNU Affero General Public License v3.0
1917 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1919 $default = '/images/default/peertube-account.png';
1926 * @license GNU Affero General Public License v3.0
1927 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
1929 $default = '/images/default/pleroma.png';
1935 * @license GNU Affero General Public License v3.0
1936 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
1938 $default = '/images/default/plume.png';
1941 return DI::baseUrl() . $default;
1944 if (!empty($contact['xmpp'])) {
1945 $avatar['email'] = $contact['xmpp'];
1946 } elseif (!empty($contact['addr'])) {
1947 $avatar['email'] = $contact['addr'];
1948 } elseif (!empty($contact['url'])) {
1949 $avatar['email'] = $contact['url'];
1951 return DI::baseUrl() . $default;
1954 $avatar['url'] = '';
1955 $avatar['success'] = false;
1957 Hook::callAll('avatar_lookup', $avatar);
1959 if ($avatar['success'] && !empty($avatar['url'])) {
1960 return $avatar['url'];
1963 return DI::baseUrl() . $default;
1967 * Get avatar link for given contact id
1969 * @param integer $cid contact id
1970 * @param string $size One of the Proxy::SIZE_* constants
1971 * @param string $updated Contact update date
1972 * @return string avatar link
1974 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
1976 // We have to fetch the "updated" variable when it wasn't provided
1977 // The parameter can be provided to improve performance
1978 if (empty($updated)) {
1979 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1980 $updated = $account['updated'] ?? '';
1981 $guid = $account['guid'] ?? '';
1984 $guid = urlencode($guid);
1986 $url = DI::baseUrl() . '/photo/contact/';
1988 case Proxy::SIZE_MICRO:
1989 $url .= Proxy::PIXEL_MICRO . '/';
1991 case Proxy::SIZE_THUMB:
1992 $url .= Proxy::PIXEL_THUMB . '/';
1994 case Proxy::SIZE_SMALL:
1995 $url .= Proxy::PIXEL_SMALL . '/';
1997 case Proxy::SIZE_MEDIUM:
1998 $url .= Proxy::PIXEL_MEDIUM . '/';
2000 case Proxy::SIZE_LARGE:
2001 $url .= Proxy::PIXEL_LARGE . '/';
2004 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2008 * Get avatar link for given contact URL
2010 * @param string $url contact url
2011 * @param integer $uid user id
2012 * @param string $size One of the Proxy::SIZE_* constants
2013 * @return string avatar link
2015 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2017 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2018 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2019 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2020 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2024 * Get header link for given contact id
2026 * @param integer $cid contact id
2027 * @param string $size One of the Proxy::SIZE_* constants
2028 * @param string $updated Contact update date
2029 * @return string header link
2031 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2033 // We have to fetch the "updated" variable when it wasn't provided
2034 // The parameter can be provided to improve performance
2035 if (empty($updated) || empty($guid)) {
2036 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2037 $updated = $account['updated'] ?? '';
2038 $guid = $account['guid'] ?? '';
2041 $guid = urlencode($guid);
2043 $url = DI::baseUrl() . '/photo/header/';
2045 case Proxy::SIZE_MICRO:
2046 $url .= Proxy::PIXEL_MICRO . '/';
2048 case Proxy::SIZE_THUMB:
2049 $url .= Proxy::PIXEL_THUMB . '/';
2051 case Proxy::SIZE_SMALL:
2052 $url .= Proxy::PIXEL_SMALL . '/';
2054 case Proxy::SIZE_MEDIUM:
2055 $url .= Proxy::PIXEL_MEDIUM . '/';
2057 case Proxy::SIZE_LARGE:
2058 $url .= Proxy::PIXEL_LARGE . '/';
2062 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2066 * Updates the avatar links in a contact only if needed
2068 * @param int $cid Contact id
2069 * @param string $avatar Link to avatar picture
2070 * @param bool $force force picture update
2071 * @param bool $create_cache Enforces the creation of cached avatar fields
2074 * @throws HTTPException\InternalServerErrorException
2075 * @throws HTTPException\NotFoundException
2076 * @throws \ImagickException
2078 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2080 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2081 ['id' => $cid, 'self' => false]);
2082 if (!DBA::isResult($contact)) {
2086 $uid = $contact['uid'];
2088 // Only update the cached photo links of public contacts when they already are cached
2089 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2090 if ($contact['avatar'] != $avatar) {
2091 self::update(['avatar' => $avatar], ['id' => $cid]);
2092 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2097 // User contacts use are updated through the public contacts
2098 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2099 $pcid = self::getIdForURL($contact['url'], 0, false);
2100 if (!empty($pcid)) {
2101 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2102 self::updateAvatar($pcid, $avatar, $force, true);
2107 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2109 if ($default_avatar) {
2110 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2113 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2115 // Local contact avatars don't need to be cached
2116 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2117 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2120 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2121 Avatar::deleteCache($contact);
2123 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2124 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2126 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2127 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2128 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2131 // Use the data from the self account
2132 if (empty($fields)) {
2133 $local_uid = User::getIdForURL($contact['url']);
2134 if (!empty($local_uid)) {
2135 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2136 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2140 if (empty($fields)) {
2141 $update = ($contact['avatar'] != $avatar) || $force;
2145 $contact['photo'] ?? '',
2146 $contact['thumb'] ?? '',
2147 $contact['micro'] ?? '',
2150 foreach ($data as $image_uri) {
2151 $image_rid = Photo::ridFromURI($image_uri);
2152 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2153 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2160 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2162 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2163 $update = !empty($fields);
2164 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2170 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2173 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2174 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2175 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2184 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2185 // Collect all user contacts of the given public contact
2186 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2187 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2188 while ($personal_contact = DBA::fetch($personal_contacts)) {
2189 $cids[] = $personal_contact['id'];
2190 $uids[] = $personal_contact['uid'];
2192 DBA::close($personal_contacts);
2194 if (!empty($cids)) {
2195 // Delete possibly existing cached user contact avatars
2196 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2202 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2203 self::update($fields, ['id' => $cids]);
2206 public static function deleteContactByUrl(string $url)
2208 // Update contact data for all users
2209 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2210 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2211 while ($contact = DBA::fetch($contacts)) {
2212 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2213 self::remove($contact['id']);
2218 * Helper function for "updateFromProbe". Updates personal and public contact
2220 * @param integer $id contact id
2221 * @param integer $uid user id
2222 * @param string $old_url The previous profile URL of the contact
2223 * @param string $new_url The profile URL of the contact
2224 * @param array $fields The fields that are updated
2226 * @throws \Exception
2228 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
2230 if (!self::update($fields, ['id' => $id])) {
2231 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2235 // Search for duplicated contacts and get rid of them
2236 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
2240 // Archive or unarchive the contact.
2241 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2242 if (!DBA::isResult($contact)) {
2243 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2247 if (isset($fields['failed'])) {
2248 if ($fields['failed']) {
2249 self::markForArchival($contact);
2251 self::unmarkForArchival($contact);
2255 if ($contact['uid'] != 0) {
2259 // Update contact data for all users
2260 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
2262 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2263 self::update($fields, $condition);
2265 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2266 $condition['network'] = Protocol::OSTATUS;
2268 // If the contact failed, propagate the update fields to all contacts
2269 if (empty($fields['failed'])) {
2270 unset($fields['last-update']);
2271 unset($fields['success_update']);
2272 unset($fields['failure_update']);
2275 if (empty($fields)) {
2279 self::update($fields, $condition);
2283 * Remove duplicated contacts
2285 * @param string $nurl Normalised contact url
2286 * @param integer $uid User id
2288 * @throws \Exception
2290 public static function removeDuplicates(string $nurl, int $uid)
2292 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2293 $count = DBA::count('contact', $condition);
2298 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2299 if (!DBA::isResult($first_contact)) {
2300 // Shouldn't happen - so we handle it
2304 $first = $first_contact['id'];
2305 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2306 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2307 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2308 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2312 // Find all duplicates
2313 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2314 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2315 while ($duplicate = DBA::fetch($duplicates)) {
2316 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2320 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2322 DBA::close($duplicates);
2323 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2328 * Updates contact record by provided id and optional network
2330 * @param integer $id contact id
2331 * @param string $network Optional network we are probing for
2333 * @throws HTTPException\InternalServerErrorException
2334 * @throws \ImagickException
2336 public static function updateFromProbe(int $id, string $network = '')
2338 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2339 if (!DBA::isResult($contact)) {
2343 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2345 if ($ret['network'] == Protocol::DIASPORA) {
2346 FContact::updateFromProbeArray($ret);
2349 return self::updateFromProbeArray($id, $ret);
2353 * Checks if the given contact has got local data
2356 * @param array $contact
2360 private static function hasLocalData(int $id, array $contact): bool
2362 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2363 // User contacts with the same uri-id exist
2365 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2366 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2369 if (DBA::exists('post-tag', ['cid' => $id])) {
2370 // Is tagged in a post
2373 if (DBA::exists('user-contact', ['cid' => $id])) {
2374 // Has got user-contact data
2377 if (Post::exists(['author-id' => $id])) {
2378 // Posts with this author exist
2381 if (Post::exists(['owner-id' => $id])) {
2382 // Posts with this owner exist
2385 if (Post::exists(['causer-id' => $id])) {
2386 // Posts with this causer exist
2389 // We don't have got this contact locally
2394 * Updates contact record by provided id and probed data
2396 * @param integer $id contact id
2397 * @param array $ret Probed data
2399 * @throws HTTPException\InternalServerErrorException
2400 * @throws \ImagickException
2402 private static function updateFromProbeArray(int $id, array $ret): bool
2405 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2406 This will reliably kill your communication with old Friendica contacts.
2409 // These fields aren't updated by this routine:
2412 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2413 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2414 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2415 'created', 'last-update'];
2416 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2417 if (!DBA::isResult($contact)) {
2421 if (self::isLocal($ret['url'])) {
2422 if ($contact['uid'] == 0) {
2423 Logger::info('Local contacts are not updated here.');
2425 self::updateFromPublicContact($id, $contact);
2430 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2431 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2434 // Delete all contacts with the same URL
2435 self::deleteContactByUrl($ret['url']);
2439 $uid = $contact['uid'];
2440 unset($contact['uid']);
2442 $uriid = $contact['uri-id'];
2443 unset($contact['uri-id']);
2445 $pubkey = $contact['pubkey'];
2446 unset($contact['pubkey']);
2448 $created = $contact['created'];
2449 unset($contact['created']);
2451 $last_update = $contact['last-update'];
2452 unset($contact['last-update']);
2454 $contact['photo'] = $contact['avatar'];
2455 unset($contact['avatar']);
2457 $updated = DateTimeFormat::utcNow();
2459 $has_local_data = self::hasLocalData($id, $contact);
2461 if (!in_array($ret['network'], array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM]))) {
2462 // Periodical checks are only done on federated contacts
2463 $failed_next_update = null;
2464 $success_next_update = null;
2465 } elseif ($has_local_data) {
2466 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2467 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2469 $failed_next_update = DateTimeFormat::utc('now +6 month');
2470 $success_next_update = DateTimeFormat::utc('now +1 month');
2473 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2474 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2475 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]);
2479 // We must not try to update relay contacts via probe. They are no real contacts.
2480 // We check after the probing to be able to correct falsely detected contact types.
2481 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2482 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2483 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]);
2484 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2488 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2489 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2490 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]);
2494 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2495 $cid = self::getIdForURL($ret['url'], 0, false);
2496 if (!empty($cid) && ($cid != $id)) {
2497 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2498 return self::updateFromProbeArray($cid, $ret);
2502 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2503 $ret['unsearchable'] = $ret['hide'];
2506 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2507 $ret['forum'] = false;
2508 $ret['prv'] = false;
2509 $ret['contact-type'] = $ret['account-type'];
2510 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2511 $ret['forum'] = (bool)!$ret['manually-approve'];
2512 $ret['prv'] = (bool)!$ret['forum'];
2516 $new_pubkey = $ret['pubkey'] ?? '';
2518 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2519 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2520 $apcontact = APContact::getByURL($ret['url'], false);
2521 if (!empty($apcontact['featured'])) {
2522 Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2526 $ret['last-item'] = Probe::getLastUpdate($ret);
2527 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2531 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2533 // make sure to not overwrite existing values with blank entries except some technical fields
2534 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2535 foreach ($ret as $key => $val) {
2536 if (!array_key_exists($key, $contact)) {
2538 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2539 $ret[$key] = $contact[$key];
2540 } elseif ($ret[$key] != $contact[$key]) {
2545 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2548 unset($ret['last-item']);
2551 if (empty($uriid)) {
2555 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2556 self::updateAvatar($id, $ret['photo'], $update);
2559 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2562 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]);
2564 if (Contact\Relation::isDiscoverable($ret['url'])) {
2565 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2568 // Update the public contact
2570 $contact = self::getByURL($ret['url'], false, ['id']);
2571 if (!empty($contact['id'])) {
2572 self::updateFromProbeArray($contact['id'], $ret);
2579 $ret['uri-id'] = $uriid;
2580 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2581 $ret['updated'] = $updated;
2582 $ret['failed'] = false;
2583 $ret['next-update'] = $success_next_update;
2584 $ret['local-data'] = $has_local_data;
2586 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2587 if (empty($pubkey) && !empty($new_pubkey)) {
2588 $ret['pubkey'] = $new_pubkey;
2591 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2592 $ret['uri-date'] = $updated;
2595 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2596 $ret['name-date'] = $updated;
2599 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2600 $ret['last-update'] = $updated;
2601 $ret['success_update'] = $updated;
2604 unset($ret['photo']);
2606 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2608 if (Contact\Relation::isDiscoverable($ret['url'])) {
2609 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2615 private static function updateFromPublicContact(int $id, array $contact)
2617 $public = self::getByURL($contact['url'], false);
2621 foreach ($contact as $field => $value) {
2622 if ($field == 'uid') {
2625 if ($public[$field] != $value) {
2626 $fields[$field] = $public[$field];
2629 if (!empty($fields)) {
2630 self::update($fields, ['id' => $id, 'self' => false]);
2631 Logger::info('Updating local contact', ['id' => $id]);
2636 * Updates contact record by provided URL
2638 * @param integer $url contact url
2639 * @return integer Contact id
2640 * @throws HTTPException\InternalServerErrorException
2641 * @throws \ImagickException
2643 public static function updateFromProbeByURL(string $url): int
2645 $id = self::getIdForURL($url);
2651 self::updateFromProbe($id);
2657 * Detects the communication protocol for a given contact url.
2658 * This is used to detect Friendica contacts that we can communicate via AP.
2660 * @param string $url contact url
2661 * @param string $network Network of that contact
2662 * @return string with protocol
2664 public static function getProtocol(string $url, string $network): string
2666 if ($network != Protocol::DFRN) {
2670 $apcontact = APContact::getByURL($url);
2671 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2672 return Protocol::ACTIVITYPUB;
2679 * Takes a $uid and a url/handle and adds a new contact
2681 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2682 * dfrn_request page.
2684 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2687 * $return['success'] boolean true if successful
2688 * $return['message'] error text if success is false.
2690 * Takes a $uid and a url/handle and adds a new contact
2692 * @param int $uid The user id the contact should be created for
2693 * @param string $url The profile URL of the contact
2694 * @param string $network
2696 * @throws HTTPException\InternalServerErrorException
2697 * @throws HTTPException\NotFoundException
2698 * @throws \ImagickException
2700 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2702 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2704 // remove ajax junk, e.g. Twitter
2705 $url = str_replace('/#!/', '/', $url);
2707 if (!Network::isUrlAllowed($url)) {
2708 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2712 if (Network::isUrlBlocked($url)) {
2713 $result['message'] = DI::l10n()->t('Blocked domain');
2718 $result['message'] = DI::l10n()->t('Connect URL missing.');
2722 $arr = ['url' => $url, 'contact' => []];
2724 Hook::callAll('follow', $arr);
2727 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2731 if (!empty($arr['contact']['name'])) {
2733 $ret = $arr['contact'];
2736 $ret = Probe::uri($url, $network, $uid);
2738 // Ensure that the public contact exists
2739 if ($ret['network'] != Protocol::PHANTOM) {
2740 self::getIdForURL($url);
2744 if (($network != '') && ($ret['network'] != $network)) {
2745 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2749 // check if we already have a contact
2750 // the poll url is more reliable than the profile url, as we may have
2751 // indirect links or webfinger links
2753 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2754 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2755 if (!DBA::isResult($contact)) {
2756 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2757 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2760 $protocol = self::getProtocol($ret['url'], $ret['network']);
2762 // This extra param just confuses things, remove it
2763 if ($protocol === Protocol::DIASPORA) {
2764 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2767 // do we have enough information?
2768 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2769 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2770 if (empty($ret['poll'])) {
2771 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2773 if (empty($ret['name'])) {
2774 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2776 if (empty($ret['url'])) {
2777 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2779 if (strpos($ret['url'], '@') !== false) {
2780 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2781 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2786 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2787 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2788 $ret['notify'] = '';
2791 if (!$ret['notify']) {
2792 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2795 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2797 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2799 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2802 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2803 $pending = (bool)$ret['manually-approve'];
2806 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2810 if (DBA::isResult($contact)) {
2812 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2814 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2815 self::update($fields, ['id' => $contact['id']]);
2817 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2819 // create contact record
2822 'created' => DateTimeFormat::utcNow(),
2823 'url' => $ret['url'],
2824 'nurl' => Strings::normaliseLink($ret['url']),
2825 'addr' => $ret['addr'],
2826 'alias' => $ret['alias'],
2827 'batch' => $ret['batch'],
2828 'notify' => $ret['notify'],
2829 'poll' => $ret['poll'],
2830 'poco' => $ret['poco'],
2831 'name' => $ret['name'],
2832 'nick' => $ret['nick'],
2833 'network' => $ret['network'],
2834 'baseurl' => $ret['baseurl'],
2835 'gsid' => $ret['gsid'] ?? null,
2836 'protocol' => $protocol,
2837 'pubkey' => $ret['pubkey'],
2838 'rel' => $new_relation,
2839 'priority'=> $ret['priority'],
2840 'writable'=> $writeable,
2841 'hidden' => $hidden,
2844 'pending' => $pending,
2849 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2850 if (!DBA::isResult($contact)) {
2851 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2855 $contact_id = $contact['id'];
2856 $result['cid'] = $contact_id;
2858 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2860 // Update the avatar
2861 self::updateAvatar($contact_id, $ret['photo']);
2863 // pull feed and consume it, which should subscribe to the hub.
2864 if ($contact['network'] == Protocol::OSTATUS) {
2865 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2869 self::updateFromProbeArray($contact_id, $ret);
2871 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2874 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2880 * @param array $importer Owner (local user) data
2881 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2882 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2883 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2884 * @param string $note Introduction additional message
2885 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2886 * @throws HTTPException\InternalServerErrorException
2887 * @throws \ImagickException
2889 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
2891 // Should always be set
2892 if (empty($datarray['author-id'])) {
2896 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2897 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2898 if (!DBA::isResult($pub_contact)) {
2899 // Should never happen
2903 // Contact is blocked at node-level
2904 if (self::isBlocked($datarray['author-id'])) {
2908 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2909 $name = $pub_contact['name'];
2910 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2911 $nick = $pub_contact['nick'];
2912 $network = $pub_contact['network'];
2914 // Ensure that we don't create a new contact when there already is one
2915 $cid = self::getIdForURL($url, $importer['uid']);
2917 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2920 self::clearFollowerFollowingEndpointCache($importer['uid']);
2922 if (!empty($contact)) {
2923 if (!empty($contact['pending'])) {
2924 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2928 // Contact is blocked at user-level
2929 if (!empty($contact['id']) && !empty($importer['id']) &&
2930 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2934 // Make sure that the existing contact isn't archived
2935 self::unmarkForArchival($contact);
2937 if (($contact['rel'] == self::SHARING)
2938 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2939 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2940 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2943 // Ensure to always have the correct network type, independent from the connection request method
2944 self::updateFromProbe($contact['id']);
2946 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2950 // send email notification to owner?
2951 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2952 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2956 // create contact record
2957 $contact_id = self::insert([
2958 'uid' => $importer['uid'],
2959 'created' => DateTimeFormat::utcNow(),
2961 'nurl' => Strings::normaliseLink($url),
2964 'network' => $network,
2965 'rel' => self::FOLLOWER,
2972 // Ensure to always have the correct network type, independent from the connection request method
2973 self::updateFromProbe($contact_id);
2975 self::updateAvatar($contact_id, $photo, true);
2977 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2979 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2981 /// @TODO Encapsulate this into a function/method
2982 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2983 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2984 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2985 // create notification
2986 if (is_array($contact_record)) {
2987 $intro = DI::introFactory()->createNew(
2989 $contact_record['id'],
2992 DI::intro()->save($intro);
2995 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
2997 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
2998 DI::notify()->createFromArray([
2999 'type' => Notification\Type::INTRO,
3000 'otype' => Notification\ObjectType::INTRO,
3001 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3002 'uid' => $user['uid'],
3003 'cid' => $contact_record['id'],
3004 'link' => DI::baseUrl() . '/notifications/intros',
3007 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3008 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3009 self::createFromProbeForUser($importer['uid'], $url, $network);
3012 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3013 $fields = ['pending' => false];
3014 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3015 $fields['rel'] = self::FRIEND;
3018 self::update($fields, $condition);
3028 * Update the local relationship when a local user loses a follower
3030 * @param array $contact User-specific contact (uid != 0) array
3032 * @throws HTTPException\InternalServerErrorException
3033 * @throws \ImagickException
3035 public static function removeFollower(array $contact)
3037 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3038 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3039 } elseif (!empty($contact['id'])) {
3040 self::remove($contact['id']);
3042 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3046 self::clearFollowerFollowingEndpointCache($contact['uid']);
3048 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3050 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3054 * Update the local relationship when a local user unfollow a contact.
3055 * Removes the contact for sharing-only protocols (feed and mail).
3057 * @param array $contact User-specific contact (uid != 0) array
3058 * @throws HTTPException\InternalServerErrorException
3060 public static function removeSharer(array $contact)
3062 self::clearFollowerFollowingEndpointCache($contact['uid']);
3064 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3065 self::remove($contact['id']);
3067 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3072 * Create a birthday event.
3074 * Update the year and the birthday.
3076 public static function updateBirthdays()
3080 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3081 AND NOT `contact`.`pending`
3082 AND NOT `contact`.`hidden`
3083 AND NOT `contact`.`blocked`
3084 AND NOT `contact`.`archive`
3085 AND NOT `contact`.`deleted`',
3091 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3093 while ($contact = DBA::fetch($contacts)) {
3094 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3096 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3098 if (Event::createBirthday($contact, $nextbd)) {
3102 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3103 ['id' => $contact['id']]
3107 DBA::close($contacts);
3111 * Remove the unavailable contact ids from the provided list
3113 * @param array $contact_ids Contact id list
3115 * @throws \Exception
3117 public static function pruneUnavailable(array $contact_ids): array
3119 if (empty($contact_ids)) {
3123 $contacts = self::selectToArray(['id'], [
3124 'id' => $contact_ids,
3130 return array_column($contacts, 'id');
3134 * Returns a magic link to authenticate remote visitors
3136 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3138 * @param string $contact_url The address of the target contact profile
3139 * @param string $url An url that we will be redirected to after the authentication
3141 * @return string with "redir" link
3142 * @throws HTTPException\InternalServerErrorException
3143 * @throws \ImagickException
3145 public static function magicLink(string $contact_url, string $url = ''): string
3147 if (!Session::isAuthenticated()) {
3148 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3151 $contact = self::getByURL($contact_url, false);
3152 if (empty($contact)) {
3153 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3156 // Prevents endless loop in case only a non-public contact exists for the contact URL
3157 unset($contact['uid']);
3159 return self::magicLinkByContact($contact, $url ?: $contact_url);
3163 * Returns a magic link to authenticate remote visitors
3165 * @param integer $cid The contact id of the target contact profile
3166 * @param string $url An url that we will be redirected to after the authentication
3168 * @return string with "redir" link
3169 * @throws HTTPException\InternalServerErrorException
3170 * @throws \ImagickException
3172 public static function magicLinkById(int $cid, string $url = ''): string
3174 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3176 return self::magicLinkByContact($contact, $url);
3180 * Returns a magic link to authenticate remote visitors
3182 * @param array $contact The contact array with "uid", "network" and "url"
3183 * @param string $url An url that we will be redirected to after the authentication
3185 * @return string with "redir" link
3186 * @throws HTTPException\InternalServerErrorException
3187 * @throws \ImagickException
3189 public static function magicLinkByContact(array $contact, string $url = ''): string
3191 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3193 if (!Session::isAuthenticated()) {
3194 return $destination;
3197 // Only redirections to the same host do make sense
3198 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3202 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3203 return 'contact/' . $contact['id'] . '/conversations';
3206 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3207 return $destination;
3210 if (empty($contact['id'])) {
3211 return $destination;
3214 $redirect = 'redir/' . $contact['id'];
3216 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3217 $redirect .= '?url=' . $url;
3224 * Is the contact a forum?
3226 * @param integer $contactid ID of the contact
3228 * @return boolean "true" if it is a forum
3230 public static function isForum(int $contactid): bool
3232 $fields = ['contact-type'];
3233 $condition = ['id' => $contactid];
3234 $contact = DBA::selectFirst('contact', $fields, $condition);
3235 if (!DBA::isResult($contact)) {
3240 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3244 * Can the remote contact receive private messages?
3246 * @param array $contact
3249 public static function canReceivePrivateMessages(array $contact): bool
3251 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3252 $self = $contact['self'] ?? false;
3254 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3258 * Search contact table by nick or name
3260 * @param string $search Name or nick
3261 * @param string $mode Search mode (e.g. "community")
3262 * @param int $uid User ID
3264 * @return array with search results
3265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3267 public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3269 if (empty($search)) {
3273 // check supported networks
3274 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3275 if (DI::config()->get('system', 'diaspora_enabled')) {
3276 $networks[] = Protocol::DIASPORA;
3279 if (!DI::config()->get('system', 'ostatus_disabled')) {
3280 $networks[] = Protocol::OSTATUS;
3283 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3286 $condition['blocked'] = false;
3289 // check if we search only communities or every contact
3290 if ($mode === 'community') {
3291 $condition['contact-type'] = self::TYPE_COMMUNITY;
3296 $condition = DBA::mergeConditions($condition,
3297 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3298 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3300 $contacts = self::selectToArray([], $condition);
3305 * Add public contacts from an array
3307 * @param array $urls
3308 * @return array result "count", "added" and "updated"
3310 public static function addByUrls(array $urls): array
3317 foreach ($urls as $url) {
3318 if (empty($url) || !is_string($url)) {
3321 $contact = self::getByURL($url, false, ['id', 'updated']);
3322 if (empty($contact['id'])) {
3323 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3325 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3326 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3334 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3338 * Returns a random, global contact array of the current node
3340 * @return array The profile array
3343 public static function getRandomContact(): array
3345 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3346 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3347 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3348 ], ['order' => ['RAND()']]);
3350 if (DBA::isResult($contact)) {