3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\App\BaseURL;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Session;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
19 use Friendica\Network\Probe;
20 use Friendica\Protocol\Activity;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Images;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
32 * @brief functions for interacting with a contact
37 * @deprecated since version 2019.03
38 * @see User::PAGE_FLAGS_NORMAL
40 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
42 * @deprecated since version 2019.03
43 * @see User::PAGE_FLAGS_SOAPBOX
45 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
47 * @deprecated since version 2019.03
48 * @see User::PAGE_FLAGS_COMMUNITY
50 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
52 * @deprecated since version 2019.03
53 * @see User::PAGE_FLAGS_FREELOVE
55 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_BLOG
60 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_PRVGROUP
65 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
73 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
75 * TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
78 * TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_SOAPBOX
84 * TYPE_COMMUNITY - the account is community forum
85 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
87 * TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const TYPE_UNKNOWN = -1;
92 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
93 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
94 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
95 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
96 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @param array $fields Array of selected fields, empty for all
116 * @param array $condition Array of fields for condition
117 * @param array $params Array of several parameters
121 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
123 return DBA::selectToArray('contact', $fields, $condition, $params);
127 * @param array $fields Array of selected fields, empty for all
128 * @param array $condition Array of fields for condition
129 * @param array $params Array of several parameters
133 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
135 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
141 * Insert a row into the contact table
142 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
144 * @param array $fields field array
145 * @param bool $on_duplicate_update Do an update on a duplicate entry
147 * @return boolean was the insert successful?
150 public static function insert(array $fields, bool $on_duplicate_update = false)
152 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
153 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
154 if (!DBA::isResult($contact)) {
159 // Search for duplicated contacts and get rid of them
160 self::removeDuplicates($contact['nurl'], $contact['uid']);
166 * @param integer $id Contact ID
167 * @param array $fields Array of selected fields, empty for all
168 * @return array|boolean Contact record if it exists, false otherwise
171 public static function getById($id, $fields = [])
173 return DBA::selectFirst('contact', $fields, ['id' => $id]);
177 * @brief Tests if the given contact is a follower
179 * @param int $cid Either public contact id or user's contact id
180 * @param int $uid User ID
182 * @return boolean is the contact id a follower?
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function isFollower($cid, $uid)
188 if (self::isBlockedByUser($cid, $uid)) {
192 $cdata = self::getPublicAndUserContacID($cid, $uid);
193 if (empty($cdata['user'])) {
197 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
198 return DBA::exists('contact', $condition);
202 * @brief Tests if the given contact url is a follower
204 * @param string $url Contact URL
205 * @param int $uid User ID
207 * @return boolean is the contact id a follower?
208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 public static function isFollowerByURL($url, $uid)
213 $cid = self::getIdForURL($url, $uid, true);
219 return self::isFollower($cid, $uid);
223 * @brief Tests if the given user follow the given contact
225 * @param int $cid Either public contact id or user's contact id
226 * @param int $uid User ID
228 * @return boolean is the contact url being followed?
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function isSharing($cid, $uid)
234 if (self::isBlockedByUser($cid, $uid)) {
238 $cdata = self::getPublicAndUserContacID($cid, $uid);
239 if (empty($cdata['user'])) {
243 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
244 return DBA::exists('contact', $condition);
248 * @brief Tests if the given user follow the given contact url
250 * @param string $url Contact URL
251 * @param int $uid User ID
253 * @return boolean is the contact url being followed?
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 public static function isSharingByURL($url, $uid)
259 $cid = self::getIdForURL($url, $uid, true);
265 return self::isSharing($cid, $uid);
269 * @brief Get the basepath for a given contact link
271 * @param string $url The contact link
272 * @param boolean $dont_update Don't update the contact
274 * @return string basepath
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function getBasepath($url, $dont_update = false)
280 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
281 if (!DBA::isResult($contact)) {
285 if (!empty($contact['baseurl'])) {
286 return $contact['baseurl'];
287 } elseif ($dont_update) {
291 // Update the existing contact
292 self::updateFromProbe($contact['id'], '', true);
294 // And fetch the result
295 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
296 if (empty($contact['baseurl'])) {
297 Logger::info('No baseurl for contact', ['url' => $url]);
301 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
302 return $contact['baseurl'];
306 * Check if the given contact url is on the same server
308 * @param string $url The contact link
310 * @return boolean Is it the same server?
312 public static function isLocal($url)
314 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
318 * Returns the public contact id of the given user id
320 * @param integer $uid User ID
322 * @return integer|boolean Public contact id for given user id
325 public static function getPublicIdByUserId($uid)
327 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
328 if (!DBA::isResult($self)) {
331 return self::getIdForURL($self['url'], 0, true);
335 * @brief Returns the contact id for the user and the public contact id for a given contact id
337 * @param int $cid Either public contact id or user's contact id
338 * @param int $uid User ID
340 * @return array with public and user's contact id
341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
342 * @throws \ImagickException
344 public static function getPublicAndUserContacID($cid, $uid)
346 if (empty($uid) || empty($cid)) {
350 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
351 if (!DBA::isResult($contact)) {
355 // We quit when the user id don't match the user id of the provided contact
356 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
360 if ($contact['uid'] != 0) {
361 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
365 $ucid = $contact['id'];
367 $pcid = $contact['id'];
368 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
371 return ['public' => $pcid, 'user' => $ucid];
375 * Returns contact details for a given contact id in combination with a user id
377 * @param int $cid A contact ID
378 * @param int $uid The User ID
379 * @param array $fields The selected fields for the contact
381 * @return array The contact details
385 public static function getContactForUser($cid, $uid, array $fields = [])
387 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
389 if (!DBA::isResult($contact)) {
397 * @brief Block contact id for user id
399 * @param int $cid Either public contact id or user's contact id
400 * @param int $uid User ID
401 * @param boolean $blocked Is the contact blocked or unblocked?
404 public static function setBlockedForUser($cid, $uid, $blocked)
406 $cdata = self::getPublicAndUserContacID($cid, $uid);
411 if ($cdata['user'] != 0) {
412 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
415 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
419 * @brief Returns "block" state for contact id and user id
421 * @param int $cid Either public contact id or user's contact id
422 * @param int $uid User ID
424 * @return boolean is the contact id blocked for the given user?
427 public static function isBlockedByUser($cid, $uid)
429 $cdata = self::getPublicAndUserContacID($cid, $uid);
434 $public_blocked = false;
436 if (!empty($cdata['public'])) {
437 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
438 if (DBA::isResult($public_contact)) {
439 $public_blocked = $public_contact['blocked'];
443 $user_blocked = $public_blocked;
445 if (!empty($cdata['user'])) {
446 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
447 if (DBA::isResult($user_contact)) {
448 $user_blocked = $user_contact['blocked'];
452 if ($user_blocked != $public_blocked) {
453 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
456 return $user_blocked;
460 * @brief Ignore contact id for user id
462 * @param int $cid Either public contact id or user's contact id
463 * @param int $uid User ID
464 * @param boolean $ignored Is the contact ignored or unignored?
467 public static function setIgnoredForUser($cid, $uid, $ignored)
469 $cdata = self::getPublicAndUserContacID($cid, $uid);
474 if ($cdata['user'] != 0) {
475 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
478 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
482 * @brief Returns "ignore" state for contact id and user id
484 * @param int $cid Either public contact id or user's contact id
485 * @param int $uid User ID
487 * @return boolean is the contact id ignored for the given user?
490 public static function isIgnoredByUser($cid, $uid)
492 $cdata = self::getPublicAndUserContacID($cid, $uid);
497 $public_ignored = false;
499 if (!empty($cdata['public'])) {
500 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
501 if (DBA::isResult($public_contact)) {
502 $public_ignored = $public_contact['ignored'];
506 $user_ignored = $public_ignored;
508 if (!empty($cdata['user'])) {
509 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
510 if (DBA::isResult($user_contact)) {
511 $user_ignored = $user_contact['readonly'];
515 if ($user_ignored != $public_ignored) {
516 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
519 return $user_ignored;
523 * @brief Set "collapsed" for contact id and user id
525 * @param int $cid Either public contact id or user's contact id
526 * @param int $uid User ID
527 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
530 public static function setCollapsedForUser($cid, $uid, $collapsed)
532 $cdata = self::getPublicAndUserContacID($cid, $uid);
537 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
541 * @brief Returns "collapsed" state for contact id and user id
543 * @param int $cid Either public contact id or user's contact id
544 * @param int $uid User ID
546 * @return boolean is the contact id blocked for the given user?
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
548 * @throws \ImagickException
550 public static function isCollapsedByUser($cid, $uid)
552 $cdata = self::getPublicAndUserContacID($cid, $uid);
559 if (!empty($cdata['public'])) {
560 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
561 if (DBA::isResult($public_contact)) {
562 $collapsed = $public_contact['collapsed'];
570 * @brief Returns a list of contacts belonging in a group
576 public static function getByGroupId($gid)
581 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
583 INNER JOIN `group_member`
584 ON `contact`.`id` = `group_member`.`contact-id`
586 AND `contact`.`uid` = ?
587 AND NOT `contact`.`self`
588 AND NOT `contact`.`deleted`
589 AND NOT `contact`.`blocked`
590 AND NOT `contact`.`pending`
591 ORDER BY `contact`.`name` ASC',
596 if (DBA::isResult($stmt)) {
597 $return = DBA::toArray($stmt);
605 * @brief Returns the count of OStatus contacts in a group
611 public static function getOStatusCountByGroupId($gid)
615 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
617 INNER JOIN `group_member`
618 ON `contact`.`id` = `group_member`.`contact-id`
620 AND `contact`.`uid` = ?
621 AND `contact`.`network` = ?
622 AND `contact`.`notify` != ""',
627 $return = $contacts['count'];
634 * Creates the self-contact for the provided user id
637 * @return bool Operation success
638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
640 public static function createSelfFromUserId($uid)
642 // Only create the entry if it doesn't exist yet
643 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
647 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
648 if (!DBA::isResult($user)) {
652 $return = DBA::insert('contact', [
653 'uid' => $user['uid'],
654 'created' => DateTimeFormat::utcNow(),
656 'name' => $user['username'],
657 'nick' => $user['nickname'],
658 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
659 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
660 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
663 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
664 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
665 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
666 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
667 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
668 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
669 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
670 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
671 'name-date' => DateTimeFormat::utcNow(),
672 'uri-date' => DateTimeFormat::utcNow(),
673 'avatar-date' => DateTimeFormat::utcNow(),
681 * Updates the self-contact for the provided user id
684 * @param boolean $update_avatar Force the avatar update
685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
687 public static function updateSelfFromUserID($uid, $update_avatar = false)
689 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
690 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
691 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
692 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
693 if (!DBA::isResult($self)) {
697 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
698 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
699 if (!DBA::isResult($user)) {
703 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
704 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
705 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
706 if (!DBA::isResult($profile)) {
710 $file_suffix = 'jpg';
712 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
713 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
714 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
715 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
716 'xmpp' => $profile['xmpp']];
718 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
719 if (DBA::isResult($avatar)) {
720 if ($update_avatar) {
721 $fields['avatar-date'] = DateTimeFormat::utcNow();
724 // Creating the path to the avatar, beginning with the file suffix
725 $types = Images::supportedTypes();
726 if (isset($types[$avatar['type']])) {
727 $file_suffix = $types[$avatar['type']];
730 // We are adding a timestamp value so that other systems won't use cached content
731 $timestamp = strtotime($fields['avatar-date']);
733 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
734 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
736 $fields['photo'] = $prefix . '4' . $suffix;
737 $fields['thumb'] = $prefix . '5' . $suffix;
738 $fields['micro'] = $prefix . '6' . $suffix;
740 // We hadn't found a photo entry, so we use the default avatar
741 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
742 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
743 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
746 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
747 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
748 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
749 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
751 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
752 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
753 $fields['nurl'] = Strings::normaliseLink($fields['url']);
754 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
755 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
756 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
757 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
758 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
759 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
763 foreach ($fields as $field => $content) {
764 if ($self[$field] != $content) {
770 if ($fields['name'] != $self['name']) {
771 $fields['name-date'] = DateTimeFormat::utcNow();
773 $fields['updated'] = DateTimeFormat::utcNow();
774 DBA::update('contact', $fields, ['id' => $self['id']]);
776 // Update the public contact as well
777 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
779 // Update the profile
780 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
781 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
782 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
787 * @brief Marks a contact for removal
789 * @param int $id contact id
791 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
793 public static function remove($id)
795 // We want just to make sure that we don't delete our "self" contact
796 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
797 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
801 // Archive the contact
802 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
804 // Delete it in the background
805 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
809 * @brief Sends an unfriend message. Does not remove the contact
811 * @param array $user User unfriending
812 * @param array $contact Contact unfriended
813 * @param boolean $dissolve Remove the contact on the remote side
815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
816 * @throws \ImagickException
818 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
820 if (empty($contact['network'])) {
824 $protocol = $contact['network'];
825 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
826 $protocol = Protocol::ACTIVITYPUB;
829 if (($protocol == Protocol::DFRN) && $dissolve) {
830 DFRN::deliver($user, $contact, 'placeholder', true);
831 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
832 // create an unfollow slap
834 $item['verb'] = Activity::O_UNFOLLOW;
835 $item['follow'] = $contact["url"];
840 $item['attach'] = '';
841 $slap = OStatus::salmon($item, $user);
843 if (!empty($contact['notify'])) {
844 Salmon::slapper($user, $contact['notify'], $slap);
846 } elseif ($protocol == Protocol::DIASPORA) {
847 Diaspora::sendUnshare($user, $contact);
848 } elseif ($protocol == Protocol::ACTIVITYPUB) {
849 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
852 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
858 * @brief Marks a contact for archival after a communication issue delay
860 * Contact has refused to recognise us as a friend. We will start a countdown.
861 * If they still don't recognise us in 32 days, the relationship is over,
862 * and we won't waste any more time trying to communicate with them.
863 * This provides for the possibility that their database is temporarily messed
864 * up or some other transient event and that there's a possibility we could recover from it.
866 * @param array $contact contact to mark for archival
868 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 public static function markForArchival(array $contact)
872 if (!isset($contact['url']) && !empty($contact['id'])) {
873 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
874 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
875 if (!DBA::isResult($contact)) {
878 } elseif (!isset($contact['url'])) {
879 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
882 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
884 // Contact already archived or "self" contact? => nothing to do
885 if ($contact['archive'] || $contact['self']) {
889 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
890 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
891 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
894 * We really should send a notification to the owner after 2-3 weeks
895 * so they won't be surprised when the contact vanishes and can take
896 * remedial action if this was a serious mistake or glitch
899 /// @todo Check for contact vitality via probing
900 $archival_days = Config::get('system', 'archival_days', 32);
902 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
903 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
904 /* Relationship is really truly dead. archive them rather than
905 * delete, though if the owner tries to unarchive them we'll start
906 * the whole process over again.
908 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
909 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
910 GContact::updateFromPublicContactURL($contact['url']);
916 * @brief Cancels the archival countdown
918 * @see Contact::markForArchival()
920 * @param array $contact contact to be unmarked for archival
924 public static function unmarkForArchival(array $contact)
926 // Always unarchive the relay contact entry
927 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
928 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
929 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
930 DBA::update('contact', $fields, $condition);
933 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
934 $exists = DBA::exists('contact', $condition);
936 // We don't need to update, we never marked this contact for archival
941 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
943 if (!isset($contact['url']) && !empty($contact['id'])) {
944 $fields = ['id', 'url', 'batch'];
945 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
946 if (!DBA::isResult($contact)) {
951 // It's a miracle. Our dead contact has inexplicably come back to life.
952 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
953 DBA::update('contact', $fields, ['id' => $contact['id']]);
954 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
955 GContact::updateFromPublicContactURL($contact['url']);
959 * @brief Get contact data for a given profile link
961 * The function looks at several places (contact table and gcontact table) for the contact
962 * It caches its result for the same script execution to prevent duplicate calls
964 * @param string $url The profile link
965 * @param int $uid User id
966 * @param array $default If not data was found take this data as default value
968 * @return array Contact data
969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 public static function getDetailsByURL($url, $uid = -1, array $default = [])
983 if (isset($cache[$url][$uid])) {
984 return $cache[$url][$uid];
987 $ssl_url = str_replace('http://', 'https://', $url);
989 $nurl = Strings::normaliseLink($url);
991 // Fetch contact data from the contact table for the given user
992 $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`,
993 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
994 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
995 $r = DBA::toArray($s);
997 // Fetch contact data from the contact table for the given user, checking with the alias
998 if (!DBA::isResult($r)) {
999 $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`,
1000 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1001 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
1002 $r = DBA::toArray($s);
1005 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1006 if (!DBA::isResult($r)) {
1007 $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`,
1008 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1009 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1010 $r = DBA::toArray($s);
1013 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1014 if (!DBA::isResult($r)) {
1015 $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`,
1016 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1017 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1018 $r = DBA::toArray($s);
1021 // Fetch the data from the gcontact table
1022 if (!DBA::isResult($r)) {
1023 $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`,
1024 `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`
1025 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1026 $r = DBA::toArray($s);
1029 if (DBA::isResult($r)) {
1030 // If there is more than one entry we filter out the connector networks
1031 if (count($r) > 1) {
1032 foreach ($r as $id => $result) {
1033 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1039 $profile = array_shift($r);
1041 // "bd" always contains the upcoming birthday of a contact.
1042 // "birthday" might contain the birthday including the year of birth.
1043 if ($profile["birthday"] > DBA::NULL_DATE) {
1044 $bd_timestamp = strtotime($profile["birthday"]);
1045 $month = date("m", $bd_timestamp);
1046 $day = date("d", $bd_timestamp);
1048 $current_timestamp = time();
1049 $current_year = date("Y", $current_timestamp);
1050 $current_month = date("m", $current_timestamp);
1051 $current_day = date("d", $current_timestamp);
1053 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1054 $current = $current_year . "-" . $current_month . "-" . $current_day;
1056 if ($profile["bd"] < $current) {
1057 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1060 $profile["bd"] = DBA::NULL_DATE;
1063 $profile = $default;
1066 if (empty($profile["photo"]) && isset($default["photo"])) {
1067 $profile["photo"] = $default["photo"];
1070 if (empty($profile["name"]) && isset($default["name"])) {
1071 $profile["name"] = $default["name"];
1074 if (empty($profile["network"]) && isset($default["network"])) {
1075 $profile["network"] = $default["network"];
1078 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1079 $profile["thumb"] = $profile["photo"];
1082 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1083 $profile["micro"] = $profile["thumb"];
1086 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1087 && in_array($profile["network"], Protocol::FEDERATED)
1089 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1092 // Show contact details of Diaspora contacts only if connected
1093 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1094 $profile["location"] = "";
1095 $profile["about"] = "";
1096 $profile["gender"] = "";
1097 $profile["birthday"] = DBA::NULL_DATE;
1100 $cache[$url][$uid] = $profile;
1106 * @brief Get contact data for a given address
1108 * The function looks at several places (contact table and gcontact table) for the contact
1110 * @param string $addr The profile link
1111 * @param int $uid User id
1113 * @return array Contact data
1114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1115 * @throws \ImagickException
1117 public static function getDetailsByAddr($addr, $uid = -1)
1124 $uid = local_user();
1127 // Fetch contact data from the contact table for the given user
1128 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1129 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1130 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1134 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1135 if (!DBA::isResult($r)) {
1136 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1137 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1138 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1143 // Fetch the data from the gcontact table
1144 if (!DBA::isResult($r)) {
1145 $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`,
1146 `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`
1147 FROM `gcontact` WHERE `addr` = '%s'",
1152 if (!DBA::isResult($r)) {
1153 $data = Probe::uri($addr);
1155 $profile = self::getDetailsByURL($data['url'], $uid);
1164 * @brief Returns the data array for the photo menu of a given contact
1166 * @param array $contact contact
1167 * @param int $uid optional, default 0
1169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1170 * @throws \ImagickException
1172 public static function photoMenu(array $contact, $uid = 0)
1177 $contact_drop_link = '';
1181 $uid = local_user();
1184 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1186 $profile_link = self::magicLink($contact['url']);
1187 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1192 // Look for our own contact if the uid doesn't match and isn't public
1193 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1194 if (DBA::isResult($contact_own)) {
1195 return self::photoMenu($contact_own, $uid);
1200 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1202 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1204 $profile_link = $contact['url'];
1207 if ($profile_link === 'mailbox') {
1212 $status_link = $profile_link . '?tab=status';
1213 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1214 $profile_link = $profile_link . '?tab=profile';
1217 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1218 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1221 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1222 $poke_link = DI::baseUrl() . '/poke/?c=' . $contact['id'];
1225 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1227 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1229 if (!$contact['self']) {
1230 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1234 $unfollow_link = '';
1235 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1236 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1237 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1238 } elseif(!$contact['pending']) {
1239 $follow_link = 'follow?url=' . urlencode($contact['url']);
1245 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1247 if (empty($contact['uid'])) {
1249 'profile' => [L10n::t('View Profile') , $profile_link , true],
1250 'network' => [L10n::t('Network Posts') , $posts_link , false],
1251 'edit' => [L10n::t('View Contact') , $contact_url , false],
1252 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1253 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link, true],
1257 'status' => [L10n::t('View Status') , $status_link , true],
1258 'profile' => [L10n::t('View Profile') , $profile_link , true],
1259 'photos' => [L10n::t('View Photos') , $photos_link , true],
1260 'network' => [L10n::t('Network Posts') , $posts_link , false],
1261 'edit' => [L10n::t('View Contact') , $contact_url , false],
1262 'drop' => [L10n::t('Drop Contact') , $contact_drop_link, false],
1263 'pm' => [L10n::t('Send PM') , $pm_url , false],
1264 'poke' => [L10n::t('Poke') , $poke_link , false],
1265 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1266 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link , true],
1269 if (!empty($contact['pending'])) {
1270 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1271 if (DBA::isResult($intro)) {
1272 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1277 $args = ['contact' => $contact, 'menu' => &$menu];
1279 Hook::callAll('contact_photo_menu', $args);
1281 $menucondensed = [];
1283 foreach ($menu as $menuname => $menuitem) {
1284 if ($menuitem[1] != '') {
1285 $menucondensed[$menuname] = $menuitem;
1289 return $menucondensed;
1293 * @brief Returns ungrouped contact count or list for user
1295 * Returns either the total number of ungrouped contacts for the given user
1296 * id or a paginated list of ungrouped contacts.
1298 * @param int $uid uid
1300 * @throws \Exception
1302 public static function getUngroupedList($uid)
1312 SELECT DISTINCT(`contact-id`)
1314 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1315 WHERE `group`.`uid` = %d
1316 )", intval($uid), intval($uid));
1320 * Have a look at all contact tables for a given profile url.
1321 * This function works as a replacement for probing the contact.
1323 * @param string $url Contact URL
1324 * @param integer $cid Contact ID
1326 * @return array Contact array in the "probe" structure
1328 private static function getProbeDataFromDatabase($url, $cid = null)
1330 // The link could be provided as http although we stored it as https
1331 $ssl_url = str_replace('http://', 'https://', $url);
1333 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1334 'photo', 'keywords', 'location', 'about', 'network',
1335 'priority', 'batch', 'request', 'confirm', 'poco'];
1338 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1339 if (DBA::isResult($data)) {
1344 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1346 if (!DBA::isResult($data)) {
1347 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1348 $data = DBA::selectFirst('contact', $fields, $condition);
1351 if (DBA::isResult($data)) {
1352 // For security reasons we don't fetch key data from our users
1353 $data["pubkey"] = '';
1357 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1358 'photo', 'keywords', 'location', 'about', 'network'];
1359 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1361 if (!DBA::isResult($data)) {
1362 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1363 $data = DBA::selectFirst('contact', $fields, $condition);
1366 if (DBA::isResult($data)) {
1367 $data["pubkey"] = '';
1369 $data["priority"] = 0;
1370 $data["batch"] = '';
1371 $data["request"] = '';
1372 $data["confirm"] = '';
1377 $data = ActivityPub::probeProfile($url, false);
1378 if (!empty($data)) {
1382 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1383 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1384 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1386 if (!DBA::isResult($data)) {
1387 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1388 $data = DBA::selectFirst('contact', $fields, $condition);
1391 if (DBA::isResult($data)) {
1392 $data["pubkey"] = '';
1393 $data["keywords"] = '';
1394 $data["location"] = '';
1395 $data["about"] = '';
1404 * @brief Fetch the contact id for a given URL and user
1406 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1407 * `addr` or `alias`.
1409 * If there's no record and we aren't looking for a public contact, we quit.
1410 * If there's one, we check that it isn't time to update the picture else we
1411 * directly return the found contact id.
1413 * Second, we probe the provided $url whether it's http://server.tld/profile or
1414 * nick@server.tld. We quit if we can't get any info back.
1416 * Third, we create the contact record if it doesn't exist
1418 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1419 * if there's any updates
1421 * @param string $url Contact URL
1422 * @param integer $uid The user id for the contact (0 = public contact)
1423 * @param boolean $no_update Don't update the contact
1424 * @param array $default Default value for creating the contact when every else fails
1425 * @param boolean $in_loop Internally used variable to prevent an endless loop
1427 * @return integer Contact ID
1428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1429 * @throws \ImagickException
1431 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1433 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1441 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1442 // We first try the nurl (http://server.tld/nick), most common case
1443 $fields = ['id', 'avatar', 'updated', 'network'];
1444 $options = ['order' => ['id']];
1445 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1447 // Then the addr (nick@server.tld)
1448 if (!DBA::isResult($contact)) {
1449 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1452 // Then the alias (which could be anything)
1453 if (!DBA::isResult($contact)) {
1454 // The link could be provided as http although we stored it as https
1455 $ssl_url = str_replace('http://', 'https://', $url);
1456 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1457 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1460 if (DBA::isResult($contact)) {
1461 $contact_id = $contact["id"];
1462 $update_contact = false;
1464 // Update the contact every 7 days (Don't update mail or feed contacts)
1465 if (in_array($contact['network'], Protocol::FEDERATED)) {
1466 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1468 // We force the update if the avatar is empty
1469 if (empty($contact['avatar'])) {
1470 $update_contact = true;
1472 } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1473 // Update public mail accounts via their user's accounts
1474 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1475 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1476 if (!DBA::isResult($mailcontact)) {
1477 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1480 if (DBA::isResult($mailcontact)) {
1481 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1485 // Update the contact in the background if needed but it is called by the frontend
1486 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1487 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1490 if (!$update_contact || $no_update) {
1493 } elseif ($uid != 0) {
1494 // Non-existing user-specific contact, exiting
1498 if ($no_update && empty($default)) {
1499 // When we don't want to update, we look if we know this contact in any way
1500 $data = self::getProbeDataFromDatabase($url, $contact_id);
1501 $background_update = true;
1502 } elseif ($no_update && !empty($default['network'])) {
1503 // If there are default values, take these
1505 $background_update = false;
1508 $background_update = false;
1512 $data = Probe::uri($url, "", $uid);
1513 // Ensure that there is a gserver entry
1514 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1515 GServer::check($data['baseurl']);
1519 // Take the default values when probing failed
1520 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1521 $data = array_merge($data, $default);
1524 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1525 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1529 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1530 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1536 'created' => DateTimeFormat::utcNow(),
1537 'url' => $data['url'],
1538 'nurl' => Strings::normaliseLink($data['url']),
1539 'addr' => $data['addr'] ?? '',
1540 'alias' => $data['alias'] ?? '',
1541 'notify' => $data['notify'] ?? '',
1542 'poll' => $data['poll'] ?? '',
1543 'name' => $data['name'] ?? '',
1544 'nick' => $data['nick'] ?? '',
1545 'photo' => $data['photo'] ?? '',
1546 'keywords' => $data['keywords'] ?? '',
1547 'location' => $data['location'] ?? '',
1548 'about' => $data['about'] ?? '',
1549 'network' => $data['network'],
1550 'pubkey' => $data['pubkey'] ?? '',
1551 'rel' => self::SHARING,
1552 'priority' => $data['priority'] ?? 0,
1553 'batch' => $data['batch'] ?? '',
1554 'request' => $data['request'] ?? '',
1555 'confirm' => $data['confirm'] ?? '',
1556 'poco' => $data['poco'] ?? '',
1557 'baseurl' => $data['baseurl'] ?? '',
1558 'name-date' => DateTimeFormat::utcNow(),
1559 'uri-date' => DateTimeFormat::utcNow(),
1560 'avatar-date' => DateTimeFormat::utcNow(),
1566 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1568 // Before inserting we do check if the entry does exist now.
1569 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1570 if (!DBA::isResult($contact)) {
1571 Logger::info('Create new contact', $fields);
1573 self::insert($fields);
1575 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1576 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1577 if (!DBA::isResult($contact)) {
1578 Logger::info('Contact creation failed', $fields);
1583 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1586 $contact_id = $contact["id"];
1589 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1590 self::updateAvatar($data['photo'], $uid, $contact_id);
1593 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1594 if ($background_update) {
1595 // Update in the background when we fetched the data solely from the database
1596 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1598 // Else do a direct update
1599 self::updateFromProbe($contact_id, '', false);
1601 // Update the gcontact entry
1603 GContact::updateFromPublicContactID($contact_id);
1607 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1608 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1610 // This condition should always be true
1611 if (!DBA::isResult($contact)) {
1616 'url' => $data['url'],
1617 'nurl' => Strings::normaliseLink($data['url']),
1618 'updated' => DateTimeFormat::utcNow()
1621 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1623 foreach ($fields as $field) {
1624 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1627 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1628 $updated['uri-date'] = DateTimeFormat::utcNow();
1631 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1632 $updated['name-date'] = DateTimeFormat::utcNow();
1635 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1642 * @brief Checks if the contact is archived
1644 * @param int $cid contact id
1646 * @return boolean Is the contact archived?
1647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1649 public static function isArchived(int $cid)
1655 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1656 if (!DBA::isResult($contact)) {
1660 if ($contact['archive']) {
1664 // Check status of ActivityPub endpoints
1665 $apcontact = APContact::getByURL($contact['url'], false);
1666 if (!empty($apcontact)) {
1667 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1671 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1676 // Check status of Diaspora endpoints
1677 if (!empty($contact['batch'])) {
1678 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1679 return DBA::exists('contact', $condition);
1686 * @brief Checks if the contact is blocked
1688 * @param int $cid contact id
1690 * @return boolean Is the contact blocked?
1691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1693 public static function isBlocked($cid)
1699 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1700 if (!DBA::isResult($blocked)) {
1704 if (Network::isUrlBlocked($blocked['url'])) {
1708 return (bool) $blocked['blocked'];
1712 * @brief Checks if the contact is hidden
1714 * @param int $cid contact id
1716 * @return boolean Is the contact hidden?
1717 * @throws \Exception
1719 public static function isHidden($cid)
1725 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1726 if (!DBA::isResult($hidden)) {
1729 return (bool) $hidden['hidden'];
1733 * @brief Returns posts from a given contact url
1735 * @param string $contact_url Contact URL
1737 * @param bool $thread_mode
1738 * @param int $update
1739 * @return string posts in HTML
1740 * @throws \Exception
1742 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1746 $cid = self::getIdForURL($contact_url);
1748 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1749 if (!DBA::isResult($contact)) {
1753 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1754 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1756 $sql = "`item`.`uid` = ?";
1759 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1762 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1763 $cid, GRAVITY_PARENT, local_user()];
1765 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1766 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1769 $pager = new Pager(DI::args()->getQueryString());
1771 $params = ['order' => ['received' => true],
1772 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1775 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1777 $items = Item::inArray($r);
1779 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1781 $r = Item::selectForUser(local_user(), [], $condition, $params);
1783 $items = Item::inArray($r);
1785 $o = conversation($a, $items, $pager, 'contact-posts', false);
1789 $o .= $pager->renderMinimal(count($items));
1796 * @brief Returns the account type name
1798 * The function can be called with either the user or the contact array
1800 * @param array $contact contact or user array
1803 public static function getAccountType(array $contact)
1805 // There are several fields that indicate that the contact or user is a forum
1806 // "page-flags" is a field in the user table,
1807 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1808 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1809 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1810 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1811 || (isset($contact['forum']) && intval($contact['forum']))
1812 || (isset($contact['prv']) && intval($contact['prv']))
1813 || (isset($contact['community']) && intval($contact['community']))
1815 $type = self::TYPE_COMMUNITY;
1817 $type = self::TYPE_PERSON;
1820 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1821 if (isset($contact["contact-type"])) {
1822 $type = $contact["contact-type"];
1825 if (isset($contact["account-type"])) {
1826 $type = $contact["account-type"];
1830 case self::TYPE_ORGANISATION:
1831 $account_type = L10n::t("Organisation");
1834 case self::TYPE_NEWS:
1835 $account_type = L10n::t('News');
1838 case self::TYPE_COMMUNITY:
1839 $account_type = L10n::t("Forum");
1847 return $account_type;
1851 * @brief Blocks a contact
1855 * @throws \Exception
1857 public static function block($cid, $reason = null)
1859 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1865 * @brief Unblocks a contact
1869 * @throws \Exception
1871 public static function unblock($cid)
1873 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1879 * @brief Updates the avatar links in a contact only if needed
1881 * @param string $avatar Link to avatar picture
1882 * @param int $uid User id of contact owner
1883 * @param int $cid Contact id
1884 * @param bool $force force picture update
1886 * @return array Returns array of the different avatar sizes
1887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1888 * @throws \ImagickException
1890 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1892 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1893 if (!DBA::isResult($contact)) {
1896 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1899 if (($contact["avatar"] != $avatar) || $force) {
1900 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1903 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1904 DBA::update('contact', $fields, ['id' => $cid]);
1906 // Update the public contact (contact id = 0)
1908 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1909 if (DBA::isResult($pcontact)) {
1910 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1922 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1924 * @param integer $id contact id
1925 * @param integer $uid user id
1926 * @param string $url The profile URL of the contact
1927 * @param array $fields The fields that are updated
1929 * @throws \Exception
1931 private static function updateContact($id, $uid, $url, array $fields)
1933 if (!DBA::update('contact', $fields, ['id' => $id])) {
1934 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1938 // Search for duplicated contacts and get rid of them
1939 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1943 // Update the corresponding gcontact entry
1944 GContact::updateFromPublicContactID($id);
1946 // Archive or unarchive the contact. We only need to do this for the public contact.
1947 // The archive/unarchive function will update the personal contacts by themselves.
1948 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1949 if (!DBA::isResult($contact)) {
1950 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1954 if (!empty($fields['success_update'])) {
1955 self::unmarkForArchival($contact);
1956 } elseif (!empty($fields['failure_update'])) {
1957 self::markForArchival($contact);
1960 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1962 // These contacts are sharing with us, we don't poll them.
1963 // This means that we don't set the update fields in "OnePoll.php".
1964 $condition['rel'] = self::SHARING;
1965 DBA::update('contact', $fields, $condition);
1967 unset($fields['last-update']);
1968 unset($fields['success_update']);
1969 unset($fields['failure_update']);
1971 if (empty($fields)) {
1975 // We are polling these contacts, so we mustn't set the update fields here.
1976 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1977 DBA::update('contact', $fields, $condition);
1981 * @brief Remove duplicated contacts
1983 * @param string $nurl Normalised contact url
1984 * @param integer $uid User id
1986 * @throws \Exception
1988 public static function removeDuplicates(string $nurl, int $uid)
1990 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1991 $count = DBA::count('contact', $condition);
1996 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1997 if (!DBA::isResult($first_contact)) {
1998 // Shouldn't happen - so we handle it
2002 $first = $first_contact['id'];
2003 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2004 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2005 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2006 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2010 // Find all duplicates
2011 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2012 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2013 while ($duplicate = DBA::fetch($duplicates)) {
2014 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2018 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2020 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2025 * @param integer $id contact id
2026 * @param string $network Optional network we are probing for
2027 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2030 * @throws \ImagickException
2032 public static function updateFromProbe($id, $network = '', $force = false)
2035 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2036 This will reliably kill your communication with old Friendica contacts.
2039 // These fields aren't updated by this routine:
2040 // 'xmpp', 'sensitive'
2042 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2043 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2044 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2045 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2046 if (!DBA::isResult($contact)) {
2050 $uid = $contact['uid'];
2051 unset($contact['uid']);
2053 $pubkey = $contact['pubkey'];
2054 unset($contact['pubkey']);
2056 $contact['photo'] = $contact['avatar'];
2057 unset($contact['avatar']);
2059 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2061 $updated = DateTimeFormat::utcNow();
2063 // We must not try to update relay contacts via probe. They are no real contacts.
2064 // We check after the probing to be able to correct falsely detected contact types.
2065 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2066 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2067 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2068 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2072 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2073 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2074 if ($force && ($uid == 0)) {
2075 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2080 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2081 $ret['unsearchable'] = $ret['hide'];
2084 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2085 $ret['forum'] = false;
2086 $ret['prv'] = false;
2087 $ret['contact-type'] = $ret['account-type'];
2088 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2089 $apcontact = APContact::getByURL($ret['url'], false);
2090 if (isset($apcontact['manually-approve'])) {
2091 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2092 $ret['prv'] = (bool)!$ret['forum'];
2097 $new_pubkey = $ret['pubkey'];
2101 // make sure to not overwrite existing values with blank entries except some technical fields
2102 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2103 foreach ($ret as $key => $val) {
2104 if (!array_key_exists($key, $contact)) {
2106 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2107 $ret[$key] = $contact[$key];
2108 } elseif ($ret[$key] != $contact[$key]) {
2113 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2114 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2119 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2124 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2125 $ret['updated'] = $updated;
2127 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2128 if (empty($pubkey) && !empty($new_pubkey)) {
2129 $ret['pubkey'] = $new_pubkey;
2132 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2133 $ret['uri-date'] = DateTimeFormat::utcNow();
2136 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2137 $ret['name-date'] = $updated;
2140 if ($force && ($uid == 0)) {
2141 $ret['last-update'] = $updated;
2142 $ret['success_update'] = $updated;
2145 unset($ret['photo']);
2147 self::updateContact($id, $uid, $ret['url'], $ret);
2152 public static function updateFromProbeByURL($url, $force = false)
2154 $id = self::getIdForURL($url);
2160 self::updateFromProbe($id, '', $force);
2166 * Detects if a given contact array belongs to a legacy DFRN connection
2168 * @param array $contact
2171 public static function isLegacyDFRNContact($contact)
2173 // Newer Friendica contacts are connected via AP, then these fields aren't set
2174 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2178 * Detects the communication protocol for a given contact url.
2179 * This is used to detect Friendica contacts that we can communicate via AP.
2181 * @param string $url contact url
2182 * @param string $network Network of that contact
2183 * @return string with protocol
2185 public static function getProtocol($url, $network)
2187 if ($network != Protocol::DFRN) {
2191 $apcontact = APContact::getByURL($url);
2192 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2193 return Protocol::ACTIVITYPUB;
2200 * Takes a $uid and a url/handle and adds a new contact
2201 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2202 * dfrn_request page.
2204 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2207 * $return['success'] boolean true if successful
2208 * $return['message'] error text if success is false.
2210 * @brief Takes a $uid and a url/handle and adds a new contact
2212 * @param string $url
2213 * @param bool $interactive
2214 * @param string $network
2216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2217 * @throws \ImagickException
2219 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2221 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2225 // remove ajax junk, e.g. Twitter
2226 $url = str_replace('/#!/', '/', $url);
2228 if (!Network::isUrlAllowed($url)) {
2229 $result['message'] = L10n::t('Disallowed profile URL.');
2233 if (Network::isUrlBlocked($url)) {
2234 $result['message'] = L10n::t('Blocked domain');
2239 $result['message'] = L10n::t('Connect URL missing.');
2243 $arr = ['url' => $url, 'contact' => []];
2245 Hook::callAll('follow', $arr);
2248 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2252 if (!empty($arr['contact']['name'])) {
2253 $ret = $arr['contact'];
2255 $ret = Probe::uri($url, $network, $uid, false);
2258 if (($network != '') && ($ret['network'] != $network)) {
2259 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2263 // check if we already have a contact
2264 // the poll url is more reliable than the profile url, as we may have
2265 // indirect links or webfinger links
2267 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2268 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2269 if (!DBA::isResult($contact)) {
2270 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2271 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2274 $protocol = self::getProtocol($url, $ret['network']);
2276 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2278 if (strlen(DI::baseUrl()->getUrlPath())) {
2279 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $a->user['nickname']);
2281 $myaddr = bin2hex($a->user['nickname'] . '@' . DI::baseUrl()->getHostname());
2284 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2288 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2289 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2290 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2294 // This extra param just confuses things, remove it
2295 if ($protocol === Protocol::DIASPORA) {
2296 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2299 // do we have enough information?
2300 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2301 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2302 if (empty($ret['poll'])) {
2303 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2305 if (empty($ret['name'])) {
2306 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2308 if (empty($ret['url'])) {
2309 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2311 if (strpos($url, '@') !== false) {
2312 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2313 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2318 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2319 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2320 $ret['notify'] = '';
2323 if (!$ret['notify']) {
2324 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2327 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2329 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2331 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2334 if ($protocol == Protocol::ACTIVITYPUB) {
2335 $apcontact = APContact::getByURL($url, false);
2336 if (isset($apcontact['manually-approve'])) {
2337 $pending = (bool)$apcontact['manually-approve'];
2341 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2345 if (DBA::isResult($contact)) {
2347 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2349 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2350 DBA::update('contact', $fields, ['id' => $contact['id']]);
2352 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2354 // create contact record
2357 'created' => DateTimeFormat::utcNow(),
2358 'url' => $ret['url'],
2359 'nurl' => Strings::normaliseLink($ret['url']),
2360 'addr' => $ret['addr'],
2361 'alias' => $ret['alias'],
2362 'batch' => $ret['batch'],
2363 'notify' => $ret['notify'],
2364 'poll' => $ret['poll'],
2365 'poco' => $ret['poco'],
2366 'name' => $ret['name'],
2367 'nick' => $ret['nick'],
2368 'network' => $ret['network'],
2369 'baseurl' => $ret['baseurl'],
2370 'protocol' => $protocol,
2371 'pubkey' => $ret['pubkey'],
2372 'rel' => $new_relation,
2373 'priority'=> $ret['priority'],
2374 'writable'=> $writeable,
2375 'hidden' => $hidden,
2378 'pending' => $pending,
2383 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2384 if (!DBA::isResult($contact)) {
2385 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2389 $contact_id = $contact['id'];
2390 $result['cid'] = $contact_id;
2392 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2394 // Update the avatar
2395 self::updateAvatar($ret['photo'], $uid, $contact_id);
2397 // pull feed and consume it, which should subscribe to the hub.
2399 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2401 $owner = User::getOwnerDataById($uid);
2403 if (DBA::isResult($owner)) {
2404 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2405 // create a follow slap
2407 $item['verb'] = Activity::FOLLOW;
2408 $item['follow'] = $contact["url"];
2410 $item['title'] = '';
2413 $item['attach'] = '';
2415 $slap = OStatus::salmon($item, $owner);
2417 if (!empty($contact['notify'])) {
2418 Salmon::slapper($owner, $contact['notify'], $slap);
2420 } elseif ($protocol == Protocol::DIASPORA) {
2421 $ret = Diaspora::sendShare($a->user, $contact);
2422 Logger::log('share returns: ' . $ret);
2423 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2424 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2425 if (empty($activity_id)) {
2426 // This really should never happen
2430 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2431 Logger::log('Follow returns: ' . $ret);
2435 $result['success'] = true;
2440 * @brief Updated contact's SSL policy
2442 * @param array $contact Contact array
2443 * @param string $new_policy New policy, valid: self,full
2445 * @return array Contact array with updated values
2446 * @throws \Exception
2448 public static function updateSslPolicy(array $contact, $new_policy)
2450 $ssl_changed = false;
2451 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2452 $ssl_changed = true;
2453 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2454 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2455 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2456 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2457 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2458 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2461 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2462 $ssl_changed = true;
2463 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2464 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2465 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2466 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2467 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2468 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2472 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2473 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2474 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2475 DBA::update('contact', $fields, ['id' => $contact['id']]);
2482 * @param array $importer Owner (local user) data
2483 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2484 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2485 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2486 * @param string $note Introduction additional message
2487 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2489 * @throws \ImagickException
2491 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2493 // Should always be set
2494 if (empty($datarray['author-id'])) {
2498 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2499 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2500 if (!DBA::isResult($pub_contact)) {
2501 // Should never happen
2505 // Contact is blocked at node-level
2506 if (self::isBlocked($datarray['author-id'])) {
2510 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2511 $name = $pub_contact['name'];
2512 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2513 $nick = $pub_contact['nick'];
2514 $network = $pub_contact['network'];
2516 // Ensure that we don't create a new contact when there already is one
2517 $cid = self::getIdForURL($url, $importer['uid']);
2519 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2522 if (!empty($contact)) {
2523 if (!empty($contact['pending'])) {
2524 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2528 // Contact is blocked at user-level
2529 if (!empty($contact['id']) && !empty($importer['id']) &&
2530 self::isBlockedByUser($contact['id'], $importer['id'])) {
2534 // Make sure that the existing contact isn't archived
2535 self::unmarkForArchival($contact);
2537 if (($contact['rel'] == self::SHARING)
2538 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2539 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2540 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2543 // Ensure to always have the correct network type, independent from the connection request method
2544 self::updateFromProbe($contact['id'], '', true);
2548 // send email notification to owner?
2549 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2550 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2554 // create contact record
2555 DBA::insert('contact', [
2556 'uid' => $importer['uid'],
2557 'created' => DateTimeFormat::utcNow(),
2559 'nurl' => Strings::normaliseLink($url),
2563 'network' => $network,
2564 'rel' => self::FOLLOWER,
2571 $contact_id = DBA::lastInsertId();
2573 // Ensure to always have the correct network type, independent from the connection request method
2574 self::updateFromProbe($contact_id, '', true);
2576 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2578 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2580 /// @TODO Encapsulate this into a function/method
2581 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2582 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2583 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2584 // create notification
2585 $hash = Strings::getRandomHex();
2587 if (is_array($contact_record)) {
2588 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2589 'blocked' => false, 'knowyou' => false, 'note' => $note,
2590 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2593 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2595 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2596 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2599 'type' => NOTIFY_INTRO,
2600 'notify_flags' => $user['notify-flags'],
2601 'language' => $user['language'],
2602 'to_name' => $user['username'],
2603 'to_email' => $user['email'],
2604 'uid' => $user['uid'],
2605 'link' => DI::baseUrl() . '/notifications/intro',
2606 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2607 'source_link' => $contact_record['url'],
2608 'source_photo' => $contact_record['photo'],
2609 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2613 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2614 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2615 DBA::update('contact', ['pending' => false], $condition);
2624 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2626 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2627 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2629 Contact::remove($contact['id']);
2633 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2635 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2636 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2638 Contact::remove($contact['id']);
2643 * @brief Create a birthday event.
2645 * Update the year and the birthday.
2647 public static function updateBirthdays()
2651 AND `bd` > "0001-01-01"
2652 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2653 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2654 AND NOT `contact`.`pending`
2655 AND NOT `contact`.`hidden`
2656 AND NOT `contact`.`blocked`
2657 AND NOT `contact`.`archive`
2658 AND NOT `contact`.`deleted`',
2663 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2665 while ($contact = DBA::fetch($contacts)) {
2666 Logger::log('update_contact_birthday: ' . $contact['bd']);
2668 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2670 if (Event::createBirthday($contact, $nextbd)) {
2674 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2675 ['id' => $contact['id']]
2682 * Remove the unavailable contact ids from the provided list
2684 * @param array $contact_ids Contact id list
2685 * @throws \Exception
2687 public static function pruneUnavailable(array &$contact_ids)
2689 if (empty($contact_ids)) {
2693 $str = DBA::escape(implode(',', $contact_ids));
2695 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2698 while($contact = DBA::fetch($stmt)) {
2699 $return[] = $contact['id'];
2704 $contact_ids = $return;
2708 * @brief Returns a magic link to authenticate remote visitors
2710 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2712 * @param string $contact_url The address of the target contact profile
2713 * @param string $url An url that we will be redirected to after the authentication
2715 * @return string with "redir" link
2716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2717 * @throws \ImagickException
2719 public static function magicLink($contact_url, $url = '')
2721 if (!Session::isAuthenticated()) {
2722 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2725 $data = self::getProbeDataFromDatabase($contact_url);
2727 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2730 // Prevents endless loop in case only a non-public contact exists for the contact URL
2731 unset($data['uid']);
2733 return self::magicLinkByContact($data, $url ?: $contact_url);
2737 * @brief Returns a magic link to authenticate remote visitors
2739 * @param integer $cid The contact id of the target contact profile
2740 * @param string $url An url that we will be redirected to after the authentication
2742 * @return string with "redir" link
2743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2744 * @throws \ImagickException
2746 public static function magicLinkbyId($cid, $url = '')
2748 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2750 return self::magicLinkByContact($contact, $url);
2754 * @brief Returns a magic link to authenticate remote visitors
2756 * @param array $contact The contact array with "uid", "network" and "url"
2757 * @param string $url An url that we will be redirected to after the authentication
2759 * @return string with "redir" link
2760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2761 * @throws \ImagickException
2763 public static function magicLinkByContact($contact, $url = '')
2765 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2767 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2768 return $destination;
2771 // Only redirections to the same host do make sense
2772 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2776 if (!empty($contact['uid'])) {
2777 return self::magicLink($contact['url'], $url);
2780 if (empty($contact['id'])) {
2781 return $destination;
2784 $redirect = 'redir/' . $contact['id'];
2786 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2787 $redirect .= '?url=' . $url;
2794 * Remove a contact from all groups
2796 * @param integer $contact_id
2798 * @return boolean Success
2800 public static function removeFromGroups($contact_id)
2802 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2806 * Is the contact a forum?
2808 * @param integer $contactid ID of the contact
2810 * @return boolean "true" if it is a forum
2812 public static function isForum($contactid)
2814 $fields = ['forum', 'prv'];
2815 $condition = ['id' => $contactid];
2816 $contact = DBA::selectFirst('contact', $fields, $condition);
2817 if (!DBA::isResult($contact)) {
2822 return ($contact['forum'] || $contact['prv']);
2826 * Can the remote contact receive private messages?
2828 * @param array $contact
2831 public static function canReceivePrivateMessages(array $contact)
2833 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2834 $self = $contact['self'] ?? false;
2836 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;