3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\App\BaseURL;
8 use Friendica\BaseObject;
9 use Friendica\Content\Pager;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Session;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\Activity;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Protocol\DFRN;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Protocol\PortableContact;
27 use Friendica\Protocol\Salmon;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\Network;
30 use Friendica\Util\Strings;
33 * @brief functions for interacting with a contact
35 class Contact extends BaseObject
38 * @deprecated since version 2019.03
39 * @see User::PAGE_FLAGS_NORMAL
41 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
43 * @deprecated since version 2019.03
44 * @see User::PAGE_FLAGS_SOAPBOX
46 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
48 * @deprecated since version 2019.03
49 * @see User::PAGE_FLAGS_COMMUNITY
51 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
53 * @deprecated since version 2019.03
54 * @see User::PAGE_FLAGS_FREELOVE
56 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
58 * @deprecated since version 2019.03
59 * @see User::PAGE_FLAGS_BLOG
61 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
63 * @deprecated since version 2019.03
64 * @see User::PAGE_FLAGS_PRVGROUP
66 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
74 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
76 * TYPE_PERSON - the account belongs to a person
77 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
79 * TYPE_ORGANISATION - the account belongs to an organisation
80 * Associated page type: PAGE_SOAPBOX
82 * TYPE_NEWS - the account is a news reflector
83 * Associated page type: PAGE_SOAPBOX
85 * TYPE_COMMUNITY - the account is community forum
86 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
88 * TYPE_RELAY - the account is a relay
89 * This will only be assigned to contacts, not to user accounts
92 const TYPE_UNKNOWN = -1;
93 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
94 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
95 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
96 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
97 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
116 * @param array $fields Array of selected fields, empty for all
117 * @param array $condition Array of fields for condition
118 * @param array $params Array of several parameters
122 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
124 return DBA::selectToArray('contact', $fields, $condition, $params);
128 * @param array $fields Array of selected fields, empty for all
129 * @param array $condition Array of fields for condition
130 * @param array $params Array of several parameters
134 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
136 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
142 * Insert a row into the contact table
143 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
145 * @param array $fields field array
146 * @param bool $on_duplicate_update Do an update on a duplicate entry
148 * @return boolean was the insert successful?
151 public static function insert(array $fields, bool $on_duplicate_update = false)
153 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
154 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
155 if (!DBA::isResult($contact)) {
160 // Search for duplicated contacts and get rid of them
161 self::removeDuplicates($contact['nurl'], $contact['uid']);
167 * @param integer $id Contact ID
168 * @param array $fields Array of selected fields, empty for all
169 * @return array|boolean Contact record if it exists, false otherwise
172 public static function getById($id, $fields = [])
174 return DBA::selectFirst('contact', $fields, ['id' => $id]);
178 * @brief Tests if the given contact is a follower
180 * @param int $cid Either public contact id or user's contact id
181 * @param int $uid User ID
183 * @return boolean is the contact id a follower?
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function isFollower($cid, $uid)
189 if (self::isBlockedByUser($cid, $uid)) {
193 $cdata = self::getPublicAndUserContacID($cid, $uid);
194 if (empty($cdata['user'])) {
198 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
199 return DBA::exists('contact', $condition);
203 * @brief Tests if the given contact url is a follower
205 * @param string $url Contact URL
206 * @param int $uid User ID
208 * @return boolean is the contact id a follower?
209 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
210 * @throws \ImagickException
212 public static function isFollowerByURL($url, $uid)
214 $cid = self::getIdForURL($url, $uid, true);
220 return self::isFollower($cid, $uid);
224 * @brief Tests if the given user follow the given contact
226 * @param int $cid Either public contact id or user's contact id
227 * @param int $uid User ID
229 * @return boolean is the contact url being followed?
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function isSharing($cid, $uid)
235 if (self::isBlockedByUser($cid, $uid)) {
239 $cdata = self::getPublicAndUserContacID($cid, $uid);
240 if (empty($cdata['user'])) {
244 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
245 return DBA::exists('contact', $condition);
249 * @brief Tests if the given user follow the given contact url
251 * @param string $url Contact URL
252 * @param int $uid User ID
254 * @return boolean is the contact url being followed?
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 public static function isSharingByURL($url, $uid)
260 $cid = self::getIdForURL($url, $uid, true);
266 return self::isSharing($cid, $uid);
270 * @brief Get the basepath for a given contact link
272 * @param string $url The contact link
274 * @return string basepath
275 * @return boolean $dont_update Don't update the contact
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 * @throws \ImagickException
279 public static function getBasepath($url, $dont_update = false)
281 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
282 if (!empty($contact['baseurl'])) {
283 return $contact['baseurl'];
284 } elseif ($dont_update) {
288 self::updateFromProbeByURL($url, true);
290 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
291 if (!empty($contact['baseurl'])) {
292 return $contact['baseurl'];
299 * Check if the given contact url is on the same server
301 * @param string $url The contact link
303 * @return boolean Is it the same server?
305 public static function isLocal($url)
307 return Strings::compareLink(self::getBasepath($url, true), System::baseUrl());
311 * Returns the public contact id of the given user id
313 * @param integer $uid User ID
315 * @return integer|boolean Public contact id for given user id
318 public static function getPublicIdByUserId($uid)
320 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
321 if (!DBA::isResult($self)) {
324 return self::getIdForURL($self['url'], 0, true);
328 * @brief Returns the contact id for the user and the public contact id for a given contact id
330 * @param int $cid Either public contact id or user's contact id
331 * @param int $uid User ID
333 * @return array with public and user's contact id
334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
335 * @throws \ImagickException
337 public static function getPublicAndUserContacID($cid, $uid)
339 if (empty($uid) || empty($cid)) {
343 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
344 if (!DBA::isResult($contact)) {
348 // We quit when the user id don't match the user id of the provided contact
349 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
353 if ($contact['uid'] != 0) {
354 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
358 $ucid = $contact['id'];
360 $pcid = $contact['id'];
361 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
364 return ['public' => $pcid, 'user' => $ucid];
368 * Returns contact details for a given contact id in combination with a user id
370 * @param int $cid A contact ID
371 * @param int $uid The User ID
372 * @param array $fields The selected fields for the contact
374 * @return array The contact details
378 public static function getContactForUser($cid, $uid, array $fields = [])
380 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
382 if (!DBA::isResult($contact)) {
390 * @brief Block contact id for user id
392 * @param int $cid Either public contact id or user's contact id
393 * @param int $uid User ID
394 * @param boolean $blocked Is the contact blocked or unblocked?
397 public static function setBlockedForUser($cid, $uid, $blocked)
399 $cdata = self::getPublicAndUserContacID($cid, $uid);
404 if ($cdata['user'] != 0) {
405 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
408 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
411 // Blocked contact can't be in any group
412 self::removeFromGroups($cid);
417 * @brief Returns "block" state for contact id and user id
419 * @param int $cid Either public contact id or user's contact id
420 * @param int $uid User ID
422 * @return boolean is the contact id blocked for the given user?
425 public static function isBlockedByUser($cid, $uid)
427 $cdata = self::getPublicAndUserContacID($cid, $uid);
432 $public_blocked = false;
434 if (!empty($cdata['public'])) {
435 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
436 if (DBA::isResult($public_contact)) {
437 $public_blocked = $public_contact['blocked'];
441 $user_blocked = $public_blocked;
443 if (!empty($cdata['user'])) {
444 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
445 if (DBA::isResult($user_contact)) {
446 $user_blocked = $user_contact['blocked'];
450 if ($user_blocked != $public_blocked) {
451 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
454 return $user_blocked;
458 * @brief Ignore contact id for user id
460 * @param int $cid Either public contact id or user's contact id
461 * @param int $uid User ID
462 * @param boolean $ignored Is the contact ignored or unignored?
465 public static function setIgnoredForUser($cid, $uid, $ignored)
467 $cdata = self::getPublicAndUserContacID($cid, $uid);
472 if ($cdata['user'] != 0) {
473 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
476 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
480 * @brief Returns "ignore" state for contact id and user id
482 * @param int $cid Either public contact id or user's contact id
483 * @param int $uid User ID
485 * @return boolean is the contact id ignored for the given user?
488 public static function isIgnoredByUser($cid, $uid)
490 $cdata = self::getPublicAndUserContacID($cid, $uid);
495 $public_ignored = false;
497 if (!empty($cdata['public'])) {
498 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
499 if (DBA::isResult($public_contact)) {
500 $public_ignored = $public_contact['ignored'];
504 $user_ignored = $public_ignored;
506 if (!empty($cdata['user'])) {
507 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
508 if (DBA::isResult($user_contact)) {
509 $user_ignored = $user_contact['readonly'];
513 if ($user_ignored != $public_ignored) {
514 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
517 return $user_ignored;
521 * @brief Set "collapsed" for contact id and user id
523 * @param int $cid Either public contact id or user's contact id
524 * @param int $uid User ID
525 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
528 public static function setCollapsedForUser($cid, $uid, $collapsed)
530 $cdata = self::getPublicAndUserContacID($cid, $uid);
535 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
539 * @brief Returns "collapsed" state for contact id and user id
541 * @param int $cid Either public contact id or user's contact id
542 * @param int $uid User ID
544 * @return boolean is the contact id blocked for the given user?
545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 * @throws \ImagickException
548 public static function isCollapsedByUser($cid, $uid)
550 $cdata = self::getPublicAndUserContacID($cid, $uid);
557 if (!empty($cdata['public'])) {
558 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
559 if (DBA::isResult($public_contact)) {
560 $collapsed = $public_contact['collapsed'];
568 * @brief Returns a list of contacts belonging in a group
574 public static function getByGroupId($gid)
579 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
581 INNER JOIN `group_member`
582 ON `contact`.`id` = `group_member`.`contact-id`
584 AND `contact`.`uid` = ?
585 AND NOT `contact`.`self`
586 AND NOT `contact`.`deleted`
587 AND NOT `contact`.`blocked`
588 AND NOT `contact`.`pending`
589 ORDER BY `contact`.`name` ASC',
594 if (DBA::isResult($stmt)) {
595 $return = DBA::toArray($stmt);
603 * @brief Returns the count of OStatus contacts in a group
609 public static function getOStatusCountByGroupId($gid)
613 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
615 INNER JOIN `group_member`
616 ON `contact`.`id` = `group_member`.`contact-id`
618 AND `contact`.`uid` = ?
619 AND `contact`.`network` = ?
620 AND `contact`.`notify` != ""',
625 $return = $contacts['count'];
632 * Creates the self-contact for the provided user id
635 * @return bool Operation success
636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
638 public static function createSelfFromUserId($uid)
640 // Only create the entry if it doesn't exist yet
641 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
645 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
646 if (!DBA::isResult($user)) {
650 $return = DBA::insert('contact', [
651 'uid' => $user['uid'],
652 'created' => DateTimeFormat::utcNow(),
654 'name' => $user['username'],
655 'nick' => $user['nickname'],
656 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
657 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
658 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
661 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
662 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
663 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
664 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
665 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
666 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
667 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
668 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
669 'name-date' => DateTimeFormat::utcNow(),
670 'uri-date' => DateTimeFormat::utcNow(),
671 'avatar-date' => DateTimeFormat::utcNow(),
679 * Updates the self-contact for the provided user id
682 * @param boolean $update_avatar Force the avatar update
683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685 public static function updateSelfFromUserID($uid, $update_avatar = false)
687 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
688 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
689 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
690 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
691 if (!DBA::isResult($self)) {
695 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
696 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
697 if (!DBA::isResult($user)) {
701 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
702 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
703 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
704 if (!DBA::isResult($profile)) {
708 $file_suffix = 'jpg';
710 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
711 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
712 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
713 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
714 'xmpp' => $profile['xmpp']];
716 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
717 if (DBA::isResult($avatar)) {
718 if ($update_avatar) {
719 $fields['avatar-date'] = DateTimeFormat::utcNow();
722 // Creating the path to the avatar, beginning with the file suffix
723 $types = Image::supportedTypes();
724 if (isset($types[$avatar['type']])) {
725 $file_suffix = $types[$avatar['type']];
728 // We are adding a timestamp value so that other systems won't use cached content
729 $timestamp = strtotime($fields['avatar-date']);
731 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
732 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
734 $fields['photo'] = $prefix . '4' . $suffix;
735 $fields['thumb'] = $prefix . '5' . $suffix;
736 $fields['micro'] = $prefix . '6' . $suffix;
738 // We hadn't found a photo entry, so we use the default avatar
739 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
740 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
741 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
744 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
745 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
746 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
747 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
749 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
750 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
751 $fields['nurl'] = Strings::normaliseLink($fields['url']);
752 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
753 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
754 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
755 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
756 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
757 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
761 foreach ($fields as $field => $content) {
762 if ($self[$field] != $content) {
768 if ($fields['name'] != $self['name']) {
769 $fields['name-date'] = DateTimeFormat::utcNow();
771 $fields['updated'] = DateTimeFormat::utcNow();
772 DBA::update('contact', $fields, ['id' => $self['id']]);
774 // Update the public contact as well
775 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
777 // Update the profile
778 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
779 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
780 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
785 * @brief Marks a contact for removal
787 * @param int $id contact id
789 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791 public static function remove($id)
793 // We want just to make sure that we don't delete our "self" contact
794 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
795 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
799 // Archive the contact
800 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
802 // Delete it in the background
803 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
807 * @brief Sends an unfriend message. Does not remove the contact
809 * @param array $user User unfriending
810 * @param array $contact Contact unfriended
811 * @param boolean $dissolve Remove the contact on the remote side
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
818 if (empty($contact['network'])) {
822 $protocol = $contact['network'];
823 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
824 $protocol = Protocol::ACTIVITYPUB;
827 if (($protocol == Protocol::DFRN) && $dissolve) {
828 DFRN::deliver($user, $contact, 'placeholder', true);
829 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
830 // create an unfollow slap
832 $item['verb'] = Activity\Namespaces::OSTATUS . "/unfollow";
833 $item['follow'] = $contact["url"];
838 $item['attach'] = '';
839 $slap = OStatus::salmon($item, $user);
841 if (!empty($contact['notify'])) {
842 Salmon::slapper($user, $contact['notify'], $slap);
844 } elseif ($protocol == Protocol::DIASPORA) {
845 Diaspora::sendUnshare($user, $contact);
846 } elseif ($protocol == Protocol::ACTIVITYPUB) {
847 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
850 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
856 * @brief Marks a contact for archival after a communication issue delay
858 * Contact has refused to recognise us as a friend. We will start a countdown.
859 * If they still don't recognise us in 32 days, the relationship is over,
860 * and we won't waste any more time trying to communicate with them.
861 * This provides for the possibility that their database is temporarily messed
862 * up or some other transient event and that there's a possibility we could recover from it.
864 * @param array $contact contact to mark for archival
866 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
868 public static function markForArchival(array $contact)
870 if (!isset($contact['url']) && !empty($contact['id'])) {
871 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
872 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
873 if (!DBA::isResult($contact)) {
876 } elseif (!isset($contact['url'])) {
877 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
880 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
882 // Contact already archived or "self" contact? => nothing to do
883 if ($contact['archive'] || $contact['self']) {
887 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
888 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
889 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
892 * We really should send a notification to the owner after 2-3 weeks
893 * so they won't be surprised when the contact vanishes and can take
894 * remedial action if this was a serious mistake or glitch
897 /// @todo Check for contact vitality via probing
898 $archival_days = Config::get('system', 'archival_days', 32);
900 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
901 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
902 /* Relationship is really truly dead. archive them rather than
903 * delete, though if the owner tries to unarchive them we'll start
904 * the whole process over again.
906 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
907 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
908 GContact::updateFromPublicContactURL($contact['url']);
914 * @brief Cancels the archival countdown
916 * @see Contact::markForArchival()
918 * @param array $contact contact to be unmarked for archival
922 public static function unmarkForArchival(array $contact)
924 // Always unarchive the relay contact entry
925 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
926 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
927 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
928 DBA::update('contact', $fields, $condition);
931 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
932 $exists = DBA::exists('contact', $condition);
934 // We don't need to update, we never marked this contact for archival
939 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
941 if (!isset($contact['url']) && !empty($contact['id'])) {
942 $fields = ['id', 'url', 'batch'];
943 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
944 if (!DBA::isResult($contact)) {
949 // It's a miracle. Our dead contact has inexplicably come back to life.
950 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
951 DBA::update('contact', $fields, ['id' => $contact['id']]);
952 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
953 GContact::updateFromPublicContactURL($contact['url']);
957 * @brief Get contact data for a given profile link
959 * The function looks at several places (contact table and gcontact table) for the contact
960 * It caches its result for the same script execution to prevent duplicate calls
962 * @param string $url The profile link
963 * @param int $uid User id
964 * @param array $default If not data was found take this data as default value
966 * @return array Contact data
967 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969 public static function getDetailsByURL($url, $uid = -1, array $default = [])
981 if (isset($cache[$url][$uid])) {
982 return $cache[$url][$uid];
985 $ssl_url = str_replace('http://', 'https://', $url);
987 // Fetch contact data from the contact table for the given user
988 $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`,
989 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
990 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
991 $r = DBA::toArray($s);
993 // Fetch contact data from the contact table for the given user, checking with the alias
994 if (!DBA::isResult($r)) {
995 $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`,
996 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
997 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
998 $r = DBA::toArray($s);
1001 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1002 if (!DBA::isResult($r)) {
1003 $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`,
1004 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1005 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
1006 $r = DBA::toArray($s);
1009 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1010 if (!DBA::isResult($r)) {
1011 $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`,
1012 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1013 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
1014 $r = DBA::toArray($s);
1017 // Fetch the data from the gcontact table
1018 if (!DBA::isResult($r)) {
1019 $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`,
1020 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1021 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1022 $r = DBA::toArray($s);
1025 if (DBA::isResult($r)) {
1026 // If there is more than one entry we filter out the connector networks
1027 if (count($r) > 1) {
1028 foreach ($r as $id => $result) {
1029 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1035 $profile = array_shift($r);
1037 // "bd" always contains the upcoming birthday of a contact.
1038 // "birthday" might contain the birthday including the year of birth.
1039 if ($profile["birthday"] > DBA::NULL_DATE) {
1040 $bd_timestamp = strtotime($profile["birthday"]);
1041 $month = date("m", $bd_timestamp);
1042 $day = date("d", $bd_timestamp);
1044 $current_timestamp = time();
1045 $current_year = date("Y", $current_timestamp);
1046 $current_month = date("m", $current_timestamp);
1047 $current_day = date("d", $current_timestamp);
1049 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1050 $current = $current_year . "-" . $current_month . "-" . $current_day;
1052 if ($profile["bd"] < $current) {
1053 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1056 $profile["bd"] = DBA::NULL_DATE;
1059 $profile = $default;
1062 if (empty($profile["photo"]) && isset($default["photo"])) {
1063 $profile["photo"] = $default["photo"];
1066 if (empty($profile["name"]) && isset($default["name"])) {
1067 $profile["name"] = $default["name"];
1070 if (empty($profile["network"]) && isset($default["network"])) {
1071 $profile["network"] = $default["network"];
1074 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1075 $profile["thumb"] = $profile["photo"];
1078 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1079 $profile["micro"] = $profile["thumb"];
1082 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1083 && in_array($profile["network"], Protocol::FEDERATED)
1085 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1088 // Show contact details of Diaspora contacts only if connected
1089 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1090 $profile["location"] = "";
1091 $profile["about"] = "";
1092 $profile["gender"] = "";
1093 $profile["birthday"] = DBA::NULL_DATE;
1096 $cache[$url][$uid] = $profile;
1102 * @brief Get contact data for a given address
1104 * The function looks at several places (contact table and gcontact table) for the contact
1106 * @param string $addr The profile link
1107 * @param int $uid User id
1109 * @return array Contact data
1110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111 * @throws \ImagickException
1113 public static function getDetailsByAddr($addr, $uid = -1)
1120 $uid = local_user();
1123 // Fetch contact data from the contact table for the given user
1124 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1125 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1126 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1130 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1131 if (!DBA::isResult($r)) {
1132 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1133 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1134 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1139 // Fetch the data from the gcontact table
1140 if (!DBA::isResult($r)) {
1141 $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`,
1142 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1143 FROM `gcontact` WHERE `addr` = '%s'",
1148 if (!DBA::isResult($r)) {
1149 $data = Probe::uri($addr);
1151 $profile = self::getDetailsByURL($data['url'], $uid);
1160 * @brief Returns the data array for the photo menu of a given contact
1162 * @param array $contact contact
1163 * @param int $uid optional, default 0
1165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1166 * @throws \ImagickException
1168 public static function photoMenu(array $contact, $uid = 0)
1173 $contact_drop_link = '';
1177 $uid = local_user();
1180 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1182 $profile_link = self::magicLink($contact['url']);
1183 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1188 // Look for our own contact if the uid doesn't match and isn't public
1189 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1190 if (DBA::isResult($contact_own)) {
1191 return self::photoMenu($contact_own, $uid);
1196 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1198 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
1200 $profile_link = $contact['url'];
1203 if ($profile_link === 'mailbox') {
1208 $status_link = $profile_link . '?tab=status';
1209 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1210 $profile_link = $profile_link . '?tab=profile';
1213 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1214 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1217 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1218 $poke_link = System::baseUrl() . '/poke/?c=' . $contact['id'];
1221 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1223 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1225 if (!$contact['self']) {
1226 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1231 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1233 if (empty($contact['uid'])) {
1234 $connlnk = 'follow/?url=' . $contact['url'];
1236 'profile' => [L10n::t('View Profile'), $profile_link, true],
1237 'network' => [L10n::t('Network Posts'), $posts_link, false],
1238 'edit' => [L10n::t('View Contact'), $contact_url, false],
1239 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1243 'status' => [L10n::t('View Status'), $status_link, true],
1244 'profile' => [L10n::t('View Profile'), $profile_link, true],
1245 'photos' => [L10n::t('View Photos'), $photos_link, true],
1246 'network' => [L10n::t('Network Posts'), $posts_link, false],
1247 'edit' => [L10n::t('View Contact'), $contact_url, false],
1248 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1249 'pm' => [L10n::t('Send PM'), $pm_url, false],
1250 'poke' => [L10n::t('Poke'), $poke_link, false],
1253 if (!empty($contact['pending'])) {
1254 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1255 if (DBA::isResult($intro)) {
1256 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1261 $args = ['contact' => $contact, 'menu' => &$menu];
1263 Hook::callAll('contact_photo_menu', $args);
1265 $menucondensed = [];
1267 foreach ($menu as $menuname => $menuitem) {
1268 if ($menuitem[1] != '') {
1269 $menucondensed[$menuname] = $menuitem;
1273 return $menucondensed;
1277 * @brief Returns ungrouped contact count or list for user
1279 * Returns either the total number of ungrouped contacts for the given user
1280 * id or a paginated list of ungrouped contacts.
1282 * @param int $uid uid
1284 * @throws \Exception
1286 public static function getUngroupedList($uid)
1296 SELECT DISTINCT(`contact-id`)
1298 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1299 WHERE `group`.`uid` = %d
1300 )", intval($uid), intval($uid));
1304 * Have a look at all contact tables for a given profile url.
1305 * This function works as a replacement for probing the contact.
1307 * @param string $url Contact URL
1308 * @param integer $cid Contact ID
1310 * @return array Contact array in the "probe" structure
1312 private static function getProbeDataFromDatabase($url, $cid = null)
1314 // The link could be provided as http although we stored it as https
1315 $ssl_url = str_replace('http://', 'https://', $url);
1317 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1318 'photo', 'keywords', 'location', 'about', 'network',
1319 'priority', 'batch', 'request', 'confirm', 'poco'];
1322 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1323 if (DBA::isResult($data)) {
1328 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1330 if (!DBA::isResult($data)) {
1331 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1332 $data = DBA::selectFirst('contact', $fields, $condition);
1335 if (DBA::isResult($data)) {
1336 // For security reasons we don't fetch key data from our users
1337 $data["pubkey"] = '';
1341 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1342 'photo', 'keywords', 'location', 'about', 'network'];
1343 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1345 if (!DBA::isResult($data)) {
1346 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1347 $data = DBA::selectFirst('contact', $fields, $condition);
1350 if (DBA::isResult($data)) {
1351 $data["pubkey"] = '';
1353 $data["priority"] = 0;
1354 $data["batch"] = '';
1355 $data["request"] = '';
1356 $data["confirm"] = '';
1361 $data = ActivityPub::probeProfile($url, false);
1362 if (!empty($data)) {
1366 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1367 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1368 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1370 if (!DBA::isResult($data)) {
1371 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1372 $data = DBA::selectFirst('contact', $fields, $condition);
1375 if (DBA::isResult($data)) {
1376 $data["pubkey"] = '';
1377 $data["keywords"] = '';
1378 $data["location"] = '';
1379 $data["about"] = '';
1388 * @brief Fetch the contact id for a given URL and user
1390 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1391 * `addr` or `alias`.
1393 * If there's no record and we aren't looking for a public contact, we quit.
1394 * If there's one, we check that it isn't time to update the picture else we
1395 * directly return the found contact id.
1397 * Second, we probe the provided $url whether it's http://server.tld/profile or
1398 * nick@server.tld. We quit if we can't get any info back.
1400 * Third, we create the contact record if it doesn't exist
1402 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1403 * if there's any updates
1405 * @param string $url Contact URL
1406 * @param integer $uid The user id for the contact (0 = public contact)
1407 * @param boolean $no_update Don't update the contact
1408 * @param array $default Default value for creating the contact when every else fails
1409 * @param boolean $in_loop Internally used variable to prevent an endless loop
1411 * @return integer Contact ID
1412 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1413 * @throws \ImagickException
1415 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1417 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1425 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1426 // We first try the nurl (http://server.tld/nick), most common case
1427 $fields = ['id', 'avatar', 'updated', 'network'];
1428 $options = ['order' => ['id']];
1429 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1431 // Then the addr (nick@server.tld)
1432 if (!DBA::isResult($contact)) {
1433 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1436 // Then the alias (which could be anything)
1437 if (!DBA::isResult($contact)) {
1438 // The link could be provided as http although we stored it as https
1439 $ssl_url = str_replace('http://', 'https://', $url);
1440 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1441 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1444 if (DBA::isResult($contact)) {
1445 $contact_id = $contact["id"];
1447 // Update the contact every 7 days
1448 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1450 // We force the update if the avatar is empty
1451 if (empty($contact['avatar'])) {
1452 $update_contact = true;
1455 // Update the contact in the background if needed but it is called by the frontend
1456 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1457 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1460 if (!$update_contact || $no_update) {
1463 } elseif ($uid != 0) {
1464 // Non-existing user-specific contact, exiting
1468 if ($no_update && empty($default)) {
1469 // When we don't want to update, we look if we know this contact in any way
1470 $data = self::getProbeDataFromDatabase($url, $contact_id);
1471 $background_update = true;
1472 } elseif ($no_update && !empty($default['network'])) {
1473 // If there are default values, take these
1475 $background_update = false;
1478 $background_update = false;
1482 $data = Probe::uri($url, "", $uid);
1483 // Ensure that there is a gserver entry
1484 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1485 GServer::check($data['baseurl']);
1489 // Take the default values when probing failed
1490 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1491 $data = array_merge($data, $default);
1498 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1499 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1505 'created' => DateTimeFormat::utcNow(),
1506 'url' => $data['url'],
1507 'nurl' => Strings::normaliseLink($data['url']),
1508 'addr' => $data['addr'] ?? '',
1509 'alias' => $data['alias'] ?? '',
1510 'notify' => $data['notify'] ?? '',
1511 'poll' => $data['poll'] ?? '',
1512 'name' => $data['name'] ?? '',
1513 'nick' => $data['nick'] ?? '',
1514 'photo' => $data['photo'] ?? '',
1515 'keywords' => $data['keywords'] ?? '',
1516 'location' => $data['location'] ?? '',
1517 'about' => $data['about'] ?? '',
1518 'network' => $data['network'],
1519 'pubkey' => $data['pubkey'] ?? '',
1520 'rel' => self::SHARING,
1521 'priority' => $data['priority'] ?? 0,
1522 'batch' => $data['batch'] ?? '',
1523 'request' => $data['request'] ?? '',
1524 'confirm' => $data['confirm'] ?? '',
1525 'poco' => $data['poco'] ?? '',
1526 'baseurl' => $data['baseurl'] ?? '',
1527 'name-date' => DateTimeFormat::utcNow(),
1528 'uri-date' => DateTimeFormat::utcNow(),
1529 'avatar-date' => DateTimeFormat::utcNow(),
1535 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1537 // Before inserting we do check if the entry does exist now.
1538 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1539 if (!DBA::isResult($contact)) {
1540 Logger::info('Create new contact', $fields);
1542 self::insert($fields);
1544 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1545 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1546 if (!DBA::isResult($contact)) {
1547 Logger::info('Contact creation failed', $fields);
1552 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1555 $contact_id = $contact["id"];
1558 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1559 self::updateAvatar($data['photo'], $uid, $contact_id);
1562 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1563 if ($background_update) {
1564 // Update in the background when we fetched the data solely from the database
1565 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1567 // Else do a direct update
1568 self::updateFromProbe($contact_id, '', false);
1570 // Update the gcontact entry
1572 GContact::updateFromPublicContactID($contact_id);
1576 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1577 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1579 // This condition should always be true
1580 if (!DBA::isResult($contact)) {
1585 'url' => $data['url'],
1586 'nurl' => Strings::normaliseLink($data['url']),
1587 'updated' => DateTimeFormat::utcNow()
1590 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1592 foreach ($fields as $field) {
1593 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1596 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1597 $updated['uri-date'] = DateTimeFormat::utcNow();
1600 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1601 $updated['name-date'] = DateTimeFormat::utcNow();
1604 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1611 * @brief Checks if the contact is archived
1613 * @param int $cid contact id
1615 * @return boolean Is the contact archived?
1616 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1618 public static function isArchived(int $cid)
1624 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1625 if (!DBA::isResult($contact)) {
1629 if ($contact['archive']) {
1633 // Check status of ActivityPub endpoints
1634 $apcontact = APContact::getByURL($contact['url'], false);
1635 if (!empty($apcontact)) {
1636 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1640 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1645 // Check status of Diaspora endpoints
1646 if (!empty($contact['batch'])) {
1647 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1648 return DBA::exists('contact', $condition);
1655 * @brief Checks if the contact is blocked
1657 * @param int $cid contact id
1659 * @return boolean Is the contact blocked?
1660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662 public static function isBlocked($cid)
1668 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1669 if (!DBA::isResult($blocked)) {
1673 if (Network::isUrlBlocked($blocked['url'])) {
1677 return (bool) $blocked['blocked'];
1681 * @brief Checks if the contact is hidden
1683 * @param int $cid contact id
1685 * @return boolean Is the contact hidden?
1686 * @throws \Exception
1688 public static function isHidden($cid)
1694 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1695 if (!DBA::isResult($hidden)) {
1698 return (bool) $hidden['hidden'];
1702 * @brief Returns posts from a given contact url
1704 * @param string $contact_url Contact URL
1706 * @param bool $thread_mode
1707 * @param int $update
1708 * @return string posts in HTML
1709 * @throws \Exception
1711 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1713 $a = self::getApp();
1715 $cid = self::getIdForURL($contact_url);
1717 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1718 if (!DBA::isResult($contact)) {
1722 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1723 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1725 $sql = "`item`.`uid` = ?";
1728 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1731 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1732 $cid, GRAVITY_PARENT, local_user()];
1734 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1735 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1738 $pager = new Pager($a->query_string);
1740 $params = ['order' => ['received' => true],
1741 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1744 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1746 $items = Item::inArray($r);
1748 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1750 $r = Item::selectForUser(local_user(), [], $condition, $params);
1752 $items = Item::inArray($r);
1754 $o = conversation($a, $items, $pager, 'contact-posts', false);
1758 $o .= $pager->renderMinimal(count($items));
1765 * @brief Returns the account type name
1767 * The function can be called with either the user or the contact array
1769 * @param array $contact contact or user array
1772 public static function getAccountType(array $contact)
1774 // There are several fields that indicate that the contact or user is a forum
1775 // "page-flags" is a field in the user table,
1776 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1777 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1778 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1779 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1780 || (isset($contact['forum']) && intval($contact['forum']))
1781 || (isset($contact['prv']) && intval($contact['prv']))
1782 || (isset($contact['community']) && intval($contact['community']))
1784 $type = self::TYPE_COMMUNITY;
1786 $type = self::TYPE_PERSON;
1789 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1790 if (isset($contact["contact-type"])) {
1791 $type = $contact["contact-type"];
1794 if (isset($contact["account-type"])) {
1795 $type = $contact["account-type"];
1799 case self::TYPE_ORGANISATION:
1800 $account_type = L10n::t("Organisation");
1803 case self::TYPE_NEWS:
1804 $account_type = L10n::t('News');
1807 case self::TYPE_COMMUNITY:
1808 $account_type = L10n::t("Forum");
1816 return $account_type;
1820 * @brief Blocks a contact
1824 * @throws \Exception
1826 public static function block($cid, $reason = null)
1828 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1834 * @brief Unblocks a contact
1838 * @throws \Exception
1840 public static function unblock($cid)
1842 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1848 * @brief Updates the avatar links in a contact only if needed
1850 * @param string $avatar Link to avatar picture
1851 * @param int $uid User id of contact owner
1852 * @param int $cid Contact id
1853 * @param bool $force force picture update
1855 * @return array Returns array of the different avatar sizes
1856 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1857 * @throws \ImagickException
1859 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1861 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1862 if (!DBA::isResult($contact)) {
1865 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1868 if (($contact["avatar"] != $avatar) || $force) {
1869 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1872 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1873 DBA::update('contact', $fields, ['id' => $cid]);
1875 // Update the public contact (contact id = 0)
1877 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1878 if (DBA::isResult($pcontact)) {
1879 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1891 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1893 * @param integer $id contact id
1894 * @param integer $uid user id
1895 * @param string $url The profile URL of the contact
1896 * @param array $fields The fields that are updated
1898 * @throws \Exception
1900 private static function updateContact($id, $uid, $url, array $fields)
1902 if (!DBA::update('contact', $fields, ['id' => $id])) {
1903 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1907 // Search for duplicated contacts and get rid of them
1908 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1912 // Update the corresponding gcontact entry
1913 GContact::updateFromPublicContactID($id);
1915 // Archive or unarchive the contact. We only need to do this for the public contact.
1916 // The archive/unarchive function will update the personal contacts by themselves.
1917 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1918 if (!DBA::isResult($contact)) {
1919 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1923 if (!empty($fields['success_update'])) {
1924 self::unmarkForArchival($contact);
1925 } elseif (!empty($fields['failure_update'])) {
1926 self::markForArchival($contact);
1929 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1931 // These contacts are sharing with us, we don't poll them.
1932 // This means that we don't set the update fields in "OnePoll.php".
1933 $condition['rel'] = self::SHARING;
1934 DBA::update('contact', $fields, $condition);
1936 unset($fields['last-update']);
1937 unset($fields['success_update']);
1938 unset($fields['failure_update']);
1940 if (empty($fields)) {
1944 // We are polling these contacts, so we mustn't set the update fields here.
1945 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1946 DBA::update('contact', $fields, $condition);
1950 * @brief Remove duplicated contacts
1952 * @param string $nurl Normalised contact url
1953 * @param integer $uid User id
1955 * @throws \Exception
1957 public static function removeDuplicates(string $nurl, int $uid)
1959 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1960 $count = DBA::count('contact', $condition);
1965 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1966 if (!DBA::isResult($first_contact)) {
1967 // Shouldn't happen - so we handle it
1971 $first = $first_contact['id'];
1972 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1973 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1974 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1975 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1979 // Find all duplicates
1980 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1981 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1982 while ($duplicate = DBA::fetch($duplicates)) {
1983 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1987 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1989 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1994 * @param integer $id contact id
1995 * @param string $network Optional network we are probing for
1996 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1998 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1999 * @throws \ImagickException
2001 public static function updateFromProbe($id, $network = '', $force = false)
2004 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2005 This will reliably kill your communication with old Friendica contacts.
2008 // These fields aren't updated by this routine:
2009 // 'xmpp', 'sensitive'
2011 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2012 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2013 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2014 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2015 if (!DBA::isResult($contact)) {
2019 $uid = $contact['uid'];
2020 unset($contact['uid']);
2022 $pubkey = $contact['pubkey'];
2023 unset($contact['pubkey']);
2025 $contact['photo'] = $contact['avatar'];
2026 unset($contact['avatar']);
2028 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2030 $updated = DateTimeFormat::utcNow();
2032 // We must not try to update relay contacts via probe. They are no real contacts.
2033 // We check after the probing to be able to correct falsely detected contact types.
2034 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2035 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2036 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2037 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2041 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2042 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2043 if ($force && ($uid == 0)) {
2044 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2049 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2050 $ret['unsearchable'] = $ret['hide'];
2053 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2054 $ret['forum'] = false;
2055 $ret['prv'] = false;
2056 $ret['contact-type'] = $ret['account-type'];
2057 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2058 $apcontact = APContact::getByURL($ret['url'], false);
2059 if (isset($apcontact['manually-approve'])) {
2060 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2061 $ret['prv'] = (bool)!$ret['forum'];
2066 $new_pubkey = $ret['pubkey'];
2070 // make sure to not overwrite existing values with blank entries except some technical fields
2071 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2072 foreach ($ret as $key => $val) {
2073 if (!array_key_exists($key, $contact)) {
2075 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2076 $ret[$key] = $contact[$key];
2077 } elseif ($ret[$key] != $contact[$key]) {
2082 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2083 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2088 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2093 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2094 $ret['updated'] = $updated;
2096 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2097 if (empty($pubkey) && !empty($new_pubkey)) {
2098 $ret['pubkey'] = $new_pubkey;
2101 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2102 $ret['uri-date'] = DateTimeFormat::utcNow();
2105 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2106 $ret['name-date'] = $updated;
2109 if ($force && ($uid == 0)) {
2110 $ret['last-update'] = $updated;
2111 $ret['success_update'] = $updated;
2114 unset($ret['photo']);
2116 self::updateContact($id, $uid, $ret['url'], $ret);
2121 public static function updateFromProbeByURL($url, $force = false)
2123 $id = self::getIdForURL($url);
2129 self::updateFromProbe($id, '', $force);
2135 * Detects if a given contact array belongs to a legacy DFRN connection
2137 * @param array $contact
2140 public static function isLegacyDFRNContact($contact)
2142 // Newer Friendica contacts are connected via AP, then these fields aren't set
2143 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2147 * Detects the communication protocol for a given contact url.
2148 * This is used to detect Friendica contacts that we can communicate via AP.
2150 * @param string $url contact url
2151 * @param string $network Network of that contact
2152 * @return string with protocol
2154 public static function getProtocol($url, $network)
2156 if ($network != Protocol::DFRN) {
2160 $apcontact = APContact::getByURL($url);
2161 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2162 return Protocol::ACTIVITYPUB;
2169 * Takes a $uid and a url/handle and adds a new contact
2170 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2171 * dfrn_request page.
2173 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2176 * $return['success'] boolean true if successful
2177 * $return['message'] error text if success is false.
2179 * @brief Takes a $uid and a url/handle and adds a new contact
2181 * @param string $url
2182 * @param bool $interactive
2183 * @param string $network
2185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2186 * @throws \ImagickException
2188 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2190 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2194 // remove ajax junk, e.g. Twitter
2195 $url = str_replace('/#!/', '/', $url);
2197 if (!Network::isUrlAllowed($url)) {
2198 $result['message'] = L10n::t('Disallowed profile URL.');
2202 if (Network::isUrlBlocked($url)) {
2203 $result['message'] = L10n::t('Blocked domain');
2208 $result['message'] = L10n::t('Connect URL missing.');
2212 $arr = ['url' => $url, 'contact' => []];
2214 Hook::callAll('follow', $arr);
2217 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2221 if (!empty($arr['contact']['name'])) {
2222 $ret = $arr['contact'];
2224 $ret = Probe::uri($url, $network, $uid, false);
2227 if (($network != '') && ($ret['network'] != $network)) {
2228 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2232 // check if we already have a contact
2233 // the poll url is more reliable than the profile url, as we may have
2234 // indirect links or webfinger links
2236 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2237 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2238 if (!DBA::isResult($contact)) {
2239 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2240 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2243 $protocol = self::getProtocol($url, $ret['network']);
2245 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2247 if (strlen($a->getURLPath())) {
2248 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2250 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2253 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2257 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2258 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2259 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2263 // This extra param just confuses things, remove it
2264 if ($protocol === Protocol::DIASPORA) {
2265 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2268 // do we have enough information?
2269 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2270 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2271 if (empty($ret['poll'])) {
2272 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2274 if (empty($ret['name'])) {
2275 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2277 if (empty($ret['url'])) {
2278 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2280 if (strpos($url, '@') !== false) {
2281 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2282 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2287 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2288 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2289 $ret['notify'] = '';
2292 if (!$ret['notify']) {
2293 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2296 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2298 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2300 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2302 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2304 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2308 if (DBA::isResult($contact)) {
2310 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2312 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2313 DBA::update('contact', $fields, ['id' => $contact['id']]);
2315 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2317 // create contact record
2320 'created' => DateTimeFormat::utcNow(),
2321 'url' => $ret['url'],
2322 'nurl' => Strings::normaliseLink($ret['url']),
2323 'addr' => $ret['addr'],
2324 'alias' => $ret['alias'],
2325 'batch' => $ret['batch'],
2326 'notify' => $ret['notify'],
2327 'poll' => $ret['poll'],
2328 'poco' => $ret['poco'],
2329 'name' => $ret['name'],
2330 'nick' => $ret['nick'],
2331 'network' => $ret['network'],
2332 'baseurl' => $ret['baseurl'],
2333 'protocol' => $protocol,
2334 'pubkey' => $ret['pubkey'],
2335 'rel' => $new_relation,
2336 'priority'=> $ret['priority'],
2337 'writable'=> $writeable,
2338 'hidden' => $hidden,
2341 'pending' => $pending,
2346 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2347 if (!DBA::isResult($contact)) {
2348 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2352 $contact_id = $contact['id'];
2353 $result['cid'] = $contact_id;
2355 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2357 // Update the avatar
2358 self::updateAvatar($ret['photo'], $uid, $contact_id);
2360 // pull feed and consume it, which should subscribe to the hub.
2362 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2364 $owner = User::getOwnerDataById($uid);
2366 if (DBA::isResult($owner)) {
2367 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2368 // create a follow slap
2370 $item['verb'] = Activity::FOLLOW;
2371 $item['follow'] = $contact["url"];
2373 $item['title'] = '';
2376 $item['attach'] = '';
2378 $slap = OStatus::salmon($item, $owner);
2380 if (!empty($contact['notify'])) {
2381 Salmon::slapper($owner, $contact['notify'], $slap);
2383 } elseif ($protocol == Protocol::DIASPORA) {
2384 $ret = Diaspora::sendShare($a->user, $contact);
2385 Logger::log('share returns: ' . $ret);
2386 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2387 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2388 if (empty($activity_id)) {
2389 // This really should never happen
2393 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2394 Logger::log('Follow returns: ' . $ret);
2398 $result['success'] = true;
2403 * @brief Updated contact's SSL policy
2405 * @param array $contact Contact array
2406 * @param string $new_policy New policy, valid: self,full
2408 * @return array Contact array with updated values
2409 * @throws \Exception
2411 public static function updateSslPolicy(array $contact, $new_policy)
2413 $ssl_changed = false;
2414 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2415 $ssl_changed = true;
2416 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2417 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2418 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2419 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2420 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2421 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2424 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2425 $ssl_changed = true;
2426 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2427 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2428 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2429 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2430 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2431 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2435 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2436 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2437 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2438 DBA::update('contact', $fields, ['id' => $contact['id']]);
2445 * @param array $importer Owner (local user) data
2446 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2447 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2448 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2449 * @param string $note Introduction additional message
2450 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2451 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2452 * @throws \ImagickException
2454 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2456 // Should always be set
2457 if (empty($datarray['author-id'])) {
2461 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2462 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2463 if (!DBA::isResult($pub_contact)) {
2464 // Should never happen
2468 // Contact is blocked at node-level
2469 if (self::isBlocked($datarray['author-id'])) {
2473 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2474 $name = $pub_contact['name'];
2475 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2476 $nick = $pub_contact['nick'];
2477 $network = $pub_contact['network'];
2479 // Ensure that we don't create a new contact when there already is one
2480 $cid = self::getIdForURL($url, $importer['uid']);
2482 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2485 if (!empty($contact)) {
2486 if (!empty($contact['pending'])) {
2487 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2491 // Contact is blocked at user-level
2492 if (!empty($contact['id']) && !empty($importer['id']) &&
2493 self::isBlockedByUser($contact['id'], $importer['id'])) {
2497 // Make sure that the existing contact isn't archived
2498 self::unmarkForArchival($contact);
2500 if (($contact['rel'] == self::SHARING)
2501 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2502 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2503 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2506 // Ensure to always have the correct network type, independent from the connection request method
2507 self::updateFromProbe($contact['id'], '', true);
2511 // send email notification to owner?
2512 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2513 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2517 // create contact record
2518 DBA::insert('contact', [
2519 'uid' => $importer['uid'],
2520 'created' => DateTimeFormat::utcNow(),
2522 'nurl' => Strings::normaliseLink($url),
2526 'network' => $network,
2527 'rel' => self::FOLLOWER,
2534 $contact_id = DBA::lastInsertId();
2536 // Ensure to always have the correct network type, independent from the connection request method
2537 self::updateFromProbe($contact_id, '', true);
2539 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2541 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2543 /// @TODO Encapsulate this into a function/method
2544 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2545 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2546 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2547 // create notification
2548 $hash = Strings::getRandomHex();
2550 if (is_array($contact_record)) {
2551 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2552 'blocked' => false, 'knowyou' => false, 'note' => $note,
2553 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2556 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2558 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2559 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2562 'type' => NOTIFY_INTRO,
2563 'notify_flags' => $user['notify-flags'],
2564 'language' => $user['language'],
2565 'to_name' => $user['username'],
2566 'to_email' => $user['email'],
2567 'uid' => $user['uid'],
2568 'link' => System::baseUrl() . '/notifications/intro',
2569 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2570 'source_link' => $contact_record['url'],
2571 'source_photo' => $contact_record['photo'],
2572 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2576 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2577 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2578 DBA::update('contact', ['pending' => false], $condition);
2587 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2589 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2590 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2592 Contact::remove($contact['id']);
2596 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2598 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2599 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2601 Contact::remove($contact['id']);
2606 * @brief Create a birthday event.
2608 * Update the year and the birthday.
2610 public static function updateBirthdays()
2614 AND `bd` > "0001-01-01"
2615 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2616 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2617 AND NOT `contact`.`pending`
2618 AND NOT `contact`.`hidden`
2619 AND NOT `contact`.`blocked`
2620 AND NOT `contact`.`archive`
2621 AND NOT `contact`.`deleted`',
2626 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2628 while ($contact = DBA::fetch($contacts)) {
2629 Logger::log('update_contact_birthday: ' . $contact['bd']);
2631 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2633 if (Event::createBirthday($contact, $nextbd)) {
2637 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2638 ['id' => $contact['id']]
2645 * Remove the unavailable contact ids from the provided list
2647 * @param array $contact_ids Contact id list
2648 * @throws \Exception
2650 public static function pruneUnavailable(array &$contact_ids)
2652 if (empty($contact_ids)) {
2656 $str = DBA::escape(implode(',', $contact_ids));
2658 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2661 while($contact = DBA::fetch($stmt)) {
2662 $return[] = $contact['id'];
2667 $contact_ids = $return;
2671 * @brief Returns a magic link to authenticate remote visitors
2673 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2675 * @param string $contact_url The address of the target contact profile
2676 * @param string $url An url that we will be redirected to after the authentication
2678 * @return string with "redir" link
2679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2680 * @throws \ImagickException
2682 public static function magicLink($contact_url, $url = '')
2684 if (!Session::isAuthenticated()) {
2685 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2688 $data = self::getProbeDataFromDatabase($contact_url);
2690 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2693 // Prevents endless loop in case only a non-public contact exists for the contact URL
2694 unset($data['uid']);
2696 return self::magicLinkByContact($data, $url ?: $contact_url);
2700 * @brief Returns a magic link to authenticate remote visitors
2702 * @param integer $cid The contact id of the target contact profile
2703 * @param string $url An url that we will be redirected to after the authentication
2705 * @return string with "redir" link
2706 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2707 * @throws \ImagickException
2709 public static function magicLinkbyId($cid, $url = '')
2711 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2713 return self::magicLinkByContact($contact, $url);
2717 * @brief Returns a magic link to authenticate remote visitors
2719 * @param array $contact The contact array with "uid", "network" and "url"
2720 * @param string $url An url that we will be redirected to after the authentication
2722 * @return string with "redir" link
2723 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2724 * @throws \ImagickException
2726 public static function magicLinkByContact($contact, $url = '')
2728 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2730 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2731 return $destination;
2734 // Only redirections to the same host do make sense
2735 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2739 if (!empty($contact['uid'])) {
2740 return self::magicLink($contact['url'], $url);
2743 if (empty($contact['id'])) {
2744 return $destination;
2747 $redirect = 'redir/' . $contact['id'];
2749 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2750 $redirect .= '?url=' . $url;
2757 * Remove a contact from all groups
2759 * @param integer $contact_id
2761 * @return boolean Success
2763 public static function removeFromGroups($contact_id)
2765 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2769 * Is the contact a forum?
2771 * @param integer $contactid ID of the contact
2773 * @return boolean "true" if it is a forum
2775 public static function isForum($contactid)
2777 $fields = ['forum', 'prv'];
2778 $condition = ['id' => $contactid];
2779 $contact = DBA::selectFirst('contact', $fields, $condition);
2780 if (!DBA::isResult($contact)) {
2785 return ($contact['forum'] || $contact['prv']);
2789 * Can the remote contact receive private messages?
2791 * @param array $contact
2794 public static function canReceivePrivateMessages(array $contact)
2796 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2797 $self = $contact['self'] ?? false;
2799 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;