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\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\Session;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\Activity;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\Salmon;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Images;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
31 * functions for interacting with a contact
36 * @deprecated since version 2019.03
37 * @see User::PAGE_FLAGS_NORMAL
39 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
41 * @deprecated since version 2019.03
42 * @see User::PAGE_FLAGS_SOAPBOX
44 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
46 * @deprecated since version 2019.03
47 * @see User::PAGE_FLAGS_COMMUNITY
49 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
51 * @deprecated since version 2019.03
52 * @see User::PAGE_FLAGS_FREELOVE
54 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
56 * @deprecated since version 2019.03
57 * @see User::PAGE_FLAGS_BLOG
59 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_PRVGROUP
64 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
72 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
74 * TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
77 * TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_SOAPBOX
83 * TYPE_COMMUNITY - the account is community forum
84 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
86 * TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const TYPE_UNKNOWN = -1;
91 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
92 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
93 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
94 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
95 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
114 * @param array $fields Array of selected fields, empty for all
115 * @param array $condition Array of fields for condition
116 * @param array $params Array of several parameters
120 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
122 return DBA::selectToArray('contact', $fields, $condition, $params);
126 * @param array $fields Array of selected fields, empty for all
127 * @param array $condition Array of fields for condition
128 * @param array $params Array of several parameters
132 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
134 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
140 * Insert a row into the contact table
141 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
143 * @param array $fields field array
144 * @param bool $on_duplicate_update Do an update on a duplicate entry
146 * @return boolean was the insert successful?
149 public static function insert(array $fields, bool $on_duplicate_update = false)
151 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
152 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
153 if (!DBA::isResult($contact)) {
158 // Search for duplicated contacts and get rid of them
159 self::removeDuplicates($contact['nurl'], $contact['uid']);
165 * @param integer $id Contact ID
166 * @param array $fields Array of selected fields, empty for all
167 * @return array|boolean Contact record if it exists, false otherwise
170 public static function getById($id, $fields = [])
172 return DBA::selectFirst('contact', $fields, ['id' => $id]);
176 * Tests if the given contact is a follower
178 * @param int $cid Either public contact id or user's contact id
179 * @param int $uid User ID
181 * @return boolean is the contact id a follower?
182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
183 * @throws \ImagickException
185 public static function isFollower($cid, $uid)
187 if (self::isBlockedByUser($cid, $uid)) {
191 $cdata = self::getPublicAndUserContacID($cid, $uid);
192 if (empty($cdata['user'])) {
196 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
197 return DBA::exists('contact', $condition);
201 * Tests if the given contact url is a follower
203 * @param string $url Contact URL
204 * @param int $uid User ID
206 * @return boolean is the contact id a follower?
207 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208 * @throws \ImagickException
210 public static function isFollowerByURL($url, $uid)
212 $cid = self::getIdForURL($url, $uid, true);
218 return self::isFollower($cid, $uid);
222 * Tests if the given user follow the given contact
224 * @param int $cid Either public contact id or user's contact id
225 * @param int $uid User ID
227 * @return boolean is the contact url being followed?
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229 * @throws \ImagickException
231 public static function isSharing($cid, $uid)
233 if (self::isBlockedByUser($cid, $uid)) {
237 $cdata = self::getPublicAndUserContacID($cid, $uid);
238 if (empty($cdata['user'])) {
242 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
243 return DBA::exists('contact', $condition);
247 * Tests if the given user follow the given contact url
249 * @param string $url Contact URL
250 * @param int $uid User ID
252 * @return boolean is the contact url being followed?
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 public static function isSharingByURL($url, $uid)
258 $cid = self::getIdForURL($url, $uid, true);
264 return self::isSharing($cid, $uid);
268 * Get the basepath for a given contact link
270 * @param string $url The contact link
271 * @param boolean $dont_update Don't update the contact
273 * @return string basepath
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275 * @throws \ImagickException
277 public static function getBasepath($url, $dont_update = false)
279 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
280 if (!DBA::isResult($contact)) {
284 if (!empty($contact['baseurl'])) {
285 return $contact['baseurl'];
286 } elseif ($dont_update) {
290 // Update the existing contact
291 self::updateFromProbe($contact['id'], '', true);
293 // And fetch the result
294 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
295 if (empty($contact['baseurl'])) {
296 Logger::info('No baseurl for contact', ['url' => $url]);
300 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
301 return $contact['baseurl'];
305 * Check if the given contact url is on the same server
307 * @param string $url The contact link
309 * @return boolean Is it the same server?
311 public static function isLocal($url)
313 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
317 * Check if the given contact ID is on the same server
319 * @param string $url The contact link
321 * @return boolean Is it the same server?
323 public static function isLocalById(int $cid)
325 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
326 if (!DBA::isResult($contact)) {
330 if (empty($contact['baseurl'])) {
331 $baseurl = self::getBasepath($contact['url'], true);
333 $baseurl = $contact['baseurl'];
336 return Strings::compareLink($baseurl, DI::baseUrl());
340 * Returns the public contact id of the given user id
342 * @param integer $uid User ID
344 * @return integer|boolean Public contact id for given user id
347 public static function getPublicIdByUserId($uid)
349 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
350 if (!DBA::isResult($self)) {
353 return self::getIdForURL($self['url'], 0, true);
357 * Returns the contact id for the user and the public contact id for a given contact id
359 * @param int $cid Either public contact id or user's contact id
360 * @param int $uid User ID
362 * @return array with public and user's contact id
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 * @throws \ImagickException
366 public static function getPublicAndUserContacID($cid, $uid)
368 if (empty($uid) || empty($cid)) {
372 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
373 if (!DBA::isResult($contact)) {
377 // We quit when the user id don't match the user id of the provided contact
378 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
382 if ($contact['uid'] != 0) {
383 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
387 $ucid = $contact['id'];
389 $pcid = $contact['id'];
390 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
393 return ['public' => $pcid, 'user' => $ucid];
397 * Returns contact details for a given contact id in combination with a user id
399 * @param int $cid A contact ID
400 * @param int $uid The User ID
401 * @param array $fields The selected fields for the contact
403 * @return array The contact details
407 public static function getContactForUser($cid, $uid, array $fields = [])
409 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
411 if (!DBA::isResult($contact)) {
419 * Block contact id for user id
421 * @param int $cid Either public contact id or user's contact id
422 * @param int $uid User ID
423 * @param boolean $blocked Is the contact blocked or unblocked?
426 public static function setBlockedForUser($cid, $uid, $blocked)
428 $cdata = self::getPublicAndUserContacID($cid, $uid);
433 if ($cdata['user'] != 0) {
434 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
437 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
441 * Returns "block" state for contact id and user id
443 * @param int $cid Either public contact id or user's contact id
444 * @param int $uid User ID
446 * @return boolean is the contact id blocked for the given user?
449 public static function isBlockedByUser($cid, $uid)
451 $cdata = self::getPublicAndUserContacID($cid, $uid);
456 $public_blocked = false;
458 if (!empty($cdata['public'])) {
459 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
460 if (DBA::isResult($public_contact)) {
461 $public_blocked = $public_contact['blocked'];
465 $user_blocked = $public_blocked;
467 if (!empty($cdata['user'])) {
468 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
469 if (DBA::isResult($user_contact)) {
470 $user_blocked = $user_contact['blocked'];
474 if ($user_blocked != $public_blocked) {
475 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
478 return $user_blocked;
482 * Ignore contact id for user id
484 * @param int $cid Either public contact id or user's contact id
485 * @param int $uid User ID
486 * @param boolean $ignored Is the contact ignored or unignored?
489 public static function setIgnoredForUser($cid, $uid, $ignored)
491 $cdata = self::getPublicAndUserContacID($cid, $uid);
496 if ($cdata['user'] != 0) {
497 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
500 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
504 * Returns "ignore" state for contact id and user id
506 * @param int $cid Either public contact id or user's contact id
507 * @param int $uid User ID
509 * @return boolean is the contact id ignored for the given user?
512 public static function isIgnoredByUser($cid, $uid)
514 $cdata = self::getPublicAndUserContacID($cid, $uid);
519 $public_ignored = false;
521 if (!empty($cdata['public'])) {
522 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
523 if (DBA::isResult($public_contact)) {
524 $public_ignored = $public_contact['ignored'];
528 $user_ignored = $public_ignored;
530 if (!empty($cdata['user'])) {
531 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
532 if (DBA::isResult($user_contact)) {
533 $user_ignored = $user_contact['readonly'];
537 if ($user_ignored != $public_ignored) {
538 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
541 return $user_ignored;
545 * Set "collapsed" for contact id and user id
547 * @param int $cid Either public contact id or user's contact id
548 * @param int $uid User ID
549 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
552 public static function setCollapsedForUser($cid, $uid, $collapsed)
554 $cdata = self::getPublicAndUserContacID($cid, $uid);
559 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
563 * Returns "collapsed" state for contact id and user id
565 * @param int $cid Either public contact id or user's contact id
566 * @param int $uid User ID
568 * @return boolean is the contact id blocked for the given user?
569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
570 * @throws \ImagickException
572 public static function isCollapsedByUser($cid, $uid)
574 $cdata = self::getPublicAndUserContacID($cid, $uid);
581 if (!empty($cdata['public'])) {
582 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
583 if (DBA::isResult($public_contact)) {
584 $collapsed = $public_contact['collapsed'];
592 * Returns a list of contacts belonging in a group
598 public static function getByGroupId($gid)
603 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
605 INNER JOIN `group_member`
606 ON `contact`.`id` = `group_member`.`contact-id`
608 AND `contact`.`uid` = ?
609 AND NOT `contact`.`self`
610 AND NOT `contact`.`deleted`
611 AND NOT `contact`.`blocked`
612 AND NOT `contact`.`pending`
613 ORDER BY `contact`.`name` ASC',
618 if (DBA::isResult($stmt)) {
619 $return = DBA::toArray($stmt);
627 * Returns the count of OStatus contacts in a group
633 public static function getOStatusCountByGroupId($gid)
637 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
639 INNER JOIN `group_member`
640 ON `contact`.`id` = `group_member`.`contact-id`
642 AND `contact`.`uid` = ?
643 AND `contact`.`network` = ?
644 AND `contact`.`notify` != ""',
649 $return = $contacts['count'];
656 * Creates the self-contact for the provided user id
659 * @return bool Operation success
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 public static function createSelfFromUserId($uid)
664 // Only create the entry if it doesn't exist yet
665 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
669 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
670 if (!DBA::isResult($user)) {
674 $return = DBA::insert('contact', [
675 'uid' => $user['uid'],
676 'created' => DateTimeFormat::utcNow(),
678 'name' => $user['username'],
679 'nick' => $user['nickname'],
680 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
681 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
682 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
685 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
686 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
687 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
688 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
689 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
690 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
691 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
692 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
693 'name-date' => DateTimeFormat::utcNow(),
694 'uri-date' => DateTimeFormat::utcNow(),
695 'avatar-date' => DateTimeFormat::utcNow(),
703 * Updates the self-contact for the provided user id
706 * @param boolean $update_avatar Force the avatar update
707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709 public static function updateSelfFromUserID($uid, $update_avatar = false)
711 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
712 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
713 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
714 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
715 if (!DBA::isResult($self)) {
719 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
720 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
721 if (!DBA::isResult($user)) {
725 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
726 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
727 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
728 if (!DBA::isResult($profile)) {
732 $file_suffix = 'jpg';
734 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
735 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
736 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
737 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
738 'xmpp' => $profile['xmpp']];
740 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
741 if (DBA::isResult($avatar)) {
742 if ($update_avatar) {
743 $fields['avatar-date'] = DateTimeFormat::utcNow();
746 // Creating the path to the avatar, beginning with the file suffix
747 $types = Images::supportedTypes();
748 if (isset($types[$avatar['type']])) {
749 $file_suffix = $types[$avatar['type']];
752 // We are adding a timestamp value so that other systems won't use cached content
753 $timestamp = strtotime($fields['avatar-date']);
755 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
756 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
758 $fields['photo'] = $prefix . '4' . $suffix;
759 $fields['thumb'] = $prefix . '5' . $suffix;
760 $fields['micro'] = $prefix . '6' . $suffix;
762 // We hadn't found a photo entry, so we use the default avatar
763 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
764 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
765 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
768 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
769 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
770 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
771 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
773 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
774 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
775 $fields['nurl'] = Strings::normaliseLink($fields['url']);
776 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
777 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
778 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
779 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
780 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
781 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
785 foreach ($fields as $field => $content) {
786 if ($self[$field] != $content) {
792 if ($fields['name'] != $self['name']) {
793 $fields['name-date'] = DateTimeFormat::utcNow();
795 $fields['updated'] = DateTimeFormat::utcNow();
796 DBA::update('contact', $fields, ['id' => $self['id']]);
798 // Update the public contact as well
799 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
801 // Update the profile
802 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
803 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
804 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
809 * Marks a contact for removal
811 * @param int $id contact id
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 public static function remove($id)
817 // We want just to make sure that we don't delete our "self" contact
818 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
819 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
823 // Archive the contact
824 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
826 // Delete it in the background
827 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
831 * Sends an unfriend message. Does not remove the contact
833 * @param array $user User unfriending
834 * @param array $contact Contact unfriended
835 * @param boolean $dissolve Remove the contact on the remote side
837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
838 * @throws \ImagickException
840 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
842 if (empty($contact['network'])) {
846 $protocol = $contact['network'];
847 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
848 $protocol = Protocol::ACTIVITYPUB;
851 if (($protocol == Protocol::DFRN) && $dissolve) {
852 DFRN::deliver($user, $contact, 'placeholder', true);
853 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
854 // create an unfollow slap
856 $item['verb'] = Activity::O_UNFOLLOW;
857 $item['follow'] = $contact["url"];
862 $item['attach'] = '';
863 $slap = OStatus::salmon($item, $user);
865 if (!empty($contact['notify'])) {
866 Salmon::slapper($user, $contact['notify'], $slap);
868 } elseif ($protocol == Protocol::DIASPORA) {
869 Diaspora::sendUnshare($user, $contact);
870 } elseif ($protocol == Protocol::ACTIVITYPUB) {
871 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
874 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
880 * Marks a contact for archival after a communication issue delay
882 * Contact has refused to recognise us as a friend. We will start a countdown.
883 * If they still don't recognise us in 32 days, the relationship is over,
884 * and we won't waste any more time trying to communicate with them.
885 * This provides for the possibility that their database is temporarily messed
886 * up or some other transient event and that there's a possibility we could recover from it.
888 * @param array $contact contact to mark for archival
890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
892 public static function markForArchival(array $contact)
894 if (!isset($contact['url']) && !empty($contact['id'])) {
895 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
896 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
897 if (!DBA::isResult($contact)) {
900 } elseif (!isset($contact['url'])) {
901 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
904 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
906 // Contact already archived or "self" contact? => nothing to do
907 if ($contact['archive'] || $contact['self']) {
911 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
912 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
913 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
916 * We really should send a notification to the owner after 2-3 weeks
917 * so they won't be surprised when the contact vanishes and can take
918 * remedial action if this was a serious mistake or glitch
921 /// @todo Check for contact vitality via probing
922 $archival_days = Config::get('system', 'archival_days', 32);
924 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
925 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
926 /* Relationship is really truly dead. archive them rather than
927 * delete, though if the owner tries to unarchive them we'll start
928 * the whole process over again.
930 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
931 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
932 GContact::updateFromPublicContactURL($contact['url']);
938 * Cancels the archival countdown
940 * @see Contact::markForArchival()
942 * @param array $contact contact to be unmarked for archival
946 public static function unmarkForArchival(array $contact)
948 // Always unarchive the relay contact entry
949 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
950 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
951 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
952 DBA::update('contact', $fields, $condition);
955 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
956 $exists = DBA::exists('contact', $condition);
958 // We don't need to update, we never marked this contact for archival
963 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
965 if (!isset($contact['url']) && !empty($contact['id'])) {
966 $fields = ['id', 'url', 'batch'];
967 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
968 if (!DBA::isResult($contact)) {
973 // It's a miracle. Our dead contact has inexplicably come back to life.
974 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
975 DBA::update('contact', $fields, ['id' => $contact['id']]);
976 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
977 GContact::updateFromPublicContactURL($contact['url']);
981 * Get contact data for a given profile link
983 * The function looks at several places (contact table and gcontact table) for the contact
984 * It caches its result for the same script execution to prevent duplicate calls
986 * @param string $url The profile link
987 * @param int $uid User id
988 * @param array $default If not data was found take this data as default value
990 * @return array Contact data
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 public static function getDetailsByURL($url, $uid = -1, array $default = [])
1002 $uid = local_user();
1005 if (isset($cache[$url][$uid])) {
1006 return $cache[$url][$uid];
1009 $ssl_url = str_replace('http://', 'https://', $url);
1011 $nurl = Strings::normaliseLink($url);
1013 // Fetch contact data from the contact table for the given user
1014 $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`,
1015 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1016 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
1017 $r = DBA::toArray($s);
1019 // Fetch contact data from the contact table for the given user, checking with the alias
1020 if (!DBA::isResult($r)) {
1021 $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`,
1022 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1023 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
1024 $r = DBA::toArray($s);
1027 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1028 if (!DBA::isResult($r)) {
1029 $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`,
1030 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1031 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1032 $r = DBA::toArray($s);
1035 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1036 if (!DBA::isResult($r)) {
1037 $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`,
1038 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1039 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1040 $r = DBA::toArray($s);
1043 // Fetch the data from the gcontact table
1044 if (!DBA::isResult($r)) {
1045 $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`,
1046 `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`
1047 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1048 $r = DBA::toArray($s);
1051 if (DBA::isResult($r)) {
1052 // If there is more than one entry we filter out the connector networks
1053 if (count($r) > 1) {
1054 foreach ($r as $id => $result) {
1055 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1061 $profile = array_shift($r);
1063 // "bd" always contains the upcoming birthday of a contact.
1064 // "birthday" might contain the birthday including the year of birth.
1065 if ($profile["birthday"] > DBA::NULL_DATE) {
1066 $bd_timestamp = strtotime($profile["birthday"]);
1067 $month = date("m", $bd_timestamp);
1068 $day = date("d", $bd_timestamp);
1070 $current_timestamp = time();
1071 $current_year = date("Y", $current_timestamp);
1072 $current_month = date("m", $current_timestamp);
1073 $current_day = date("d", $current_timestamp);
1075 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1076 $current = $current_year . "-" . $current_month . "-" . $current_day;
1078 if ($profile["bd"] < $current) {
1079 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1082 $profile["bd"] = DBA::NULL_DATE;
1085 $profile = $default;
1088 if (empty($profile["photo"]) && isset($default["photo"])) {
1089 $profile["photo"] = $default["photo"];
1092 if (empty($profile["name"]) && isset($default["name"])) {
1093 $profile["name"] = $default["name"];
1096 if (empty($profile["network"]) && isset($default["network"])) {
1097 $profile["network"] = $default["network"];
1100 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1101 $profile["thumb"] = $profile["photo"];
1104 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1105 $profile["micro"] = $profile["thumb"];
1108 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1109 && in_array($profile["network"], Protocol::FEDERATED)
1111 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1114 // Show contact details of Diaspora contacts only if connected
1115 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1116 $profile["location"] = "";
1117 $profile["about"] = "";
1118 $profile["gender"] = "";
1119 $profile["birthday"] = DBA::NULL_DATE;
1122 $cache[$url][$uid] = $profile;
1128 * Get contact data for a given address
1130 * The function looks at several places (contact table and gcontact table) for the contact
1132 * @param string $addr The profile link
1133 * @param int $uid User id
1135 * @return array Contact data
1136 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137 * @throws \ImagickException
1139 public static function getDetailsByAddr($addr, $uid = -1)
1146 $uid = local_user();
1149 // Fetch contact data from the contact table for the given user
1150 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1151 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1152 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1156 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1157 if (!DBA::isResult($r)) {
1158 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1159 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1160 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1165 // Fetch the data from the gcontact table
1166 if (!DBA::isResult($r)) {
1167 $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`,
1168 `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`
1169 FROM `gcontact` WHERE `addr` = '%s'",
1174 if (!DBA::isResult($r)) {
1175 $data = Probe::uri($addr);
1177 $profile = self::getDetailsByURL($data['url'], $uid);
1186 * Returns the data array for the photo menu of a given contact
1188 * @param array $contact contact
1189 * @param int $uid optional, default 0
1191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1192 * @throws \ImagickException
1194 public static function photoMenu(array $contact, $uid = 0)
1199 $contact_drop_link = '';
1203 $uid = local_user();
1206 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1208 $profile_link = self::magicLink($contact['url']);
1209 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1214 // Look for our own contact if the uid doesn't match and isn't public
1215 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1216 if (DBA::isResult($contact_own)) {
1217 return self::photoMenu($contact_own, $uid);
1222 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1224 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1226 $profile_link = $contact['url'];
1229 if ($profile_link === 'mailbox') {
1234 $status_link = $profile_link . '?tab=status';
1235 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1236 $profile_link = $profile_link . '?tab=profile';
1239 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1240 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1243 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1244 $poke_link = DI::baseUrl() . '/poke/?c=' . $contact['id'];
1247 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1249 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1251 if (!$contact['self']) {
1252 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1256 $unfollow_link = '';
1257 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1258 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1259 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1260 } elseif(!$contact['pending']) {
1261 $follow_link = 'follow?url=' . urlencode($contact['url']);
1267 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1269 if (empty($contact['uid'])) {
1271 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1272 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1273 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1274 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1275 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1279 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1280 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1281 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1282 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1283 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1284 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1285 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1286 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1287 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1288 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1291 if (!empty($contact['pending'])) {
1292 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1293 if (DBA::isResult($intro)) {
1294 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1299 $args = ['contact' => $contact, 'menu' => &$menu];
1301 Hook::callAll('contact_photo_menu', $args);
1303 $menucondensed = [];
1305 foreach ($menu as $menuname => $menuitem) {
1306 if ($menuitem[1] != '') {
1307 $menucondensed[$menuname] = $menuitem;
1311 return $menucondensed;
1315 * Returns ungrouped contact count or list for user
1317 * Returns either the total number of ungrouped contacts for the given user
1318 * id or a paginated list of ungrouped contacts.
1320 * @param int $uid uid
1322 * @throws \Exception
1324 public static function getUngroupedList($uid)
1334 SELECT DISTINCT(`contact-id`)
1336 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1337 WHERE `group`.`uid` = %d
1338 )", intval($uid), intval($uid));
1342 * Have a look at all contact tables for a given profile url.
1343 * This function works as a replacement for probing the contact.
1345 * @param string $url Contact URL
1346 * @param integer $cid Contact ID
1348 * @return array Contact array in the "probe" structure
1350 private static function getProbeDataFromDatabase($url, $cid = null)
1352 // The link could be provided as http although we stored it as https
1353 $ssl_url = str_replace('http://', 'https://', $url);
1355 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1356 'photo', 'keywords', 'location', 'about', 'network',
1357 'priority', 'batch', 'request', 'confirm', 'poco'];
1360 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1361 if (DBA::isResult($data)) {
1366 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1368 if (!DBA::isResult($data)) {
1369 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1370 $data = DBA::selectFirst('contact', $fields, $condition);
1373 if (DBA::isResult($data)) {
1374 // For security reasons we don't fetch key data from our users
1375 $data["pubkey"] = '';
1379 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1380 'photo', 'keywords', 'location', 'about', 'network'];
1381 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1383 if (!DBA::isResult($data)) {
1384 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1385 $data = DBA::selectFirst('contact', $fields, $condition);
1388 if (DBA::isResult($data)) {
1389 $data["pubkey"] = '';
1391 $data["priority"] = 0;
1392 $data["batch"] = '';
1393 $data["request"] = '';
1394 $data["confirm"] = '';
1399 $data = ActivityPub::probeProfile($url, false);
1400 if (!empty($data)) {
1404 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1405 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1406 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1408 if (!DBA::isResult($data)) {
1409 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1410 $data = DBA::selectFirst('contact', $fields, $condition);
1413 if (DBA::isResult($data)) {
1414 $data["pubkey"] = '';
1415 $data["keywords"] = '';
1416 $data["location"] = '';
1417 $data["about"] = '';
1426 * Fetch the contact id for a given URL and user
1428 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1429 * `addr` or `alias`.
1431 * If there's no record and we aren't looking for a public contact, we quit.
1432 * If there's one, we check that it isn't time to update the picture else we
1433 * directly return the found contact id.
1435 * Second, we probe the provided $url whether it's http://server.tld/profile or
1436 * nick@server.tld. We quit if we can't get any info back.
1438 * Third, we create the contact record if it doesn't exist
1440 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1441 * if there's any updates
1443 * @param string $url Contact URL
1444 * @param integer $uid The user id for the contact (0 = public contact)
1445 * @param boolean $no_update Don't update the contact
1446 * @param array $default Default value for creating the contact when every else fails
1447 * @param boolean $in_loop Internally used variable to prevent an endless loop
1449 * @return integer Contact ID
1450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451 * @throws \ImagickException
1453 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1455 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1463 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1464 // We first try the nurl (http://server.tld/nick), most common case
1465 $fields = ['id', 'avatar', 'updated', 'network'];
1466 $options = ['order' => ['id']];
1467 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1469 // Then the addr (nick@server.tld)
1470 if (!DBA::isResult($contact)) {
1471 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1474 // Then the alias (which could be anything)
1475 if (!DBA::isResult($contact)) {
1476 // The link could be provided as http although we stored it as https
1477 $ssl_url = str_replace('http://', 'https://', $url);
1478 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1479 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1482 if (DBA::isResult($contact)) {
1483 $contact_id = $contact["id"];
1484 $update_contact = false;
1486 // Update the contact every 7 days (Don't update mail or feed contacts)
1487 if (in_array($contact['network'], Protocol::FEDERATED)) {
1488 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1490 // We force the update if the avatar is empty
1491 if (empty($contact['avatar'])) {
1492 $update_contact = true;
1494 } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1495 // Update public mail accounts via their user's accounts
1496 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1497 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1498 if (!DBA::isResult($mailcontact)) {
1499 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1502 if (DBA::isResult($mailcontact)) {
1503 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1507 // Update the contact in the background if needed but it is called by the frontend
1508 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1509 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1512 if (!$update_contact || $no_update) {
1515 } elseif ($uid != 0) {
1516 // Non-existing user-specific contact, exiting
1520 if ($no_update && empty($default)) {
1521 // When we don't want to update, we look if we know this contact in any way
1522 $data = self::getProbeDataFromDatabase($url, $contact_id);
1523 $background_update = true;
1524 } elseif ($no_update && !empty($default['network'])) {
1525 // If there are default values, take these
1527 $background_update = false;
1530 $background_update = false;
1534 $data = Probe::uri($url, "", $uid);
1535 // Ensure that there is a gserver entry
1536 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1537 GServer::check($data['baseurl']);
1541 // Take the default values when probing failed
1542 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1543 $data = array_merge($data, $default);
1546 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1547 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1551 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1552 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1558 'created' => DateTimeFormat::utcNow(),
1559 'url' => $data['url'],
1560 'nurl' => Strings::normaliseLink($data['url']),
1561 'addr' => $data['addr'] ?? '',
1562 'alias' => $data['alias'] ?? '',
1563 'notify' => $data['notify'] ?? '',
1564 'poll' => $data['poll'] ?? '',
1565 'name' => $data['name'] ?? '',
1566 'nick' => $data['nick'] ?? '',
1567 'photo' => $data['photo'] ?? '',
1568 'keywords' => $data['keywords'] ?? '',
1569 'location' => $data['location'] ?? '',
1570 'about' => $data['about'] ?? '',
1571 'network' => $data['network'],
1572 'pubkey' => $data['pubkey'] ?? '',
1573 'rel' => self::SHARING,
1574 'priority' => $data['priority'] ?? 0,
1575 'batch' => $data['batch'] ?? '',
1576 'request' => $data['request'] ?? '',
1577 'confirm' => $data['confirm'] ?? '',
1578 'poco' => $data['poco'] ?? '',
1579 'baseurl' => $data['baseurl'] ?? '',
1580 'name-date' => DateTimeFormat::utcNow(),
1581 'uri-date' => DateTimeFormat::utcNow(),
1582 'avatar-date' => DateTimeFormat::utcNow(),
1588 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1590 // Before inserting we do check if the entry does exist now.
1591 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1592 if (!DBA::isResult($contact)) {
1593 Logger::info('Create new contact', $fields);
1595 self::insert($fields);
1597 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1598 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1599 if (!DBA::isResult($contact)) {
1600 Logger::info('Contact creation failed', $fields);
1605 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1608 $contact_id = $contact["id"];
1611 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1612 self::updateAvatar($data['photo'], $uid, $contact_id);
1615 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1616 if ($background_update) {
1617 // Update in the background when we fetched the data solely from the database
1618 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1620 // Else do a direct update
1621 self::updateFromProbe($contact_id, '', false);
1623 // Update the gcontact entry
1625 GContact::updateFromPublicContactID($contact_id);
1629 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1630 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1632 // This condition should always be true
1633 if (!DBA::isResult($contact)) {
1638 'url' => $data['url'],
1639 'nurl' => Strings::normaliseLink($data['url']),
1640 'updated' => DateTimeFormat::utcNow()
1643 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1645 foreach ($fields as $field) {
1646 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1649 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1650 $updated['uri-date'] = DateTimeFormat::utcNow();
1653 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1654 $updated['name-date'] = DateTimeFormat::utcNow();
1657 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1664 * Checks if the contact is archived
1666 * @param int $cid contact id
1668 * @return boolean Is the contact archived?
1669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1671 public static function isArchived(int $cid)
1677 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1678 if (!DBA::isResult($contact)) {
1682 if ($contact['archive']) {
1686 // Check status of ActivityPub endpoints
1687 $apcontact = APContact::getByURL($contact['url'], false);
1688 if (!empty($apcontact)) {
1689 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1693 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1698 // Check status of Diaspora endpoints
1699 if (!empty($contact['batch'])) {
1700 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1701 return DBA::exists('contact', $condition);
1708 * Checks if the contact is blocked
1710 * @param int $cid contact id
1712 * @return boolean Is the contact blocked?
1713 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1715 public static function isBlocked($cid)
1721 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1722 if (!DBA::isResult($blocked)) {
1726 if (Network::isUrlBlocked($blocked['url'])) {
1730 return (bool) $blocked['blocked'];
1734 * Checks if the contact is hidden
1736 * @param int $cid contact id
1738 * @return boolean Is the contact hidden?
1739 * @throws \Exception
1741 public static function isHidden($cid)
1747 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1748 if (!DBA::isResult($hidden)) {
1751 return (bool) $hidden['hidden'];
1755 * Returns posts from a given contact url
1757 * @param string $contact_url Contact URL
1759 * @param bool $thread_mode
1760 * @param int $update
1761 * @return string posts in HTML
1762 * @throws \Exception
1764 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1768 $cid = self::getIdForURL($contact_url);
1770 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1771 if (!DBA::isResult($contact)) {
1775 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1776 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1778 $sql = "`item`.`uid` = ?";
1781 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1784 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1785 $cid, GRAVITY_PARENT, local_user()];
1787 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1788 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1791 $pager = new Pager(DI::args()->getQueryString());
1793 $params = ['order' => ['received' => true],
1794 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1797 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1799 $items = Item::inArray($r);
1801 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1803 $r = Item::selectForUser(local_user(), [], $condition, $params);
1805 $items = Item::inArray($r);
1807 $o = conversation($a, $items, $pager, 'contact-posts', false);
1811 $o .= $pager->renderMinimal(count($items));
1818 * Returns the account type name
1820 * The function can be called with either the user or the contact array
1822 * @param array $contact contact or user array
1825 public static function getAccountType(array $contact)
1827 // There are several fields that indicate that the contact or user is a forum
1828 // "page-flags" is a field in the user table,
1829 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1830 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1831 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1832 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1833 || (isset($contact['forum']) && intval($contact['forum']))
1834 || (isset($contact['prv']) && intval($contact['prv']))
1835 || (isset($contact['community']) && intval($contact['community']))
1837 $type = self::TYPE_COMMUNITY;
1839 $type = self::TYPE_PERSON;
1842 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1843 if (isset($contact["contact-type"])) {
1844 $type = $contact["contact-type"];
1847 if (isset($contact["account-type"])) {
1848 $type = $contact["account-type"];
1852 case self::TYPE_ORGANISATION:
1853 $account_type = DI::l10n()->t("Organisation");
1856 case self::TYPE_NEWS:
1857 $account_type = DI::l10n()->t('News');
1860 case self::TYPE_COMMUNITY:
1861 $account_type = DI::l10n()->t("Forum");
1869 return $account_type;
1877 * @throws \Exception
1879 public static function block($cid, $reason = null)
1881 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1887 * Unblocks a contact
1891 * @throws \Exception
1893 public static function unblock($cid)
1895 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1901 * Updates the avatar links in a contact only if needed
1903 * @param string $avatar Link to avatar picture
1904 * @param int $uid User id of contact owner
1905 * @param int $cid Contact id
1906 * @param bool $force force picture update
1908 * @return array Returns array of the different avatar sizes
1909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1910 * @throws \ImagickException
1912 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1914 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1915 if (!DBA::isResult($contact)) {
1918 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1921 foreach ($data as $image_uri) {
1922 $image_rid = Photo::ridFromURI($image_uri);
1923 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1924 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1929 if (($contact["avatar"] != $avatar) || $force) {
1930 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1933 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1934 DBA::update('contact', $fields, ['id' => $cid]);
1936 // Update the public contact (contact id = 0)
1938 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1939 if (DBA::isResult($pcontact)) {
1940 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1952 * Helper function for "updateFromProbe". Updates personal and public contact
1954 * @param integer $id contact id
1955 * @param integer $uid user id
1956 * @param string $url The profile URL of the contact
1957 * @param array $fields The fields that are updated
1959 * @throws \Exception
1961 private static function updateContact($id, $uid, $url, array $fields)
1963 if (!DBA::update('contact', $fields, ['id' => $id])) {
1964 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1968 // Search for duplicated contacts and get rid of them
1969 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1973 // Update the corresponding gcontact entry
1974 GContact::updateFromPublicContactID($id);
1976 // Archive or unarchive the contact. We only need to do this for the public contact.
1977 // The archive/unarchive function will update the personal contacts by themselves.
1978 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1979 if (!DBA::isResult($contact)) {
1980 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1984 if (!empty($fields['success_update'])) {
1985 self::unmarkForArchival($contact);
1986 } elseif (!empty($fields['failure_update'])) {
1987 self::markForArchival($contact);
1990 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1992 // These contacts are sharing with us, we don't poll them.
1993 // This means that we don't set the update fields in "OnePoll.php".
1994 $condition['rel'] = self::SHARING;
1995 DBA::update('contact', $fields, $condition);
1997 unset($fields['last-update']);
1998 unset($fields['success_update']);
1999 unset($fields['failure_update']);
2001 if (empty($fields)) {
2005 // We are polling these contacts, so we mustn't set the update fields here.
2006 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2007 DBA::update('contact', $fields, $condition);
2011 * Remove duplicated contacts
2013 * @param string $nurl Normalised contact url
2014 * @param integer $uid User id
2016 * @throws \Exception
2018 public static function removeDuplicates(string $nurl, int $uid)
2020 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2021 $count = DBA::count('contact', $condition);
2026 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2027 if (!DBA::isResult($first_contact)) {
2028 // Shouldn't happen - so we handle it
2032 $first = $first_contact['id'];
2033 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2034 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2035 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2036 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2040 // Find all duplicates
2041 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2042 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2043 while ($duplicate = DBA::fetch($duplicates)) {
2044 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2048 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2050 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2055 * @param integer $id contact id
2056 * @param string $network Optional network we are probing for
2057 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2059 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2060 * @throws \ImagickException
2062 public static function updateFromProbe($id, $network = '', $force = false)
2065 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2066 This will reliably kill your communication with old Friendica contacts.
2069 // These fields aren't updated by this routine:
2070 // 'xmpp', 'sensitive'
2072 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2073 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2074 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2075 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2076 if (!DBA::isResult($contact)) {
2080 $uid = $contact['uid'];
2081 unset($contact['uid']);
2083 $pubkey = $contact['pubkey'];
2084 unset($contact['pubkey']);
2086 $contact['photo'] = $contact['avatar'];
2087 unset($contact['avatar']);
2089 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2091 $updated = DateTimeFormat::utcNow();
2093 // We must not try to update relay contacts via probe. They are no real contacts.
2094 // We check after the probing to be able to correct falsely detected contact types.
2095 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2096 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2097 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2098 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2102 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2103 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2104 if ($force && ($uid == 0)) {
2105 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2110 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2111 $ret['unsearchable'] = $ret['hide'];
2114 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2115 $ret['forum'] = false;
2116 $ret['prv'] = false;
2117 $ret['contact-type'] = $ret['account-type'];
2118 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2119 $apcontact = APContact::getByURL($ret['url'], false);
2120 if (isset($apcontact['manually-approve'])) {
2121 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2122 $ret['prv'] = (bool)!$ret['forum'];
2127 $new_pubkey = $ret['pubkey'];
2131 // make sure to not overwrite existing values with blank entries except some technical fields
2132 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2133 foreach ($ret as $key => $val) {
2134 if (!array_key_exists($key, $contact)) {
2136 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2137 $ret[$key] = $contact[$key];
2138 } elseif ($ret[$key] != $contact[$key]) {
2143 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2144 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2149 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2152 // Update the public contact
2154 self::updateFromProbeByURL($ret['url']);
2160 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2161 $ret['updated'] = $updated;
2163 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2164 if (empty($pubkey) && !empty($new_pubkey)) {
2165 $ret['pubkey'] = $new_pubkey;
2168 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2169 $ret['uri-date'] = DateTimeFormat::utcNow();
2172 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2173 $ret['name-date'] = $updated;
2176 if ($force && ($uid == 0)) {
2177 $ret['last-update'] = $updated;
2178 $ret['success_update'] = $updated;
2181 unset($ret['photo']);
2183 self::updateContact($id, $uid, $ret['url'], $ret);
2188 public static function updateFromProbeByURL($url, $force = false)
2190 $id = self::getIdForURL($url);
2196 self::updateFromProbe($id, '', $force);
2202 * Detects if a given contact array belongs to a legacy DFRN connection
2204 * @param array $contact
2207 public static function isLegacyDFRNContact($contact)
2209 // Newer Friendica contacts are connected via AP, then these fields aren't set
2210 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2214 * Detects the communication protocol for a given contact url.
2215 * This is used to detect Friendica contacts that we can communicate via AP.
2217 * @param string $url contact url
2218 * @param string $network Network of that contact
2219 * @return string with protocol
2221 public static function getProtocol($url, $network)
2223 if ($network != Protocol::DFRN) {
2227 $apcontact = APContact::getByURL($url);
2228 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2229 return Protocol::ACTIVITYPUB;
2236 * 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'] = DI::l10n()->t('Disallowed profile URL.');
2270 if (Network::isUrlBlocked($url)) {
2271 $result['message'] = DI::l10n()->t('Blocked domain');
2276 $result['message'] = DI::l10n()->t('Connect URL missing.');
2280 $arr = ['url' => $url, 'contact' => []];
2282 Hook::callAll('follow', $arr);
2285 $result['message'] = DI::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'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2327 $result['message'] .= DI::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'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2339 if (empty($ret['poll'])) {
2340 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2342 if (empty($ret['name'])) {
2343 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2345 if (empty($ret['url'])) {
2346 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2348 if (strpos($url, '@') !== false) {
2349 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2350 $result['message'] .= DI::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'] .= DI::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'] .= DI::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'] .= DI::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']) : DI::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;