3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\App\BaseURL;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Session;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
19 use Friendica\Network\Probe;
20 use Friendica\Protocol\Activity;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Images;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
32 * functions for interacting with a contact
37 * @deprecated since version 2019.03
38 * @see User::PAGE_FLAGS_NORMAL
40 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
42 * @deprecated since version 2019.03
43 * @see User::PAGE_FLAGS_SOAPBOX
45 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
47 * @deprecated since version 2019.03
48 * @see User::PAGE_FLAGS_COMMUNITY
50 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
52 * @deprecated since version 2019.03
53 * @see User::PAGE_FLAGS_FREELOVE
55 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_BLOG
60 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_PRVGROUP
65 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
73 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
75 * TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
78 * TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_SOAPBOX
84 * TYPE_COMMUNITY - the account is community forum
85 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
87 * TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const TYPE_UNKNOWN = -1;
92 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
93 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
94 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
95 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
96 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @param array $fields Array of selected fields, empty for all
116 * @param array $condition Array of fields for condition
117 * @param array $params Array of several parameters
121 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
123 return DBA::selectToArray('contact', $fields, $condition, $params);
127 * @param array $fields Array of selected fields, empty for all
128 * @param array $condition Array of fields for condition
129 * @param array $params Array of several parameters
133 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
135 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
141 * Insert a row into the contact table
142 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
144 * @param array $fields field array
145 * @param bool $on_duplicate_update Do an update on a duplicate entry
147 * @return boolean was the insert successful?
150 public static function insert(array $fields, bool $on_duplicate_update = false)
152 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
153 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
154 if (!DBA::isResult($contact)) {
159 // Search for duplicated contacts and get rid of them
160 self::removeDuplicates($contact['nurl'], $contact['uid']);
166 * @param integer $id Contact ID
167 * @param array $fields Array of selected fields, empty for all
168 * @return array|boolean Contact record if it exists, false otherwise
171 public static function getById($id, $fields = [])
173 return DBA::selectFirst('contact', $fields, ['id' => $id]);
177 * Tests if the given contact is a follower
179 * @param int $cid Either public contact id or user's contact id
180 * @param int $uid User ID
182 * @return boolean is the contact id a follower?
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function isFollower($cid, $uid)
188 if (self::isBlockedByUser($cid, $uid)) {
192 $cdata = self::getPublicAndUserContacID($cid, $uid);
193 if (empty($cdata['user'])) {
197 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
198 return DBA::exists('contact', $condition);
202 * Tests if the given contact url is a follower
204 * @param string $url Contact URL
205 * @param int $uid User ID
207 * @return boolean is the contact id a follower?
208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 public static function isFollowerByURL($url, $uid)
213 $cid = self::getIdForURL($url, $uid, true);
219 return self::isFollower($cid, $uid);
223 * Tests if the given user follow the given contact
225 * @param int $cid Either public contact id or user's contact id
226 * @param int $uid User ID
228 * @return boolean is the contact url being followed?
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function isSharing($cid, $uid)
234 if (self::isBlockedByUser($cid, $uid)) {
238 $cdata = self::getPublicAndUserContacID($cid, $uid);
239 if (empty($cdata['user'])) {
243 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
244 return DBA::exists('contact', $condition);
248 * Tests if the given user follow the given contact url
250 * @param string $url Contact URL
251 * @param int $uid User ID
253 * @return boolean is the contact url being followed?
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 public static function isSharingByURL($url, $uid)
259 $cid = self::getIdForURL($url, $uid, true);
265 return self::isSharing($cid, $uid);
269 * Get the basepath for a given contact link
271 * @param string $url The contact link
272 * @param boolean $dont_update Don't update the contact
274 * @return string basepath
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function getBasepath($url, $dont_update = false)
280 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
281 if (!DBA::isResult($contact)) {
285 if (!empty($contact['baseurl'])) {
286 return $contact['baseurl'];
287 } elseif ($dont_update) {
291 // Update the existing contact
292 self::updateFromProbe($contact['id'], '', true);
294 // And fetch the result
295 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
296 if (empty($contact['baseurl'])) {
297 Logger::info('No baseurl for contact', ['url' => $url]);
301 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
302 return $contact['baseurl'];
306 * Check if the given contact url is on the same server
308 * @param string $url The contact link
310 * @return boolean Is it the same server?
312 public static function isLocal($url)
314 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
318 * Check if the given contact ID is on the same server
320 * @param string $url The contact link
322 * @return boolean Is it the same server?
324 public static function isLocalById(int $cid)
326 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
327 if (!DBA::isResult($contact)) {
331 if (empty($contact['baseurl'])) {
332 $baseurl = self::getBasepath($contact['url'], true);
334 $baseurl = $contact['baseurl'];
337 return Strings::compareLink($baseurl, DI::baseUrl());
341 * Returns the public contact id of the given user id
343 * @param integer $uid User ID
345 * @return integer|boolean Public contact id for given user id
348 public static function getPublicIdByUserId($uid)
350 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
351 if (!DBA::isResult($self)) {
354 return self::getIdForURL($self['url'], 0, true);
358 * Returns the contact id for the user and the public contact id for a given contact id
360 * @param int $cid Either public contact id or user's contact id
361 * @param int $uid User ID
363 * @return array with public and user's contact id
364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365 * @throws \ImagickException
367 public static function getPublicAndUserContacID($cid, $uid)
369 if (empty($uid) || empty($cid)) {
373 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
374 if (!DBA::isResult($contact)) {
378 // We quit when the user id don't match the user id of the provided contact
379 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
383 if ($contact['uid'] != 0) {
384 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
388 $ucid = $contact['id'];
390 $pcid = $contact['id'];
391 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
394 return ['public' => $pcid, 'user' => $ucid];
398 * Returns contact details for a given contact id in combination with a user id
400 * @param int $cid A contact ID
401 * @param int $uid The User ID
402 * @param array $fields The selected fields for the contact
404 * @return array The contact details
408 public static function getContactForUser($cid, $uid, array $fields = [])
410 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
412 if (!DBA::isResult($contact)) {
420 * Block contact id for user id
422 * @param int $cid Either public contact id or user's contact id
423 * @param int $uid User ID
424 * @param boolean $blocked Is the contact blocked or unblocked?
427 public static function setBlockedForUser($cid, $uid, $blocked)
429 $cdata = self::getPublicAndUserContacID($cid, $uid);
434 if ($cdata['user'] != 0) {
435 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
438 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
442 * Returns "block" state for contact id and user id
444 * @param int $cid Either public contact id or user's contact id
445 * @param int $uid User ID
447 * @return boolean is the contact id blocked for the given user?
450 public static function isBlockedByUser($cid, $uid)
452 $cdata = self::getPublicAndUserContacID($cid, $uid);
457 $public_blocked = false;
459 if (!empty($cdata['public'])) {
460 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
461 if (DBA::isResult($public_contact)) {
462 $public_blocked = $public_contact['blocked'];
466 $user_blocked = $public_blocked;
468 if (!empty($cdata['user'])) {
469 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
470 if (DBA::isResult($user_contact)) {
471 $user_blocked = $user_contact['blocked'];
475 if ($user_blocked != $public_blocked) {
476 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
479 return $user_blocked;
483 * Ignore contact id for user id
485 * @param int $cid Either public contact id or user's contact id
486 * @param int $uid User ID
487 * @param boolean $ignored Is the contact ignored or unignored?
490 public static function setIgnoredForUser($cid, $uid, $ignored)
492 $cdata = self::getPublicAndUserContacID($cid, $uid);
497 if ($cdata['user'] != 0) {
498 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
501 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
505 * Returns "ignore" state for contact id and user id
507 * @param int $cid Either public contact id or user's contact id
508 * @param int $uid User ID
510 * @return boolean is the contact id ignored for the given user?
513 public static function isIgnoredByUser($cid, $uid)
515 $cdata = self::getPublicAndUserContacID($cid, $uid);
520 $public_ignored = false;
522 if (!empty($cdata['public'])) {
523 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
524 if (DBA::isResult($public_contact)) {
525 $public_ignored = $public_contact['ignored'];
529 $user_ignored = $public_ignored;
531 if (!empty($cdata['user'])) {
532 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
533 if (DBA::isResult($user_contact)) {
534 $user_ignored = $user_contact['readonly'];
538 if ($user_ignored != $public_ignored) {
539 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
542 return $user_ignored;
546 * Set "collapsed" for contact id and user id
548 * @param int $cid Either public contact id or user's contact id
549 * @param int $uid User ID
550 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
553 public static function setCollapsedForUser($cid, $uid, $collapsed)
555 $cdata = self::getPublicAndUserContacID($cid, $uid);
560 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
564 * Returns "collapsed" state for contact id and user id
566 * @param int $cid Either public contact id or user's contact id
567 * @param int $uid User ID
569 * @return boolean is the contact id blocked for the given user?
570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
571 * @throws \ImagickException
573 public static function isCollapsedByUser($cid, $uid)
575 $cdata = self::getPublicAndUserContacID($cid, $uid);
582 if (!empty($cdata['public'])) {
583 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
584 if (DBA::isResult($public_contact)) {
585 $collapsed = $public_contact['collapsed'];
593 * Returns a list of contacts belonging in a group
599 public static function getByGroupId($gid)
604 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
606 INNER JOIN `group_member`
607 ON `contact`.`id` = `group_member`.`contact-id`
609 AND `contact`.`uid` = ?
610 AND NOT `contact`.`self`
611 AND NOT `contact`.`deleted`
612 AND NOT `contact`.`blocked`
613 AND NOT `contact`.`pending`
614 ORDER BY `contact`.`name` ASC',
619 if (DBA::isResult($stmt)) {
620 $return = DBA::toArray($stmt);
628 * Returns the count of OStatus contacts in a group
634 public static function getOStatusCountByGroupId($gid)
638 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
640 INNER JOIN `group_member`
641 ON `contact`.`id` = `group_member`.`contact-id`
643 AND `contact`.`uid` = ?
644 AND `contact`.`network` = ?
645 AND `contact`.`notify` != ""',
650 $return = $contacts['count'];
657 * Creates the self-contact for the provided user id
660 * @return bool Operation success
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
663 public static function createSelfFromUserId($uid)
665 // Only create the entry if it doesn't exist yet
666 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
670 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
671 if (!DBA::isResult($user)) {
675 $return = DBA::insert('contact', [
676 'uid' => $user['uid'],
677 'created' => DateTimeFormat::utcNow(),
679 'name' => $user['username'],
680 'nick' => $user['nickname'],
681 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
682 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
683 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
686 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
687 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
688 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
689 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
690 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
691 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
692 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
693 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
694 'name-date' => DateTimeFormat::utcNow(),
695 'uri-date' => DateTimeFormat::utcNow(),
696 'avatar-date' => DateTimeFormat::utcNow(),
704 * Updates the self-contact for the provided user id
707 * @param boolean $update_avatar Force the avatar update
708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
710 public static function updateSelfFromUserID($uid, $update_avatar = false)
712 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
713 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
714 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
715 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
716 if (!DBA::isResult($self)) {
720 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
721 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
722 if (!DBA::isResult($user)) {
726 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
727 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
728 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
729 if (!DBA::isResult($profile)) {
733 $file_suffix = 'jpg';
735 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
736 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
737 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
738 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
739 'xmpp' => $profile['xmpp']];
741 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
742 if (DBA::isResult($avatar)) {
743 if ($update_avatar) {
744 $fields['avatar-date'] = DateTimeFormat::utcNow();
747 // Creating the path to the avatar, beginning with the file suffix
748 $types = Images::supportedTypes();
749 if (isset($types[$avatar['type']])) {
750 $file_suffix = $types[$avatar['type']];
753 // We are adding a timestamp value so that other systems won't use cached content
754 $timestamp = strtotime($fields['avatar-date']);
756 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
757 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
759 $fields['photo'] = $prefix . '4' . $suffix;
760 $fields['thumb'] = $prefix . '5' . $suffix;
761 $fields['micro'] = $prefix . '6' . $suffix;
763 // We hadn't found a photo entry, so we use the default avatar
764 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
765 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
766 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
769 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
770 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
771 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
772 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
774 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
775 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
776 $fields['nurl'] = Strings::normaliseLink($fields['url']);
777 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
778 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
779 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
780 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
781 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
782 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
786 foreach ($fields as $field => $content) {
787 if ($self[$field] != $content) {
793 if ($fields['name'] != $self['name']) {
794 $fields['name-date'] = DateTimeFormat::utcNow();
796 $fields['updated'] = DateTimeFormat::utcNow();
797 DBA::update('contact', $fields, ['id' => $self['id']]);
799 // Update the public contact as well
800 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
802 // Update the profile
803 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
804 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
805 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
810 * Marks a contact for removal
812 * @param int $id contact id
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
816 public static function remove($id)
818 // We want just to make sure that we don't delete our "self" contact
819 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
820 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
824 // Archive the contact
825 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
827 // Delete it in the background
828 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
832 * Sends an unfriend message. Does not remove the contact
834 * @param array $user User unfriending
835 * @param array $contact Contact unfriended
836 * @param boolean $dissolve Remove the contact on the remote side
838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
839 * @throws \ImagickException
841 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
843 if (empty($contact['network'])) {
847 $protocol = $contact['network'];
848 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
849 $protocol = Protocol::ACTIVITYPUB;
852 if (($protocol == Protocol::DFRN) && $dissolve) {
853 DFRN::deliver($user, $contact, 'placeholder', true);
854 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
855 // create an unfollow slap
857 $item['verb'] = Activity::O_UNFOLLOW;
858 $item['follow'] = $contact["url"];
863 $item['attach'] = '';
864 $slap = OStatus::salmon($item, $user);
866 if (!empty($contact['notify'])) {
867 Salmon::slapper($user, $contact['notify'], $slap);
869 } elseif ($protocol == Protocol::DIASPORA) {
870 Diaspora::sendUnshare($user, $contact);
871 } elseif ($protocol == Protocol::ACTIVITYPUB) {
872 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
875 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
881 * Marks a contact for archival after a communication issue delay
883 * Contact has refused to recognise us as a friend. We will start a countdown.
884 * If they still don't recognise us in 32 days, the relationship is over,
885 * and we won't waste any more time trying to communicate with them.
886 * This provides for the possibility that their database is temporarily messed
887 * up or some other transient event and that there's a possibility we could recover from it.
889 * @param array $contact contact to mark for archival
891 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893 public static function markForArchival(array $contact)
895 if (!isset($contact['url']) && !empty($contact['id'])) {
896 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
897 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
898 if (!DBA::isResult($contact)) {
901 } elseif (!isset($contact['url'])) {
902 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
905 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
907 // Contact already archived or "self" contact? => nothing to do
908 if ($contact['archive'] || $contact['self']) {
912 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
913 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
914 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
917 * We really should send a notification to the owner after 2-3 weeks
918 * so they won't be surprised when the contact vanishes and can take
919 * remedial action if this was a serious mistake or glitch
922 /// @todo Check for contact vitality via probing
923 $archival_days = Config::get('system', 'archival_days', 32);
925 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
926 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
927 /* Relationship is really truly dead. archive them rather than
928 * delete, though if the owner tries to unarchive them we'll start
929 * the whole process over again.
931 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
932 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
933 GContact::updateFromPublicContactURL($contact['url']);
939 * Cancels the archival countdown
941 * @see Contact::markForArchival()
943 * @param array $contact contact to be unmarked for archival
947 public static function unmarkForArchival(array $contact)
949 // Always unarchive the relay contact entry
950 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
951 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
952 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
953 DBA::update('contact', $fields, $condition);
956 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
957 $exists = DBA::exists('contact', $condition);
959 // We don't need to update, we never marked this contact for archival
964 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
966 if (!isset($contact['url']) && !empty($contact['id'])) {
967 $fields = ['id', 'url', 'batch'];
968 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
969 if (!DBA::isResult($contact)) {
974 // It's a miracle. Our dead contact has inexplicably come back to life.
975 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
976 DBA::update('contact', $fields, ['id' => $contact['id']]);
977 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
978 GContact::updateFromPublicContactURL($contact['url']);
982 * Get contact data for a given profile link
984 * The function looks at several places (contact table and gcontact table) for the contact
985 * It caches its result for the same script execution to prevent duplicate calls
987 * @param string $url The profile link
988 * @param int $uid User id
989 * @param array $default If not data was found take this data as default value
991 * @return array Contact data
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 public static function getDetailsByURL($url, $uid = -1, array $default = [])
1003 $uid = local_user();
1006 if (isset($cache[$url][$uid])) {
1007 return $cache[$url][$uid];
1010 $ssl_url = str_replace('http://', 'https://', $url);
1012 $nurl = Strings::normaliseLink($url);
1014 // Fetch contact data from the contact table for the given user
1015 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1016 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1017 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
1018 $r = DBA::toArray($s);
1020 // Fetch contact data from the contact table for the given user, checking with the alias
1021 if (!DBA::isResult($r)) {
1022 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1023 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1024 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
1025 $r = DBA::toArray($s);
1028 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1029 if (!DBA::isResult($r)) {
1030 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1031 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1032 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1033 $r = DBA::toArray($s);
1036 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1037 if (!DBA::isResult($r)) {
1038 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1039 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1040 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1041 $r = DBA::toArray($s);
1044 // Fetch the data from the gcontact table
1045 if (!DBA::isResult($r)) {
1046 $s = DBA::p("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
1047 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`, 2 AS `rel`, 0 AS `pending`
1048 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1049 $r = DBA::toArray($s);
1052 if (DBA::isResult($r)) {
1053 // If there is more than one entry we filter out the connector networks
1054 if (count($r) > 1) {
1055 foreach ($r as $id => $result) {
1056 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1062 $profile = array_shift($r);
1064 // "bd" always contains the upcoming birthday of a contact.
1065 // "birthday" might contain the birthday including the year of birth.
1066 if ($profile["birthday"] > DBA::NULL_DATE) {
1067 $bd_timestamp = strtotime($profile["birthday"]);
1068 $month = date("m", $bd_timestamp);
1069 $day = date("d", $bd_timestamp);
1071 $current_timestamp = time();
1072 $current_year = date("Y", $current_timestamp);
1073 $current_month = date("m", $current_timestamp);
1074 $current_day = date("d", $current_timestamp);
1076 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1077 $current = $current_year . "-" . $current_month . "-" . $current_day;
1079 if ($profile["bd"] < $current) {
1080 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1083 $profile["bd"] = DBA::NULL_DATE;
1086 $profile = $default;
1089 if (empty($profile["photo"]) && isset($default["photo"])) {
1090 $profile["photo"] = $default["photo"];
1093 if (empty($profile["name"]) && isset($default["name"])) {
1094 $profile["name"] = $default["name"];
1097 if (empty($profile["network"]) && isset($default["network"])) {
1098 $profile["network"] = $default["network"];
1101 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1102 $profile["thumb"] = $profile["photo"];
1105 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1106 $profile["micro"] = $profile["thumb"];
1109 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1110 && in_array($profile["network"], Protocol::FEDERATED)
1112 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1115 // Show contact details of Diaspora contacts only if connected
1116 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1117 $profile["location"] = "";
1118 $profile["about"] = "";
1119 $profile["gender"] = "";
1120 $profile["birthday"] = DBA::NULL_DATE;
1123 $cache[$url][$uid] = $profile;
1129 * Get contact data for a given address
1131 * The function looks at several places (contact table and gcontact table) for the contact
1133 * @param string $addr The profile link
1134 * @param int $uid User id
1136 * @return array Contact data
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 public static function getDetailsByAddr($addr, $uid = -1)
1147 $uid = local_user();
1150 // Fetch contact data from the contact table for the given user
1151 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1152 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1153 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1157 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1158 if (!DBA::isResult($r)) {
1159 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1160 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1161 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1166 // Fetch the data from the gcontact table
1167 if (!DBA::isResult($r)) {
1168 $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
1169 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`, 2 AS `rel`, 0 AS `pending`
1170 FROM `gcontact` WHERE `addr` = '%s'",
1175 if (!DBA::isResult($r)) {
1176 $data = Probe::uri($addr);
1178 $profile = self::getDetailsByURL($data['url'], $uid);
1187 * Returns the data array for the photo menu of a given contact
1189 * @param array $contact contact
1190 * @param int $uid optional, default 0
1192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1193 * @throws \ImagickException
1195 public static function photoMenu(array $contact, $uid = 0)
1200 $contact_drop_link = '';
1204 $uid = local_user();
1207 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1209 $profile_link = self::magicLink($contact['url']);
1210 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1215 // Look for our own contact if the uid doesn't match and isn't public
1216 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1217 if (DBA::isResult($contact_own)) {
1218 return self::photoMenu($contact_own, $uid);
1223 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1225 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1227 $profile_link = $contact['url'];
1230 if ($profile_link === 'mailbox') {
1235 $status_link = $profile_link . '?tab=status';
1236 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1237 $profile_link = $profile_link . '?tab=profile';
1240 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1241 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1244 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1245 $poke_link = DI::baseUrl() . '/poke/?c=' . $contact['id'];
1248 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1250 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1252 if (!$contact['self']) {
1253 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1257 $unfollow_link = '';
1258 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1259 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1260 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1261 } elseif(!$contact['pending']) {
1262 $follow_link = 'follow?url=' . urlencode($contact['url']);
1268 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1270 if (empty($contact['uid'])) {
1272 'profile' => [L10n::t('View Profile') , $profile_link , true],
1273 'network' => [L10n::t('Network Posts') , $posts_link , false],
1274 'edit' => [L10n::t('View Contact') , $contact_url , false],
1275 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1276 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link, true],
1280 'status' => [L10n::t('View Status') , $status_link , true],
1281 'profile' => [L10n::t('View Profile') , $profile_link , true],
1282 'photos' => [L10n::t('View Photos') , $photos_link , true],
1283 'network' => [L10n::t('Network Posts') , $posts_link , false],
1284 'edit' => [L10n::t('View Contact') , $contact_url , false],
1285 'drop' => [L10n::t('Drop Contact') , $contact_drop_link, false],
1286 'pm' => [L10n::t('Send PM') , $pm_url , false],
1287 'poke' => [L10n::t('Poke') , $poke_link , false],
1288 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1289 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link , true],
1292 if (!empty($contact['pending'])) {
1293 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1294 if (DBA::isResult($intro)) {
1295 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1300 $args = ['contact' => $contact, 'menu' => &$menu];
1302 Hook::callAll('contact_photo_menu', $args);
1304 $menucondensed = [];
1306 foreach ($menu as $menuname => $menuitem) {
1307 if ($menuitem[1] != '') {
1308 $menucondensed[$menuname] = $menuitem;
1312 return $menucondensed;
1316 * Returns ungrouped contact count or list for user
1318 * Returns either the total number of ungrouped contacts for the given user
1319 * id or a paginated list of ungrouped contacts.
1321 * @param int $uid uid
1323 * @throws \Exception
1325 public static function getUngroupedList($uid)
1335 SELECT DISTINCT(`contact-id`)
1337 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1338 WHERE `group`.`uid` = %d
1339 )", intval($uid), intval($uid));
1343 * Have a look at all contact tables for a given profile url.
1344 * This function works as a replacement for probing the contact.
1346 * @param string $url Contact URL
1347 * @param integer $cid Contact ID
1349 * @return array Contact array in the "probe" structure
1351 private static function getProbeDataFromDatabase($url, $cid = null)
1353 // The link could be provided as http although we stored it as https
1354 $ssl_url = str_replace('http://', 'https://', $url);
1356 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1357 'photo', 'keywords', 'location', 'about', 'network',
1358 'priority', 'batch', 'request', 'confirm', 'poco'];
1361 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1362 if (DBA::isResult($data)) {
1367 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1369 if (!DBA::isResult($data)) {
1370 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1371 $data = DBA::selectFirst('contact', $fields, $condition);
1374 if (DBA::isResult($data)) {
1375 // For security reasons we don't fetch key data from our users
1376 $data["pubkey"] = '';
1380 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1381 'photo', 'keywords', 'location', 'about', 'network'];
1382 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1384 if (!DBA::isResult($data)) {
1385 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1386 $data = DBA::selectFirst('contact', $fields, $condition);
1389 if (DBA::isResult($data)) {
1390 $data["pubkey"] = '';
1392 $data["priority"] = 0;
1393 $data["batch"] = '';
1394 $data["request"] = '';
1395 $data["confirm"] = '';
1400 $data = ActivityPub::probeProfile($url, false);
1401 if (!empty($data)) {
1405 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1406 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1407 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1409 if (!DBA::isResult($data)) {
1410 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1411 $data = DBA::selectFirst('contact', $fields, $condition);
1414 if (DBA::isResult($data)) {
1415 $data["pubkey"] = '';
1416 $data["keywords"] = '';
1417 $data["location"] = '';
1418 $data["about"] = '';
1427 * Fetch the contact id for a given URL and user
1429 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1430 * `addr` or `alias`.
1432 * If there's no record and we aren't looking for a public contact, we quit.
1433 * If there's one, we check that it isn't time to update the picture else we
1434 * directly return the found contact id.
1436 * Second, we probe the provided $url whether it's http://server.tld/profile or
1437 * nick@server.tld. We quit if we can't get any info back.
1439 * Third, we create the contact record if it doesn't exist
1441 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1442 * if there's any updates
1444 * @param string $url Contact URL
1445 * @param integer $uid The user id for the contact (0 = public contact)
1446 * @param boolean $no_update Don't update the contact
1447 * @param array $default Default value for creating the contact when every else fails
1448 * @param boolean $in_loop Internally used variable to prevent an endless loop
1450 * @return integer Contact ID
1451 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1452 * @throws \ImagickException
1454 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1456 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1464 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1465 // We first try the nurl (http://server.tld/nick), most common case
1466 $fields = ['id', 'avatar', 'updated', 'network'];
1467 $options = ['order' => ['id']];
1468 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1470 // Then the addr (nick@server.tld)
1471 if (!DBA::isResult($contact)) {
1472 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1475 // Then the alias (which could be anything)
1476 if (!DBA::isResult($contact)) {
1477 // The link could be provided as http although we stored it as https
1478 $ssl_url = str_replace('http://', 'https://', $url);
1479 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1480 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1483 if (DBA::isResult($contact)) {
1484 $contact_id = $contact["id"];
1485 $update_contact = false;
1487 // Update the contact every 7 days (Don't update mail or feed contacts)
1488 if (in_array($contact['network'], Protocol::FEDERATED)) {
1489 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1491 // We force the update if the avatar is empty
1492 if (empty($contact['avatar'])) {
1493 $update_contact = true;
1495 } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1496 // Update public mail accounts via their user's accounts
1497 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1498 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1499 if (!DBA::isResult($mailcontact)) {
1500 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1503 if (DBA::isResult($mailcontact)) {
1504 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1508 // Update the contact in the background if needed but it is called by the frontend
1509 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1510 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1513 if (!$update_contact || $no_update) {
1516 } elseif ($uid != 0) {
1517 // Non-existing user-specific contact, exiting
1521 if ($no_update && empty($default)) {
1522 // When we don't want to update, we look if we know this contact in any way
1523 $data = self::getProbeDataFromDatabase($url, $contact_id);
1524 $background_update = true;
1525 } elseif ($no_update && !empty($default['network'])) {
1526 // If there are default values, take these
1528 $background_update = false;
1531 $background_update = false;
1535 $data = Probe::uri($url, "", $uid);
1536 // Ensure that there is a gserver entry
1537 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1538 GServer::check($data['baseurl']);
1542 // Take the default values when probing failed
1543 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1544 $data = array_merge($data, $default);
1547 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1548 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1552 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1553 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1559 'created' => DateTimeFormat::utcNow(),
1560 'url' => $data['url'],
1561 'nurl' => Strings::normaliseLink($data['url']),
1562 'addr' => $data['addr'] ?? '',
1563 'alias' => $data['alias'] ?? '',
1564 'notify' => $data['notify'] ?? '',
1565 'poll' => $data['poll'] ?? '',
1566 'name' => $data['name'] ?? '',
1567 'nick' => $data['nick'] ?? '',
1568 'photo' => $data['photo'] ?? '',
1569 'keywords' => $data['keywords'] ?? '',
1570 'location' => $data['location'] ?? '',
1571 'about' => $data['about'] ?? '',
1572 'network' => $data['network'],
1573 'pubkey' => $data['pubkey'] ?? '',
1574 'rel' => self::SHARING,
1575 'priority' => $data['priority'] ?? 0,
1576 'batch' => $data['batch'] ?? '',
1577 'request' => $data['request'] ?? '',
1578 'confirm' => $data['confirm'] ?? '',
1579 'poco' => $data['poco'] ?? '',
1580 'baseurl' => $data['baseurl'] ?? '',
1581 'name-date' => DateTimeFormat::utcNow(),
1582 'uri-date' => DateTimeFormat::utcNow(),
1583 'avatar-date' => DateTimeFormat::utcNow(),
1589 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1591 // Before inserting we do check if the entry does exist now.
1592 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1593 if (!DBA::isResult($contact)) {
1594 Logger::info('Create new contact', $fields);
1596 self::insert($fields);
1598 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1599 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1600 if (!DBA::isResult($contact)) {
1601 Logger::info('Contact creation failed', $fields);
1606 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1609 $contact_id = $contact["id"];
1612 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1613 self::updateAvatar($data['photo'], $uid, $contact_id);
1616 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1617 if ($background_update) {
1618 // Update in the background when we fetched the data solely from the database
1619 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1621 // Else do a direct update
1622 self::updateFromProbe($contact_id, '', false);
1624 // Update the gcontact entry
1626 GContact::updateFromPublicContactID($contact_id);
1630 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1631 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1633 // This condition should always be true
1634 if (!DBA::isResult($contact)) {
1639 'url' => $data['url'],
1640 'nurl' => Strings::normaliseLink($data['url']),
1641 'updated' => DateTimeFormat::utcNow()
1644 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1646 foreach ($fields as $field) {
1647 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1650 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1651 $updated['uri-date'] = DateTimeFormat::utcNow();
1654 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1655 $updated['name-date'] = DateTimeFormat::utcNow();
1658 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1665 * Checks if the contact is archived
1667 * @param int $cid contact id
1669 * @return boolean Is the contact archived?
1670 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1672 public static function isArchived(int $cid)
1678 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1679 if (!DBA::isResult($contact)) {
1683 if ($contact['archive']) {
1687 // Check status of ActivityPub endpoints
1688 $apcontact = APContact::getByURL($contact['url'], false);
1689 if (!empty($apcontact)) {
1690 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1694 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1699 // Check status of Diaspora endpoints
1700 if (!empty($contact['batch'])) {
1701 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1702 return DBA::exists('contact', $condition);
1709 * Checks if the contact is blocked
1711 * @param int $cid contact id
1713 * @return boolean Is the contact blocked?
1714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1716 public static function isBlocked($cid)
1722 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1723 if (!DBA::isResult($blocked)) {
1727 if (Network::isUrlBlocked($blocked['url'])) {
1731 return (bool) $blocked['blocked'];
1735 * Checks if the contact is hidden
1737 * @param int $cid contact id
1739 * @return boolean Is the contact hidden?
1740 * @throws \Exception
1742 public static function isHidden($cid)
1748 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1749 if (!DBA::isResult($hidden)) {
1752 return (bool) $hidden['hidden'];
1756 * Returns posts from a given contact url
1758 * @param string $contact_url Contact URL
1760 * @param bool $thread_mode
1761 * @param int $update
1762 * @return string posts in HTML
1763 * @throws \Exception
1765 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1769 $cid = self::getIdForURL($contact_url);
1771 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1772 if (!DBA::isResult($contact)) {
1776 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1777 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1779 $sql = "`item`.`uid` = ?";
1782 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1785 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1786 $cid, GRAVITY_PARENT, local_user()];
1788 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1789 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1792 $pager = new Pager(DI::args()->getQueryString());
1794 $params = ['order' => ['received' => true],
1795 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1798 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1800 $items = Item::inArray($r);
1802 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1804 $r = Item::selectForUser(local_user(), [], $condition, $params);
1806 $items = Item::inArray($r);
1808 $o = conversation($a, $items, $pager, 'contact-posts', false);
1812 $o .= $pager->renderMinimal(count($items));
1819 * Returns the account type name
1821 * The function can be called with either the user or the contact array
1823 * @param array $contact contact or user array
1826 public static function getAccountType(array $contact)
1828 // There are several fields that indicate that the contact or user is a forum
1829 // "page-flags" is a field in the user table,
1830 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1831 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1832 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1833 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1834 || (isset($contact['forum']) && intval($contact['forum']))
1835 || (isset($contact['prv']) && intval($contact['prv']))
1836 || (isset($contact['community']) && intval($contact['community']))
1838 $type = self::TYPE_COMMUNITY;
1840 $type = self::TYPE_PERSON;
1843 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1844 if (isset($contact["contact-type"])) {
1845 $type = $contact["contact-type"];
1848 if (isset($contact["account-type"])) {
1849 $type = $contact["account-type"];
1853 case self::TYPE_ORGANISATION:
1854 $account_type = L10n::t("Organisation");
1857 case self::TYPE_NEWS:
1858 $account_type = L10n::t('News');
1861 case self::TYPE_COMMUNITY:
1862 $account_type = L10n::t("Forum");
1870 return $account_type;
1878 * @throws \Exception
1880 public static function block($cid, $reason = null)
1882 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1888 * Unblocks a contact
1892 * @throws \Exception
1894 public static function unblock($cid)
1896 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1902 * Updates the avatar links in a contact only if needed
1904 * @param string $avatar Link to avatar picture
1905 * @param int $uid User id of contact owner
1906 * @param int $cid Contact id
1907 * @param bool $force force picture update
1909 * @return array Returns array of the different avatar sizes
1910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1911 * @throws \ImagickException
1913 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1915 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1916 if (!DBA::isResult($contact)) {
1919 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1922 foreach ($data as $image_uri) {
1923 $image_rid = Photo::ridFromURI($image_uri);
1924 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1925 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1930 if (($contact["avatar"] != $avatar) || $force) {
1931 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1934 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1935 DBA::update('contact', $fields, ['id' => $cid]);
1937 // Update the public contact (contact id = 0)
1939 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1940 if (DBA::isResult($pcontact)) {
1941 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1953 * Helper function for "updateFromProbe". Updates personal and public contact
1955 * @param integer $id contact id
1956 * @param integer $uid user id
1957 * @param string $url The profile URL of the contact
1958 * @param array $fields The fields that are updated
1960 * @throws \Exception
1962 private static function updateContact($id, $uid, $url, array $fields)
1964 if (!DBA::update('contact', $fields, ['id' => $id])) {
1965 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1969 // Search for duplicated contacts and get rid of them
1970 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1974 // Update the corresponding gcontact entry
1975 GContact::updateFromPublicContactID($id);
1977 // Archive or unarchive the contact. We only need to do this for the public contact.
1978 // The archive/unarchive function will update the personal contacts by themselves.
1979 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1980 if (!DBA::isResult($contact)) {
1981 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1985 if (!empty($fields['success_update'])) {
1986 self::unmarkForArchival($contact);
1987 } elseif (!empty($fields['failure_update'])) {
1988 self::markForArchival($contact);
1991 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1993 // These contacts are sharing with us, we don't poll them.
1994 // This means that we don't set the update fields in "OnePoll.php".
1995 $condition['rel'] = self::SHARING;
1996 DBA::update('contact', $fields, $condition);
1998 unset($fields['last-update']);
1999 unset($fields['success_update']);
2000 unset($fields['failure_update']);
2002 if (empty($fields)) {
2006 // We are polling these contacts, so we mustn't set the update fields here.
2007 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2008 DBA::update('contact', $fields, $condition);
2012 * Remove duplicated contacts
2014 * @param string $nurl Normalised contact url
2015 * @param integer $uid User id
2017 * @throws \Exception
2019 public static function removeDuplicates(string $nurl, int $uid)
2021 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2022 $count = DBA::count('contact', $condition);
2027 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2028 if (!DBA::isResult($first_contact)) {
2029 // Shouldn't happen - so we handle it
2033 $first = $first_contact['id'];
2034 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2035 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2036 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2037 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2041 // Find all duplicates
2042 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2043 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2044 while ($duplicate = DBA::fetch($duplicates)) {
2045 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2049 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2051 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2056 * @param integer $id contact id
2057 * @param string $network Optional network we are probing for
2058 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2060 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2061 * @throws \ImagickException
2063 public static function updateFromProbe($id, $network = '', $force = false)
2066 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2067 This will reliably kill your communication with old Friendica contacts.
2070 // These fields aren't updated by this routine:
2071 // 'xmpp', 'sensitive'
2073 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2074 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2075 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2076 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2077 if (!DBA::isResult($contact)) {
2081 $uid = $contact['uid'];
2082 unset($contact['uid']);
2084 $pubkey = $contact['pubkey'];
2085 unset($contact['pubkey']);
2087 $contact['photo'] = $contact['avatar'];
2088 unset($contact['avatar']);
2090 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2092 $updated = DateTimeFormat::utcNow();
2094 // We must not try to update relay contacts via probe. They are no real contacts.
2095 // We check after the probing to be able to correct falsely detected contact types.
2096 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2097 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2098 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2099 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2103 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2104 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2105 if ($force && ($uid == 0)) {
2106 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2111 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2112 $ret['unsearchable'] = $ret['hide'];
2115 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2116 $ret['forum'] = false;
2117 $ret['prv'] = false;
2118 $ret['contact-type'] = $ret['account-type'];
2119 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2120 $apcontact = APContact::getByURL($ret['url'], false);
2121 if (isset($apcontact['manually-approve'])) {
2122 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2123 $ret['prv'] = (bool)!$ret['forum'];
2128 $new_pubkey = $ret['pubkey'];
2132 // make sure to not overwrite existing values with blank entries except some technical fields
2133 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2134 foreach ($ret as $key => $val) {
2135 if (!array_key_exists($key, $contact)) {
2137 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2138 $ret[$key] = $contact[$key];
2139 } elseif ($ret[$key] != $contact[$key]) {
2144 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2145 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2150 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2153 // Update the public contact
2155 self::updateFromProbeByURL($ret['url']);
2161 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2162 $ret['updated'] = $updated;
2164 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2165 if (empty($pubkey) && !empty($new_pubkey)) {
2166 $ret['pubkey'] = $new_pubkey;
2169 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2170 $ret['uri-date'] = DateTimeFormat::utcNow();
2173 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2174 $ret['name-date'] = $updated;
2177 if ($force && ($uid == 0)) {
2178 $ret['last-update'] = $updated;
2179 $ret['success_update'] = $updated;
2182 unset($ret['photo']);
2184 self::updateContact($id, $uid, $ret['url'], $ret);
2189 public static function updateFromProbeByURL($url, $force = false)
2191 $id = self::getIdForURL($url);
2197 self::updateFromProbe($id, '', $force);
2203 * Detects if a given contact array belongs to a legacy DFRN connection
2205 * @param array $contact
2208 public static function isLegacyDFRNContact($contact)
2210 // Newer Friendica contacts are connected via AP, then these fields aren't set
2211 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2215 * Detects the communication protocol for a given contact url.
2216 * This is used to detect Friendica contacts that we can communicate via AP.
2218 * @param string $url contact url
2219 * @param string $network Network of that contact
2220 * @return string with protocol
2222 public static function getProtocol($url, $network)
2224 if ($network != Protocol::DFRN) {
2228 $apcontact = APContact::getByURL($url);
2229 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2230 return Protocol::ACTIVITYPUB;
2237 * Takes a $uid and a url/handle and adds a new contact
2238 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2239 * dfrn_request page.
2241 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2244 * $return['success'] boolean true if successful
2245 * $return['message'] error text if success is false.
2247 * Takes a $uid and a url/handle and adds a new contact
2249 * @param string $url
2250 * @param bool $interactive
2251 * @param string $network
2253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2254 * @throws \ImagickException
2256 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2258 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2262 // remove ajax junk, e.g. Twitter
2263 $url = str_replace('/#!/', '/', $url);
2265 if (!Network::isUrlAllowed($url)) {
2266 $result['message'] = L10n::t('Disallowed profile URL.');
2270 if (Network::isUrlBlocked($url)) {
2271 $result['message'] = L10n::t('Blocked domain');
2276 $result['message'] = L10n::t('Connect URL missing.');
2280 $arr = ['url' => $url, 'contact' => []];
2282 Hook::callAll('follow', $arr);
2285 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2289 if (!empty($arr['contact']['name'])) {
2290 $ret = $arr['contact'];
2292 $ret = Probe::uri($url, $network, $uid, false);
2295 if (($network != '') && ($ret['network'] != $network)) {
2296 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2300 // check if we already have a contact
2301 // the poll url is more reliable than the profile url, as we may have
2302 // indirect links or webfinger links
2304 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2305 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2306 if (!DBA::isResult($contact)) {
2307 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2308 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2311 $protocol = self::getProtocol($url, $ret['network']);
2313 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2315 if (strlen(DI::baseUrl()->getUrlPath())) {
2316 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $a->user['nickname']);
2318 $myaddr = bin2hex($a->user['nickname'] . '@' . DI::baseUrl()->getHostname());
2321 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2325 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2326 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2327 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2331 // This extra param just confuses things, remove it
2332 if ($protocol === Protocol::DIASPORA) {
2333 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2336 // do we have enough information?
2337 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2338 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2339 if (empty($ret['poll'])) {
2340 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2342 if (empty($ret['name'])) {
2343 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2345 if (empty($ret['url'])) {
2346 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2348 if (strpos($url, '@') !== false) {
2349 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2350 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2355 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2356 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2357 $ret['notify'] = '';
2360 if (!$ret['notify']) {
2361 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2364 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2366 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2368 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2371 if ($protocol == Protocol::ACTIVITYPUB) {
2372 $apcontact = APContact::getByURL($url, false);
2373 if (isset($apcontact['manually-approve'])) {
2374 $pending = (bool)$apcontact['manually-approve'];
2378 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2382 if (DBA::isResult($contact)) {
2384 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2386 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2387 DBA::update('contact', $fields, ['id' => $contact['id']]);
2389 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2391 // create contact record
2394 'created' => DateTimeFormat::utcNow(),
2395 'url' => $ret['url'],
2396 'nurl' => Strings::normaliseLink($ret['url']),
2397 'addr' => $ret['addr'],
2398 'alias' => $ret['alias'],
2399 'batch' => $ret['batch'],
2400 'notify' => $ret['notify'],
2401 'poll' => $ret['poll'],
2402 'poco' => $ret['poco'],
2403 'name' => $ret['name'],
2404 'nick' => $ret['nick'],
2405 'network' => $ret['network'],
2406 'baseurl' => $ret['baseurl'],
2407 'protocol' => $protocol,
2408 'pubkey' => $ret['pubkey'],
2409 'rel' => $new_relation,
2410 'priority'=> $ret['priority'],
2411 'writable'=> $writeable,
2412 'hidden' => $hidden,
2415 'pending' => $pending,
2420 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2421 if (!DBA::isResult($contact)) {
2422 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2426 $contact_id = $contact['id'];
2427 $result['cid'] = $contact_id;
2429 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2431 // Update the avatar
2432 self::updateAvatar($ret['photo'], $uid, $contact_id);
2434 // pull feed and consume it, which should subscribe to the hub.
2436 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2438 $owner = User::getOwnerDataById($uid);
2440 if (DBA::isResult($owner)) {
2441 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2442 // create a follow slap
2444 $item['verb'] = Activity::FOLLOW;
2445 $item['follow'] = $contact["url"];
2447 $item['title'] = '';
2450 $item['attach'] = '';
2452 $slap = OStatus::salmon($item, $owner);
2454 if (!empty($contact['notify'])) {
2455 Salmon::slapper($owner, $contact['notify'], $slap);
2457 } elseif ($protocol == Protocol::DIASPORA) {
2458 $ret = Diaspora::sendShare($a->user, $contact);
2459 Logger::log('share returns: ' . $ret);
2460 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2461 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2462 if (empty($activity_id)) {
2463 // This really should never happen
2467 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2468 Logger::log('Follow returns: ' . $ret);
2472 $result['success'] = true;
2477 * Updated contact's SSL policy
2479 * @param array $contact Contact array
2480 * @param string $new_policy New policy, valid: self,full
2482 * @return array Contact array with updated values
2483 * @throws \Exception
2485 public static function updateSslPolicy(array $contact, $new_policy)
2487 $ssl_changed = false;
2488 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2489 $ssl_changed = true;
2490 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2491 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2492 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2493 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2494 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2495 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2498 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2499 $ssl_changed = true;
2500 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2501 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2502 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2503 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2504 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2505 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2509 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2510 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2511 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2512 DBA::update('contact', $fields, ['id' => $contact['id']]);
2519 * @param array $importer Owner (local user) data
2520 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2521 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2522 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2523 * @param string $note Introduction additional message
2524 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2525 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2526 * @throws \ImagickException
2528 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2530 // Should always be set
2531 if (empty($datarray['author-id'])) {
2535 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2536 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2537 if (!DBA::isResult($pub_contact)) {
2538 // Should never happen
2542 // Contact is blocked at node-level
2543 if (self::isBlocked($datarray['author-id'])) {
2547 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2548 $name = $pub_contact['name'];
2549 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2550 $nick = $pub_contact['nick'];
2551 $network = $pub_contact['network'];
2553 // Ensure that we don't create a new contact when there already is one
2554 $cid = self::getIdForURL($url, $importer['uid']);
2556 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2559 if (!empty($contact)) {
2560 if (!empty($contact['pending'])) {
2561 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2565 // Contact is blocked at user-level
2566 if (!empty($contact['id']) && !empty($importer['id']) &&
2567 self::isBlockedByUser($contact['id'], $importer['id'])) {
2571 // Make sure that the existing contact isn't archived
2572 self::unmarkForArchival($contact);
2574 if (($contact['rel'] == self::SHARING)
2575 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2576 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2577 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2580 // Ensure to always have the correct network type, independent from the connection request method
2581 self::updateFromProbe($contact['id'], '', true);
2585 // send email notification to owner?
2586 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2587 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2591 // create contact record
2592 DBA::insert('contact', [
2593 'uid' => $importer['uid'],
2594 'created' => DateTimeFormat::utcNow(),
2596 'nurl' => Strings::normaliseLink($url),
2600 'network' => $network,
2601 'rel' => self::FOLLOWER,
2608 $contact_id = DBA::lastInsertId();
2610 // Ensure to always have the correct network type, independent from the connection request method
2611 self::updateFromProbe($contact_id, '', true);
2613 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2615 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2617 /// @TODO Encapsulate this into a function/method
2618 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2619 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2620 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2621 // create notification
2622 $hash = Strings::getRandomHex();
2624 if (is_array($contact_record)) {
2625 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2626 'blocked' => false, 'knowyou' => false, 'note' => $note,
2627 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2630 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2632 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2633 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2636 'type' => NOTIFY_INTRO,
2637 'notify_flags' => $user['notify-flags'],
2638 'language' => $user['language'],
2639 'to_name' => $user['username'],
2640 'to_email' => $user['email'],
2641 'uid' => $user['uid'],
2642 'link' => DI::baseUrl() . '/notifications/intro',
2643 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2644 'source_link' => $contact_record['url'],
2645 'source_photo' => $contact_record['photo'],
2646 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2650 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2651 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2652 DBA::update('contact', ['pending' => false], $condition);
2661 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2663 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2664 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2666 Contact::remove($contact['id']);
2670 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2672 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2673 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2675 Contact::remove($contact['id']);
2680 * Create a birthday event.
2682 * Update the year and the birthday.
2684 public static function updateBirthdays()
2688 AND `bd` > "0001-01-01"
2689 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2690 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2691 AND NOT `contact`.`pending`
2692 AND NOT `contact`.`hidden`
2693 AND NOT `contact`.`blocked`
2694 AND NOT `contact`.`archive`
2695 AND NOT `contact`.`deleted`',
2700 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2702 while ($contact = DBA::fetch($contacts)) {
2703 Logger::log('update_contact_birthday: ' . $contact['bd']);
2705 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2707 if (Event::createBirthday($contact, $nextbd)) {
2711 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2712 ['id' => $contact['id']]
2719 * Remove the unavailable contact ids from the provided list
2721 * @param array $contact_ids Contact id list
2723 * @throws \Exception
2725 public static function pruneUnavailable(array $contact_ids)
2727 if (empty($contact_ids)) {
2731 $contacts = Contact::selectToArray(['id'], [
2732 'id' => $contact_ids,
2738 return array_column($contacts, 'id');
2742 * Returns a magic link to authenticate remote visitors
2744 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2746 * @param string $contact_url The address of the target contact profile
2747 * @param string $url An url that we will be redirected to after the authentication
2749 * @return string with "redir" link
2750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2751 * @throws \ImagickException
2753 public static function magicLink($contact_url, $url = '')
2755 if (!Session::isAuthenticated()) {
2756 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2759 $data = self::getProbeDataFromDatabase($contact_url);
2761 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2764 // Prevents endless loop in case only a non-public contact exists for the contact URL
2765 unset($data['uid']);
2767 return self::magicLinkByContact($data, $url ?: $contact_url);
2771 * Returns a magic link to authenticate remote visitors
2773 * @param integer $cid The contact id of the target contact profile
2774 * @param string $url An url that we will be redirected to after the authentication
2776 * @return string with "redir" link
2777 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2778 * @throws \ImagickException
2780 public static function magicLinkbyId($cid, $url = '')
2782 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2784 return self::magicLinkByContact($contact, $url);
2788 * Returns a magic link to authenticate remote visitors
2790 * @param array $contact The contact array with "uid", "network" and "url"
2791 * @param string $url An url that we will be redirected to after the authentication
2793 * @return string with "redir" link
2794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2795 * @throws \ImagickException
2797 public static function magicLinkByContact($contact, $url = '')
2799 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2801 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2802 return $destination;
2805 // Only redirections to the same host do make sense
2806 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2810 if (!empty($contact['uid'])) {
2811 return self::magicLink($contact['url'], $url);
2814 if (empty($contact['id'])) {
2815 return $destination;
2818 $redirect = 'redir/' . $contact['id'];
2820 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2821 $redirect .= '?url=' . $url;
2828 * Remove a contact from all groups
2830 * @param integer $contact_id
2832 * @return boolean Success
2834 public static function removeFromGroups($contact_id)
2836 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2840 * Is the contact a forum?
2842 * @param integer $contactid ID of the contact
2844 * @return boolean "true" if it is a forum
2846 public static function isForum($contactid)
2848 $fields = ['forum', 'prv'];
2849 $condition = ['id' => $contactid];
2850 $contact = DBA::selectFirst('contact', $fields, $condition);
2851 if (!DBA::isResult($contact)) {
2856 return ($contact['forum'] || $contact['prv']);
2860 * Can the remote contact receive private messages?
2862 * @param array $contact
2865 public static function canReceivePrivateMessages(array $contact)
2867 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2868 $self = $contact['self'] ?? false;
2870 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;