3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Notify\Type;
35 use Friendica\Network\Probe;
36 use Friendica\Protocol\Activity;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\DFRN;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Protocol\OStatus;
41 use Friendica\Protocol\Salmon;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Images;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
48 * functions for interacting with a contact
53 * @deprecated since version 2019.03
54 * @see User::PAGE_FLAGS_NORMAL
56 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
58 * @deprecated since version 2019.03
59 * @see User::PAGE_FLAGS_SOAPBOX
61 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
63 * @deprecated since version 2019.03
64 * @see User::PAGE_FLAGS_COMMUNITY
66 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
68 * @deprecated since version 2019.03
69 * @see User::PAGE_FLAGS_FREELOVE
71 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
73 * @deprecated since version 2019.03
74 * @see User::PAGE_FLAGS_BLOG
76 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
78 * @deprecated since version 2019.03
79 * @see User::PAGE_FLAGS_PRVGROUP
81 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
89 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
91 * TYPE_PERSON - the account belongs to a person
92 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
94 * TYPE_ORGANISATION - the account belongs to an organisation
95 * Associated page type: PAGE_SOAPBOX
97 * TYPE_NEWS - the account is a news reflector
98 * Associated page type: PAGE_SOAPBOX
100 * TYPE_COMMUNITY - the account is community forum
101 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
103 * TYPE_RELAY - the account is a relay
104 * This will only be assigned to contacts, not to user accounts
107 const TYPE_UNKNOWN = -1;
108 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
109 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
110 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
111 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
112 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
131 * @param array $fields Array of selected fields, empty for all
132 * @param array $condition Array of fields for condition
133 * @param array $params Array of several parameters
137 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
139 return DBA::selectToArray('contact', $fields, $condition, $params);
143 * @param array $fields Array of selected fields, empty for all
144 * @param array $condition Array of fields for condition
145 * @param array $params Array of several parameters
149 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
151 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
157 * Insert a row into the contact table
158 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
160 * @param array $fields field array
161 * @param bool $on_duplicate_update Do an update on a duplicate entry
163 * @return boolean was the insert successful?
166 public static function insert(array $fields, bool $on_duplicate_update = false)
168 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
169 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
170 if (!DBA::isResult($contact)) {
175 // Search for duplicated contacts and get rid of them
176 self::removeDuplicates($contact['nurl'], $contact['uid']);
182 * @param integer $id Contact ID
183 * @param array $fields Array of selected fields, empty for all
184 * @return array|boolean Contact record if it exists, false otherwise
187 public static function getById($id, $fields = [])
189 return DBA::selectFirst('contact', $fields, ['id' => $id]);
193 * Tests if the given contact is a follower
195 * @param int $cid Either public contact id or user's contact id
196 * @param int $uid User ID
198 * @return boolean is the contact id a follower?
199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
200 * @throws \ImagickException
202 public static function isFollower($cid, $uid)
204 if (self::isBlockedByUser($cid, $uid)) {
208 $cdata = self::getPublicAndUserContacID($cid, $uid);
209 if (empty($cdata['user'])) {
213 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
214 return DBA::exists('contact', $condition);
218 * Tests if the given contact url is a follower
220 * @param string $url Contact URL
221 * @param int $uid User ID
223 * @return boolean is the contact id a follower?
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 * @throws \ImagickException
227 public static function isFollowerByURL($url, $uid)
229 $cid = self::getIdForURL($url, $uid, true);
235 return self::isFollower($cid, $uid);
239 * Tests if the given user follow the given contact
241 * @param int $cid Either public contact id or user's contact id
242 * @param int $uid User ID
244 * @return boolean is the contact url being followed?
245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
246 * @throws \ImagickException
248 public static function isSharing($cid, $uid)
250 if (self::isBlockedByUser($cid, $uid)) {
254 $cdata = self::getPublicAndUserContacID($cid, $uid);
255 if (empty($cdata['user'])) {
259 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
260 return DBA::exists('contact', $condition);
264 * Tests if the given user follow the given contact url
266 * @param string $url Contact URL
267 * @param int $uid User ID
269 * @return boolean is the contact url being followed?
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function isSharingByURL($url, $uid)
275 $cid = self::getIdForURL($url, $uid, true);
281 return self::isSharing($cid, $uid);
285 * Get the basepath for a given contact link
287 * @param string $url The contact link
288 * @param boolean $dont_update Don't update the contact
290 * @return string basepath
291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
292 * @throws \ImagickException
294 public static function getBasepath($url, $dont_update = false)
296 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
297 if (!DBA::isResult($contact)) {
301 if (!empty($contact['baseurl'])) {
302 return $contact['baseurl'];
303 } elseif ($dont_update) {
307 // Update the existing contact
308 self::updateFromProbe($contact['id'], '', true);
310 // And fetch the result
311 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
312 if (empty($contact['baseurl'])) {
313 Logger::info('No baseurl for contact', ['url' => $url]);
317 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
318 return $contact['baseurl'];
322 * Check if the given contact url is on the same server
324 * @param string $url The contact link
326 * @return boolean Is it the same server?
328 public static function isLocal($url)
330 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
334 * Check if the given contact ID is on the same server
336 * @param string $url The contact link
338 * @return boolean Is it the same server?
340 public static function isLocalById(int $cid)
342 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
343 if (!DBA::isResult($contact)) {
347 if (empty($contact['baseurl'])) {
348 $baseurl = self::getBasepath($contact['url'], true);
350 $baseurl = $contact['baseurl'];
353 return Strings::compareLink($baseurl, DI::baseUrl());
357 * Returns the public contact id of the given user id
359 * @param integer $uid User ID
361 * @return integer|boolean Public contact id for given user id
364 public static function getPublicIdByUserId($uid)
366 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
367 if (!DBA::isResult($self)) {
370 return self::getIdForURL($self['url'], 0, true);
374 * Returns the contact id for the user and the public contact id for a given contact id
376 * @param int $cid Either public contact id or user's contact id
377 * @param int $uid User ID
379 * @return array with public and user's contact id
380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
381 * @throws \ImagickException
383 public static function getPublicAndUserContacID($cid, $uid)
385 if (empty($uid) || empty($cid)) {
389 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
390 if (!DBA::isResult($contact)) {
394 // We quit when the user id don't match the user id of the provided contact
395 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
399 if ($contact['uid'] != 0) {
400 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
404 $ucid = $contact['id'];
406 $pcid = $contact['id'];
407 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
410 return ['public' => $pcid, 'user' => $ucid];
414 * Returns contact details for a given contact id in combination with a user id
416 * @param int $cid A contact ID
417 * @param int $uid The User ID
418 * @param array $fields The selected fields for the contact
420 * @return array The contact details
424 public static function getContactForUser($cid, $uid, array $fields = [])
426 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
428 if (!DBA::isResult($contact)) {
436 * Block contact id for user id
438 * @param int $cid Either public contact id or user's contact id
439 * @param int $uid User ID
440 * @param boolean $blocked Is the contact blocked or unblocked?
443 public static function setBlockedForUser($cid, $uid, $blocked)
445 $cdata = self::getPublicAndUserContacID($cid, $uid);
450 if ($cdata['user'] != 0) {
451 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
454 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
458 * Returns "block" state for contact id and user id
460 * @param int $cid Either public contact id or user's contact id
461 * @param int $uid User ID
463 * @return boolean is the contact id blocked for the given user?
466 public static function isBlockedByUser($cid, $uid)
468 $cdata = self::getPublicAndUserContacID($cid, $uid);
473 $public_blocked = false;
475 if (!empty($cdata['public'])) {
476 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
477 if (DBA::isResult($public_contact)) {
478 $public_blocked = $public_contact['blocked'];
482 $user_blocked = $public_blocked;
484 if (!empty($cdata['user'])) {
485 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
486 if (DBA::isResult($user_contact)) {
487 $user_blocked = $user_contact['blocked'];
491 if ($user_blocked != $public_blocked) {
492 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
495 return $user_blocked;
499 * Ignore contact id for user id
501 * @param int $cid Either public contact id or user's contact id
502 * @param int $uid User ID
503 * @param boolean $ignored Is the contact ignored or unignored?
506 public static function setIgnoredForUser($cid, $uid, $ignored)
508 $cdata = self::getPublicAndUserContacID($cid, $uid);
513 if ($cdata['user'] != 0) {
514 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
517 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
521 * Returns "ignore" state 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
526 * @return boolean is the contact id ignored for the given user?
529 public static function isIgnoredByUser($cid, $uid)
531 $cdata = self::getPublicAndUserContacID($cid, $uid);
536 $public_ignored = false;
538 if (!empty($cdata['public'])) {
539 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
540 if (DBA::isResult($public_contact)) {
541 $public_ignored = $public_contact['ignored'];
545 $user_ignored = $public_ignored;
547 if (!empty($cdata['user'])) {
548 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
549 if (DBA::isResult($user_contact)) {
550 $user_ignored = $user_contact['readonly'];
554 if ($user_ignored != $public_ignored) {
555 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
558 return $user_ignored;
562 * Set "collapsed" for contact id and user id
564 * @param int $cid Either public contact id or user's contact id
565 * @param int $uid User ID
566 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
569 public static function setCollapsedForUser($cid, $uid, $collapsed)
571 $cdata = self::getPublicAndUserContacID($cid, $uid);
576 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
580 * Returns "collapsed" state for contact id and user id
582 * @param int $cid Either public contact id or user's contact id
583 * @param int $uid User ID
585 * @return boolean is the contact id blocked for the given user?
586 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
587 * @throws \ImagickException
589 public static function isCollapsedByUser($cid, $uid)
591 $cdata = self::getPublicAndUserContacID($cid, $uid);
598 if (!empty($cdata['public'])) {
599 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
600 if (DBA::isResult($public_contact)) {
601 $collapsed = $public_contact['collapsed'];
609 * Returns a list of contacts belonging in a group
615 public static function getByGroupId($gid)
620 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
622 INNER JOIN `group_member`
623 ON `contact`.`id` = `group_member`.`contact-id`
625 AND `contact`.`uid` = ?
626 AND NOT `contact`.`self`
627 AND NOT `contact`.`deleted`
628 AND NOT `contact`.`blocked`
629 AND NOT `contact`.`pending`
630 ORDER BY `contact`.`name` ASC',
635 if (DBA::isResult($stmt)) {
636 $return = DBA::toArray($stmt);
644 * Returns the count of OStatus contacts in a group
650 public static function getOStatusCountByGroupId($gid)
654 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
656 INNER JOIN `group_member`
657 ON `contact`.`id` = `group_member`.`contact-id`
659 AND `contact`.`uid` = ?
660 AND `contact`.`network` = ?
661 AND `contact`.`notify` != ""',
666 $return = $contacts['count'];
673 * Creates the self-contact for the provided user id
676 * @return bool Operation success
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 public static function createSelfFromUserId($uid)
681 // Only create the entry if it doesn't exist yet
682 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
686 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
687 if (!DBA::isResult($user)) {
691 $return = DBA::insert('contact', [
692 'uid' => $user['uid'],
693 'created' => DateTimeFormat::utcNow(),
695 'name' => $user['username'],
696 'nick' => $user['nickname'],
697 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
698 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
699 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
702 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
703 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
704 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
705 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
706 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
707 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
708 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
709 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
710 'name-date' => DateTimeFormat::utcNow(),
711 'uri-date' => DateTimeFormat::utcNow(),
712 'avatar-date' => DateTimeFormat::utcNow(),
720 * Updates the self-contact for the provided user id
723 * @param boolean $update_avatar Force the avatar update
724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
726 public static function updateSelfFromUserID($uid, $update_avatar = false)
728 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
729 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
730 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
731 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
732 if (!DBA::isResult($self)) {
736 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
737 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
738 if (!DBA::isResult($user)) {
742 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
743 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
744 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
745 if (!DBA::isResult($profile)) {
749 $file_suffix = 'jpg';
751 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
752 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
753 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
754 'gender' => '', 'contact-type' => $user['account-type'],
755 'xmpp' => $profile['xmpp']];
757 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
758 if (DBA::isResult($avatar)) {
759 if ($update_avatar) {
760 $fields['avatar-date'] = DateTimeFormat::utcNow();
763 // Creating the path to the avatar, beginning with the file suffix
764 $types = Images::supportedTypes();
765 if (isset($types[$avatar['type']])) {
766 $file_suffix = $types[$avatar['type']];
769 // We are adding a timestamp value so that other systems won't use cached content
770 $timestamp = strtotime($fields['avatar-date']);
772 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
773 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
775 $fields['photo'] = $prefix . '4' . $suffix;
776 $fields['thumb'] = $prefix . '5' . $suffix;
777 $fields['micro'] = $prefix . '6' . $suffix;
779 // We hadn't found a photo entry, so we use the default avatar
780 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
781 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
782 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
785 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
786 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
787 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
788 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
790 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
791 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
792 $fields['nurl'] = Strings::normaliseLink($fields['url']);
793 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
794 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
795 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
796 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
797 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
798 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
802 foreach ($fields as $field => $content) {
803 if ($self[$field] != $content) {
809 if ($fields['name'] != $self['name']) {
810 $fields['name-date'] = DateTimeFormat::utcNow();
812 $fields['updated'] = DateTimeFormat::utcNow();
813 DBA::update('contact', $fields, ['id' => $self['id']]);
815 // Update the public contact as well
816 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
818 // Update the profile
819 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
820 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
821 DBA::update('profile', $fields, ['uid' => $uid]);
826 * Marks a contact for removal
828 * @param int $id contact id
830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
832 public static function remove($id)
834 // We want just to make sure that we don't delete our "self" contact
835 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
836 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
840 // Archive the contact
841 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
843 // Delete it in the background
844 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
848 * Sends an unfriend message. Does not remove the contact
850 * @param array $user User unfriending
851 * @param array $contact Contact unfriended
852 * @param boolean $dissolve Remove the contact on the remote side
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855 * @throws \ImagickException
857 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
859 if (empty($contact['network'])) {
863 $protocol = $contact['network'];
864 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
865 $protocol = Protocol::ACTIVITYPUB;
868 if (($protocol == Protocol::DFRN) && $dissolve) {
869 DFRN::deliver($user, $contact, 'placeholder', true);
870 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
871 // create an unfollow slap
873 $item['verb'] = Activity::O_UNFOLLOW;
874 $item['follow'] = $contact["url"];
879 $item['attach'] = '';
880 $slap = OStatus::salmon($item, $user);
882 if (!empty($contact['notify'])) {
883 Salmon::slapper($user, $contact['notify'], $slap);
885 } elseif ($protocol == Protocol::DIASPORA) {
886 Diaspora::sendUnshare($user, $contact);
887 } elseif ($protocol == Protocol::ACTIVITYPUB) {
888 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
891 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
897 * Marks a contact for archival after a communication issue delay
899 * Contact has refused to recognise us as a friend. We will start a countdown.
900 * If they still don't recognise us in 32 days, the relationship is over,
901 * and we won't waste any more time trying to communicate with them.
902 * This provides for the possibility that their database is temporarily messed
903 * up or some other transient event and that there's a possibility we could recover from it.
905 * @param array $contact contact to mark for archival
907 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
909 public static function markForArchival(array $contact)
911 if (!isset($contact['url']) && !empty($contact['id'])) {
912 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
913 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
914 if (!DBA::isResult($contact)) {
917 } elseif (!isset($contact['url'])) {
918 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
921 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
923 // Contact already archived or "self" contact? => nothing to do
924 if ($contact['archive'] || $contact['self']) {
928 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
929 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
930 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
933 * We really should send a notification to the owner after 2-3 weeks
934 * so they won't be surprised when the contact vanishes and can take
935 * remedial action if this was a serious mistake or glitch
938 /// @todo Check for contact vitality via probing
939 $archival_days = DI::config()->get('system', 'archival_days', 32);
941 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
942 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
943 /* Relationship is really truly dead. archive them rather than
944 * delete, though if the owner tries to unarchive them we'll start
945 * the whole process over again.
947 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
948 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
949 GContact::updateFromPublicContactURL($contact['url']);
955 * Cancels the archival countdown
957 * @see Contact::markForArchival()
959 * @param array $contact contact to be unmarked for archival
963 public static function unmarkForArchival(array $contact)
965 // Always unarchive the relay contact entry
966 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
967 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
968 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
969 DBA::update('contact', $fields, $condition);
972 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
973 $exists = DBA::exists('contact', $condition);
975 // We don't need to update, we never marked this contact for archival
980 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
982 if (!isset($contact['url']) && !empty($contact['id'])) {
983 $fields = ['id', 'url', 'batch'];
984 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
985 if (!DBA::isResult($contact)) {
990 // It's a miracle. Our dead contact has inexplicably come back to life.
991 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
992 DBA::update('contact', $fields, ['id' => $contact['id']]);
993 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
994 GContact::updateFromPublicContactURL($contact['url']);
998 * Get contact data for a given profile link
1000 * The function looks at several places (contact table and gcontact table) for the contact
1001 * It caches its result for the same script execution to prevent duplicate calls
1003 * @param string $url The profile link
1004 * @param int $uid User id
1005 * @param array $default If not data was found take this data as default value
1007 * @return array Contact data
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1010 public static function getDetailsByURL($url, $uid = -1, array $default = [])
1019 $uid = local_user();
1022 if (isset($cache[$url][$uid])) {
1023 return $cache[$url][$uid];
1026 $ssl_url = str_replace('http://', 'https://', $url);
1028 $nurl = Strings::normaliseLink($url);
1030 // Fetch contact data from the contact table for the given user
1031 $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`,
1032 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1033 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
1034 $r = DBA::toArray($s);
1036 // Fetch contact data from the contact table for the given user, checking with the alias
1037 if (!DBA::isResult($r)) {
1038 $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`,
1039 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1040 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
1041 $r = DBA::toArray($s);
1044 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1045 if (!DBA::isResult($r)) {
1046 $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`,
1047 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1048 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1049 $r = DBA::toArray($s);
1052 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1053 if (!DBA::isResult($r)) {
1054 $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`,
1055 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1056 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1057 $r = DBA::toArray($s);
1060 // Fetch the data from the gcontact table
1061 if (!DBA::isResult($r)) {
1062 $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`,
1063 `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`
1064 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1065 $r = DBA::toArray($s);
1068 if (DBA::isResult($r)) {
1069 // If there is more than one entry we filter out the connector networks
1070 if (count($r) > 1) {
1071 foreach ($r as $id => $result) {
1072 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1078 $profile = array_shift($r);
1080 // "bd" always contains the upcoming birthday of a contact.
1081 // "birthday" might contain the birthday including the year of birth.
1082 if ($profile["birthday"] > DBA::NULL_DATE) {
1083 $bd_timestamp = strtotime($profile["birthday"]);
1084 $month = date("m", $bd_timestamp);
1085 $day = date("d", $bd_timestamp);
1087 $current_timestamp = time();
1088 $current_year = date("Y", $current_timestamp);
1089 $current_month = date("m", $current_timestamp);
1090 $current_day = date("d", $current_timestamp);
1092 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1093 $current = $current_year . "-" . $current_month . "-" . $current_day;
1095 if ($profile["bd"] < $current) {
1096 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1099 $profile["bd"] = DBA::NULL_DATE;
1102 $profile = $default;
1105 if (empty($profile["photo"]) && isset($default["photo"])) {
1106 $profile["photo"] = $default["photo"];
1109 if (empty($profile["name"]) && isset($default["name"])) {
1110 $profile["name"] = $default["name"];
1113 if (empty($profile["network"]) && isset($default["network"])) {
1114 $profile["network"] = $default["network"];
1117 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1118 $profile["thumb"] = $profile["photo"];
1121 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1122 $profile["micro"] = $profile["thumb"];
1125 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1126 && in_array($profile["network"], Protocol::FEDERATED)
1128 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1131 // Show contact details of Diaspora contacts only if connected
1132 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1133 $profile["location"] = "";
1134 $profile["about"] = "";
1135 $profile["gender"] = "";
1136 $profile["birthday"] = DBA::NULL_DATE;
1139 $cache[$url][$uid] = $profile;
1145 * Get contact data for a given address
1147 * The function looks at several places (contact table and gcontact table) for the contact
1149 * @param string $addr The profile link
1150 * @param int $uid User id
1152 * @return array Contact data
1153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1154 * @throws \ImagickException
1156 public static function getDetailsByAddr($addr, $uid = -1)
1163 $uid = local_user();
1166 // Fetch contact data from the contact table for the given user
1167 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1168 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1169 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1173 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1174 if (!DBA::isResult($r)) {
1175 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1176 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1177 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1182 // Fetch the data from the gcontact table
1183 if (!DBA::isResult($r)) {
1184 $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`,
1185 `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`
1186 FROM `gcontact` WHERE `addr` = '%s'",
1191 if (!DBA::isResult($r)) {
1192 $data = Probe::uri($addr);
1194 $profile = self::getDetailsByURL($data['url'], $uid);
1203 * Returns the data array for the photo menu of a given contact
1205 * @param array $contact contact
1206 * @param int $uid optional, default 0
1208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1209 * @throws \ImagickException
1211 public static function photoMenu(array $contact, $uid = 0)
1216 $contact_drop_link = '';
1220 $uid = local_user();
1223 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1225 $profile_link = self::magicLink($contact['url']);
1226 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1231 // Look for our own contact if the uid doesn't match and isn't public
1232 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1233 if (DBA::isResult($contact_own)) {
1234 return self::photoMenu($contact_own, $uid);
1239 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1241 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1243 $profile_link = $contact['url'];
1246 if ($profile_link === 'mailbox') {
1251 $status_link = $profile_link . '/status';
1252 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1253 $profile_link = $profile_link . '/profile';
1256 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1257 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1260 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1261 $poke_link = DI::baseUrl() . '/poke/?c=' . $contact['id'];
1264 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1266 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1268 if (!$contact['self']) {
1269 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1273 $unfollow_link = '';
1274 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1275 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1276 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1277 } elseif(!$contact['pending']) {
1278 $follow_link = 'follow?url=' . urlencode($contact['url']);
1284 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1286 if (empty($contact['uid'])) {
1288 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1289 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1290 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1291 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1292 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1296 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1297 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1298 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1299 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1300 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1301 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1302 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1303 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1304 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1305 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1308 if (!empty($contact['pending'])) {
1309 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1310 if (DBA::isResult($intro)) {
1311 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1316 $args = ['contact' => $contact, 'menu' => &$menu];
1318 Hook::callAll('contact_photo_menu', $args);
1320 $menucondensed = [];
1322 foreach ($menu as $menuname => $menuitem) {
1323 if ($menuitem[1] != '') {
1324 $menucondensed[$menuname] = $menuitem;
1328 return $menucondensed;
1332 * Returns ungrouped contact count or list for user
1334 * Returns either the total number of ungrouped contacts for the given user
1335 * id or a paginated list of ungrouped contacts.
1337 * @param int $uid uid
1339 * @throws \Exception
1341 public static function getUngroupedList($uid)
1351 SELECT DISTINCT(`contact-id`)
1353 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1354 WHERE `group`.`uid` = %d
1355 )", intval($uid), intval($uid));
1359 * Have a look at all contact tables for a given profile url.
1360 * This function works as a replacement for probing the contact.
1362 * @param string $url Contact URL
1363 * @param integer $cid Contact ID
1365 * @return array Contact array in the "probe" structure
1367 private static function getProbeDataFromDatabase($url, $cid = null)
1369 // The link could be provided as http although we stored it as https
1370 $ssl_url = str_replace('http://', 'https://', $url);
1372 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1373 'photo', 'keywords', 'location', 'about', 'network',
1374 'priority', 'batch', 'request', 'confirm', 'poco'];
1377 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1378 if (DBA::isResult($data)) {
1383 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1385 if (!DBA::isResult($data)) {
1386 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1387 $data = DBA::selectFirst('contact', $fields, $condition);
1390 if (DBA::isResult($data)) {
1391 // For security reasons we don't fetch key data from our users
1392 $data["pubkey"] = '';
1396 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1397 'photo', 'keywords', 'location', 'about', 'network'];
1398 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1400 if (!DBA::isResult($data)) {
1401 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1402 $data = DBA::selectFirst('contact', $fields, $condition);
1405 if (DBA::isResult($data)) {
1406 $data["pubkey"] = '';
1408 $data["priority"] = 0;
1409 $data["batch"] = '';
1410 $data["request"] = '';
1411 $data["confirm"] = '';
1416 $data = ActivityPub::probeProfile($url, false);
1417 if (!empty($data)) {
1421 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1422 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1423 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1425 if (!DBA::isResult($data)) {
1426 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1427 $data = DBA::selectFirst('contact', $fields, $condition);
1430 if (DBA::isResult($data)) {
1431 $data["pubkey"] = '';
1432 $data["keywords"] = '';
1433 $data["location"] = '';
1434 $data["about"] = '';
1443 * Fetch the contact id for a given URL and user
1445 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1446 * `addr` or `alias`.
1448 * If there's no record and we aren't looking for a public contact, we quit.
1449 * If there's one, we check that it isn't time to update the picture else we
1450 * directly return the found contact id.
1452 * Second, we probe the provided $url whether it's http://server.tld/profile or
1453 * nick@server.tld. We quit if we can't get any info back.
1455 * Third, we create the contact record if it doesn't exist
1457 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1458 * if there's any updates
1460 * @param string $url Contact URL
1461 * @param integer $uid The user id for the contact (0 = public contact)
1462 * @param boolean $no_update Don't update the contact
1463 * @param array $default Default value for creating the contact when every else fails
1464 * @param boolean $in_loop Internally used variable to prevent an endless loop
1466 * @return integer Contact ID
1467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1468 * @throws \ImagickException
1470 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1472 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1480 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1481 // We first try the nurl (http://server.tld/nick), most common case
1482 $fields = ['id', 'avatar', 'updated', 'network'];
1483 $options = ['order' => ['id']];
1484 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1486 // Then the addr (nick@server.tld)
1487 if (!DBA::isResult($contact)) {
1488 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1491 // Then the alias (which could be anything)
1492 if (!DBA::isResult($contact)) {
1493 // The link could be provided as http although we stored it as https
1494 $ssl_url = str_replace('http://', 'https://', $url);
1495 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1496 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1499 if (DBA::isResult($contact)) {
1500 $contact_id = $contact["id"];
1501 $update_contact = false;
1503 // Update the contact every 7 days (Don't update mail or feed contacts)
1504 if (in_array($contact['network'], Protocol::FEDERATED)) {
1505 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1507 // We force the update if the avatar is empty
1508 if (empty($contact['avatar'])) {
1509 $update_contact = true;
1511 } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1512 // Update public mail accounts via their user's accounts
1513 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1514 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1515 if (!DBA::isResult($mailcontact)) {
1516 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1519 if (DBA::isResult($mailcontact)) {
1520 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1524 // Update the contact in the background if needed but it is called by the frontend
1525 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1526 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1529 if (!$update_contact || $no_update) {
1532 } elseif ($uid != 0) {
1533 // Non-existing user-specific contact, exiting
1537 if ($no_update && empty($default)) {
1538 // When we don't want to update, we look if we know this contact in any way
1539 $data = self::getProbeDataFromDatabase($url, $contact_id);
1540 $background_update = true;
1541 } elseif ($no_update && !empty($default['network'])) {
1542 // If there are default values, take these
1544 $background_update = false;
1547 $background_update = false;
1551 $data = Probe::uri($url, "", $uid);
1552 // Ensure that there is a gserver entry
1553 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1554 GServer::check($data['baseurl']);
1558 // Take the default values when probing failed
1559 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1560 $data = array_merge($data, $default);
1563 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1564 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1568 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1569 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1575 'created' => DateTimeFormat::utcNow(),
1576 'url' => $data['url'],
1577 'nurl' => Strings::normaliseLink($data['url']),
1578 'addr' => $data['addr'] ?? '',
1579 'alias' => $data['alias'] ?? '',
1580 'notify' => $data['notify'] ?? '',
1581 'poll' => $data['poll'] ?? '',
1582 'name' => $data['name'] ?? '',
1583 'nick' => $data['nick'] ?? '',
1584 'photo' => $data['photo'] ?? '',
1585 'keywords' => $data['keywords'] ?? '',
1586 'location' => $data['location'] ?? '',
1587 'about' => $data['about'] ?? '',
1588 'network' => $data['network'],
1589 'pubkey' => $data['pubkey'] ?? '',
1590 'rel' => self::SHARING,
1591 'priority' => $data['priority'] ?? 0,
1592 'batch' => $data['batch'] ?? '',
1593 'request' => $data['request'] ?? '',
1594 'confirm' => $data['confirm'] ?? '',
1595 'poco' => $data['poco'] ?? '',
1596 'baseurl' => $data['baseurl'] ?? '',
1597 'name-date' => DateTimeFormat::utcNow(),
1598 'uri-date' => DateTimeFormat::utcNow(),
1599 'avatar-date' => DateTimeFormat::utcNow(),
1605 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1607 // Before inserting we do check if the entry does exist now.
1608 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1609 if (!DBA::isResult($contact)) {
1610 Logger::info('Create new contact', $fields);
1612 self::insert($fields);
1614 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1615 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1616 if (!DBA::isResult($contact)) {
1617 Logger::info('Contact creation failed', $fields);
1622 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1625 $contact_id = $contact["id"];
1628 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1629 self::updateAvatar($data['photo'], $uid, $contact_id);
1632 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1633 if ($background_update) {
1634 // Update in the background when we fetched the data solely from the database
1635 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1637 // Else do a direct update
1638 self::updateFromProbe($contact_id, '', false);
1640 // Update the gcontact entry
1642 GContact::updateFromPublicContactID($contact_id);
1646 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1647 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1649 // This condition should always be true
1650 if (!DBA::isResult($contact)) {
1655 'url' => $data['url'],
1656 'nurl' => Strings::normaliseLink($data['url']),
1657 'updated' => DateTimeFormat::utcNow()
1660 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1662 foreach ($fields as $field) {
1663 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1666 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1667 $updated['uri-date'] = DateTimeFormat::utcNow();
1670 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1671 $updated['name-date'] = DateTimeFormat::utcNow();
1674 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1681 * Checks if the contact is archived
1683 * @param int $cid contact id
1685 * @return boolean Is the contact archived?
1686 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1688 public static function isArchived(int $cid)
1694 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1695 if (!DBA::isResult($contact)) {
1699 if ($contact['archive']) {
1703 // Check status of ActivityPub endpoints
1704 $apcontact = APContact::getByURL($contact['url'], false);
1705 if (!empty($apcontact)) {
1706 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1710 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1715 // Check status of Diaspora endpoints
1716 if (!empty($contact['batch'])) {
1717 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1718 return DBA::exists('contact', $condition);
1725 * Checks if the contact is blocked
1727 * @param int $cid contact id
1729 * @return boolean Is the contact blocked?
1730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1732 public static function isBlocked($cid)
1738 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1739 if (!DBA::isResult($blocked)) {
1743 if (Network::isUrlBlocked($blocked['url'])) {
1747 return (bool) $blocked['blocked'];
1751 * Checks if the contact is hidden
1753 * @param int $cid contact id
1755 * @return boolean Is the contact hidden?
1756 * @throws \Exception
1758 public static function isHidden($cid)
1764 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1765 if (!DBA::isResult($hidden)) {
1768 return (bool) $hidden['hidden'];
1772 * Returns posts from a given contact url
1774 * @param string $contact_url Contact URL
1776 * @param bool $thread_mode
1777 * @param int $update
1778 * @return string posts in HTML
1779 * @throws \Exception
1781 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1785 $cid = self::getIdForURL($contact_url);
1787 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1788 if (!DBA::isResult($contact)) {
1792 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1793 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1795 $sql = "`item`.`uid` = ?";
1798 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1801 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1802 $cid, GRAVITY_PARENT, local_user()];
1804 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1805 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1808 $pager = new Pager(DI::args()->getQueryString());
1810 $params = ['order' => ['received' => true],
1811 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1814 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1816 $items = Item::inArray($r);
1818 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1820 $r = Item::selectForUser(local_user(), [], $condition, $params);
1822 $items = Item::inArray($r);
1824 $o = conversation($a, $items, $pager, 'contact-posts', false);
1828 $o .= $pager->renderMinimal(count($items));
1835 * Returns the account type name
1837 * The function can be called with either the user or the contact array
1839 * @param array $contact contact or user array
1842 public static function getAccountType(array $contact)
1844 // There are several fields that indicate that the contact or user is a forum
1845 // "page-flags" is a field in the user table,
1846 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1847 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1848 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1849 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1850 || (isset($contact['forum']) && intval($contact['forum']))
1851 || (isset($contact['prv']) && intval($contact['prv']))
1852 || (isset($contact['community']) && intval($contact['community']))
1854 $type = self::TYPE_COMMUNITY;
1856 $type = self::TYPE_PERSON;
1859 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1860 if (isset($contact["contact-type"])) {
1861 $type = $contact["contact-type"];
1864 if (isset($contact["account-type"])) {
1865 $type = $contact["account-type"];
1869 case self::TYPE_ORGANISATION:
1870 $account_type = DI::l10n()->t("Organisation");
1873 case self::TYPE_NEWS:
1874 $account_type = DI::l10n()->t('News');
1877 case self::TYPE_COMMUNITY:
1878 $account_type = DI::l10n()->t("Forum");
1886 return $account_type;
1894 * @throws \Exception
1896 public static function block($cid, $reason = null)
1898 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1904 * Unblocks a contact
1908 * @throws \Exception
1910 public static function unblock($cid)
1912 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1918 * Updates the avatar links in a contact only if needed
1920 * @param string $avatar Link to avatar picture
1921 * @param int $uid User id of contact owner
1922 * @param int $cid Contact id
1923 * @param bool $force force picture update
1925 * @return array Returns array of the different avatar sizes
1926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1927 * @throws \ImagickException
1929 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1931 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1932 if (!DBA::isResult($contact)) {
1935 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1938 foreach ($data as $image_uri) {
1939 $image_rid = Photo::ridFromURI($image_uri);
1940 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1941 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1946 if (($contact["avatar"] != $avatar) || $force) {
1947 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1950 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1951 DBA::update('contact', $fields, ['id' => $cid]);
1953 // Update the public contact (contact id = 0)
1955 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1956 if (DBA::isResult($pcontact)) {
1957 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1969 * Helper function for "updateFromProbe". Updates personal and public contact
1971 * @param integer $id contact id
1972 * @param integer $uid user id
1973 * @param string $url The profile URL of the contact
1974 * @param array $fields The fields that are updated
1976 * @throws \Exception
1978 private static function updateContact($id, $uid, $url, array $fields)
1980 if (!DBA::update('contact', $fields, ['id' => $id])) {
1981 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1985 // Search for duplicated contacts and get rid of them
1986 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1990 // Update the corresponding gcontact entry
1991 GContact::updateFromPublicContactID($id);
1993 // Archive or unarchive the contact. We only need to do this for the public contact.
1994 // The archive/unarchive function will update the personal contacts by themselves.
1995 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1996 if (!DBA::isResult($contact)) {
1997 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2001 if (!empty($fields['success_update'])) {
2002 self::unmarkForArchival($contact);
2003 } elseif (!empty($fields['failure_update'])) {
2004 self::markForArchival($contact);
2007 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2009 // These contacts are sharing with us, we don't poll them.
2010 // This means that we don't set the update fields in "OnePoll.php".
2011 $condition['rel'] = self::SHARING;
2012 DBA::update('contact', $fields, $condition);
2014 unset($fields['last-update']);
2015 unset($fields['success_update']);
2016 unset($fields['failure_update']);
2018 if (empty($fields)) {
2022 // We are polling these contacts, so we mustn't set the update fields here.
2023 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2024 DBA::update('contact', $fields, $condition);
2028 * Remove duplicated contacts
2030 * @param string $nurl Normalised contact url
2031 * @param integer $uid User id
2033 * @throws \Exception
2035 public static function removeDuplicates(string $nurl, int $uid)
2037 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2038 $count = DBA::count('contact', $condition);
2043 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2044 if (!DBA::isResult($first_contact)) {
2045 // Shouldn't happen - so we handle it
2049 $first = $first_contact['id'];
2050 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2051 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2052 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2053 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2057 // Find all duplicates
2058 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2059 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2060 while ($duplicate = DBA::fetch($duplicates)) {
2061 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2065 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2067 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2072 * @param integer $id contact id
2073 * @param string $network Optional network we are probing for
2074 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2079 public static function updateFromProbe($id, $network = '', $force = false)
2082 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2083 This will reliably kill your communication with old Friendica contacts.
2086 // These fields aren't updated by this routine:
2087 // 'xmpp', 'sensitive'
2089 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2090 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2091 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2092 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2093 if (!DBA::isResult($contact)) {
2097 $uid = $contact['uid'];
2098 unset($contact['uid']);
2100 $pubkey = $contact['pubkey'];
2101 unset($contact['pubkey']);
2103 $contact['photo'] = $contact['avatar'];
2104 unset($contact['avatar']);
2106 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2108 $updated = DateTimeFormat::utcNow();
2110 // We must not try to update relay contacts via probe. They are no real contacts.
2111 // We check after the probing to be able to correct falsely detected contact types.
2112 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2113 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2114 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2115 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2119 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2120 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2121 if ($force && ($uid == 0)) {
2122 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2127 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2128 $ret['unsearchable'] = $ret['hide'];
2131 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2132 $ret['forum'] = false;
2133 $ret['prv'] = false;
2134 $ret['contact-type'] = $ret['account-type'];
2135 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2136 $apcontact = APContact::getByURL($ret['url'], false);
2137 if (isset($apcontact['manually-approve'])) {
2138 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2139 $ret['prv'] = (bool)!$ret['forum'];
2144 $new_pubkey = $ret['pubkey'];
2148 // make sure to not overwrite existing values with blank entries except some technical fields
2149 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2150 foreach ($ret as $key => $val) {
2151 if (!array_key_exists($key, $contact)) {
2153 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2154 $ret[$key] = $contact[$key];
2155 } elseif ($ret[$key] != $contact[$key]) {
2160 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2161 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2166 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2169 // Update the public contact
2171 self::updateFromProbeByURL($ret['url']);
2177 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2178 $ret['updated'] = $updated;
2180 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2181 if (empty($pubkey) && !empty($new_pubkey)) {
2182 $ret['pubkey'] = $new_pubkey;
2185 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2186 $ret['uri-date'] = DateTimeFormat::utcNow();
2189 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2190 $ret['name-date'] = $updated;
2193 if ($force && ($uid == 0)) {
2194 $ret['last-update'] = $updated;
2195 $ret['success_update'] = $updated;
2198 unset($ret['photo']);
2200 self::updateContact($id, $uid, $ret['url'], $ret);
2205 public static function updateFromProbeByURL($url, $force = false)
2207 $id = self::getIdForURL($url);
2213 self::updateFromProbe($id, '', $force);
2219 * Detects if a given contact array belongs to a legacy DFRN connection
2221 * @param array $contact
2224 public static function isLegacyDFRNContact($contact)
2226 // Newer Friendica contacts are connected via AP, then these fields aren't set
2227 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2231 * Detects the communication protocol for a given contact url.
2232 * This is used to detect Friendica contacts that we can communicate via AP.
2234 * @param string $url contact url
2235 * @param string $network Network of that contact
2236 * @return string with protocol
2238 public static function getProtocol($url, $network)
2240 if ($network != Protocol::DFRN) {
2244 $apcontact = APContact::getByURL($url);
2245 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2246 return Protocol::ACTIVITYPUB;
2253 * Takes a $uid and a url/handle and adds a new contact
2255 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2256 * dfrn_request page.
2258 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2261 * $return['success'] boolean true if successful
2262 * $return['message'] error text if success is false.
2264 * Takes a $uid and a url/handle and adds a new contact
2266 * @param string $url
2267 * @param bool $interactive
2268 * @param string $network
2270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2271 * @throws \ImagickException
2273 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2275 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2279 // remove ajax junk, e.g. Twitter
2280 $url = str_replace('/#!/', '/', $url);
2282 if (!Network::isUrlAllowed($url)) {
2283 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2287 if (Network::isUrlBlocked($url)) {
2288 $result['message'] = DI::l10n()->t('Blocked domain');
2293 $result['message'] = DI::l10n()->t('Connect URL missing.');
2297 $arr = ['url' => $url, 'contact' => []];
2299 Hook::callAll('follow', $arr);
2302 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2306 if (!empty($arr['contact']['name'])) {
2307 $ret = $arr['contact'];
2309 $ret = Probe::uri($url, $network, $uid, false);
2312 if (($network != '') && ($ret['network'] != $network)) {
2313 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2317 // check if we already have a contact
2318 // the poll url is more reliable than the profile url, as we may have
2319 // indirect links or webfinger links
2321 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2322 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2323 if (!DBA::isResult($contact)) {
2324 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2325 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2328 $protocol = self::getProtocol($url, $ret['network']);
2330 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2332 if (strlen(DI::baseUrl()->getUrlPath())) {
2333 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $a->user['nickname']);
2335 $myaddr = bin2hex($a->user['nickname'] . '@' . DI::baseUrl()->getHostname());
2338 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2342 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2343 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2344 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2348 // This extra param just confuses things, remove it
2349 if ($protocol === Protocol::DIASPORA) {
2350 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2353 // do we have enough information?
2354 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2355 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2356 if (empty($ret['poll'])) {
2357 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2359 if (empty($ret['name'])) {
2360 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2362 if (empty($ret['url'])) {
2363 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2365 if (strpos($url, '@') !== false) {
2366 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2367 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2372 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2373 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2374 $ret['notify'] = '';
2377 if (!$ret['notify']) {
2378 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2381 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2383 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2385 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2388 if ($protocol == Protocol::ACTIVITYPUB) {
2389 $apcontact = APContact::getByURL($url, false);
2390 if (isset($apcontact['manually-approve'])) {
2391 $pending = (bool)$apcontact['manually-approve'];
2395 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2399 if (DBA::isResult($contact)) {
2401 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2403 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2404 DBA::update('contact', $fields, ['id' => $contact['id']]);
2406 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2408 // create contact record
2411 'created' => DateTimeFormat::utcNow(),
2412 'url' => $ret['url'],
2413 'nurl' => Strings::normaliseLink($ret['url']),
2414 'addr' => $ret['addr'],
2415 'alias' => $ret['alias'],
2416 'batch' => $ret['batch'],
2417 'notify' => $ret['notify'],
2418 'poll' => $ret['poll'],
2419 'poco' => $ret['poco'],
2420 'name' => $ret['name'],
2421 'nick' => $ret['nick'],
2422 'network' => $ret['network'],
2423 'baseurl' => $ret['baseurl'],
2424 'protocol' => $protocol,
2425 'pubkey' => $ret['pubkey'],
2426 'rel' => $new_relation,
2427 'priority'=> $ret['priority'],
2428 'writable'=> $writeable,
2429 'hidden' => $hidden,
2432 'pending' => $pending,
2437 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2438 if (!DBA::isResult($contact)) {
2439 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2443 $contact_id = $contact['id'];
2444 $result['cid'] = $contact_id;
2446 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2448 // Update the avatar
2449 self::updateAvatar($ret['photo'], $uid, $contact_id);
2451 // pull feed and consume it, which should subscribe to the hub.
2453 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2455 $owner = User::getOwnerDataById($uid);
2457 if (DBA::isResult($owner)) {
2458 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2459 // create a follow slap
2461 $item['verb'] = Activity::FOLLOW;
2462 $item['follow'] = $contact["url"];
2464 $item['title'] = '';
2467 $item['attach'] = '';
2469 $slap = OStatus::salmon($item, $owner);
2471 if (!empty($contact['notify'])) {
2472 Salmon::slapper($owner, $contact['notify'], $slap);
2474 } elseif ($protocol == Protocol::DIASPORA) {
2475 $ret = Diaspora::sendShare($a->user, $contact);
2476 Logger::log('share returns: ' . $ret);
2477 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2478 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2479 if (empty($activity_id)) {
2480 // This really should never happen
2484 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2485 Logger::log('Follow returns: ' . $ret);
2489 $result['success'] = true;
2494 * Updated contact's SSL policy
2496 * @param array $contact Contact array
2497 * @param string $new_policy New policy, valid: self,full
2499 * @return array Contact array with updated values
2500 * @throws \Exception
2502 public static function updateSslPolicy(array $contact, $new_policy)
2504 $ssl_changed = false;
2505 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2506 $ssl_changed = true;
2507 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2508 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2509 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2510 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2511 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2512 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2515 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2516 $ssl_changed = true;
2517 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2518 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2519 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2520 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2521 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2522 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2526 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2527 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2528 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2529 DBA::update('contact', $fields, ['id' => $contact['id']]);
2536 * @param array $importer Owner (local user) data
2537 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2538 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2539 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2540 * @param string $note Introduction additional message
2541 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2542 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2543 * @throws \ImagickException
2545 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2547 // Should always be set
2548 if (empty($datarray['author-id'])) {
2552 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2553 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2554 if (!DBA::isResult($pub_contact)) {
2555 // Should never happen
2559 // Contact is blocked at node-level
2560 if (self::isBlocked($datarray['author-id'])) {
2564 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2565 $name = $pub_contact['name'];
2566 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2567 $nick = $pub_contact['nick'];
2568 $network = $pub_contact['network'];
2570 // Ensure that we don't create a new contact when there already is one
2571 $cid = self::getIdForURL($url, $importer['uid']);
2573 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2576 if (!empty($contact)) {
2577 if (!empty($contact['pending'])) {
2578 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2582 // Contact is blocked at user-level
2583 if (!empty($contact['id']) && !empty($importer['id']) &&
2584 self::isBlockedByUser($contact['id'], $importer['id'])) {
2588 // Make sure that the existing contact isn't archived
2589 self::unmarkForArchival($contact);
2591 if (($contact['rel'] == self::SHARING)
2592 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2593 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2594 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2597 // Ensure to always have the correct network type, independent from the connection request method
2598 self::updateFromProbe($contact['id'], '', true);
2602 // send email notification to owner?
2603 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2604 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2608 // create contact record
2609 DBA::insert('contact', [
2610 'uid' => $importer['uid'],
2611 'created' => DateTimeFormat::utcNow(),
2613 'nurl' => Strings::normaliseLink($url),
2617 'network' => $network,
2618 'rel' => self::FOLLOWER,
2625 $contact_id = DBA::lastInsertId();
2627 // Ensure to always have the correct network type, independent from the connection request method
2628 self::updateFromProbe($contact_id, '', true);
2630 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2632 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2634 /// @TODO Encapsulate this into a function/method
2635 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2636 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2637 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2638 // create notification
2639 $hash = Strings::getRandomHex();
2641 if (is_array($contact_record)) {
2642 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2643 'blocked' => false, 'knowyou' => false, 'note' => $note,
2644 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2647 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2649 if (($user['notify-flags'] & Type::INTRO) &&
2650 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2653 'type' => Type::INTRO,
2654 'notify_flags' => $user['notify-flags'],
2655 'language' => $user['language'],
2656 'to_name' => $user['username'],
2657 'to_email' => $user['email'],
2658 'uid' => $user['uid'],
2659 'link' => DI::baseUrl() . '/notifications/intros',
2660 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2661 'source_link' => $contact_record['url'],
2662 'source_photo' => $contact_record['photo'],
2663 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2667 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2668 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2669 DBA::update('contact', ['pending' => false], $condition);
2678 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2680 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2681 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2683 Contact::remove($contact['id']);
2687 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2689 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2690 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2692 Contact::remove($contact['id']);
2697 * Create a birthday event.
2699 * Update the year and the birthday.
2701 public static function updateBirthdays()
2705 AND `bd` > "0001-01-01"
2706 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2707 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2708 AND NOT `contact`.`pending`
2709 AND NOT `contact`.`hidden`
2710 AND NOT `contact`.`blocked`
2711 AND NOT `contact`.`archive`
2712 AND NOT `contact`.`deleted`',
2717 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2719 while ($contact = DBA::fetch($contacts)) {
2720 Logger::log('update_contact_birthday: ' . $contact['bd']);
2722 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2724 if (Event::createBirthday($contact, $nextbd)) {
2728 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2729 ['id' => $contact['id']]
2736 * Remove the unavailable contact ids from the provided list
2738 * @param array $contact_ids Contact id list
2740 * @throws \Exception
2742 public static function pruneUnavailable(array $contact_ids)
2744 if (empty($contact_ids)) {
2748 $contacts = Contact::selectToArray(['id'], [
2749 'id' => $contact_ids,
2755 return array_column($contacts, 'id');
2759 * Returns a magic link to authenticate remote visitors
2761 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2763 * @param string $contact_url The address of the target contact profile
2764 * @param string $url An url that we will be redirected to after the authentication
2766 * @return string with "redir" link
2767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2768 * @throws \ImagickException
2770 public static function magicLink($contact_url, $url = '')
2772 if (!Session::isAuthenticated()) {
2773 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2776 $data = self::getProbeDataFromDatabase($contact_url);
2778 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2781 // Prevents endless loop in case only a non-public contact exists for the contact URL
2782 unset($data['uid']);
2784 return self::magicLinkByContact($data, $url ?: $contact_url);
2788 * Returns a magic link to authenticate remote visitors
2790 * @param integer $cid The contact id of the target contact profile
2791 * @param string $url An url that we will be redirected to after the authentication
2793 * @return string with "redir" link
2794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2795 * @throws \ImagickException
2797 public static function magicLinkbyId($cid, $url = '')
2799 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2801 return self::magicLinkByContact($contact, $url);
2805 * Returns a magic link to authenticate remote visitors
2807 * @param array $contact The contact array with "uid", "network" and "url"
2808 * @param string $url An url that we will be redirected to after the authentication
2810 * @return string with "redir" link
2811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2812 * @throws \ImagickException
2814 public static function magicLinkByContact($contact, $url = '')
2816 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2818 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2819 return $destination;
2822 // Only redirections to the same host do make sense
2823 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2827 if (!empty($contact['uid'])) {
2828 return self::magicLink($contact['url'], $url);
2831 if (empty($contact['id'])) {
2832 return $destination;
2835 $redirect = 'redir/' . $contact['id'];
2837 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2838 $redirect .= '?url=' . $url;
2845 * Remove a contact from all groups
2847 * @param integer $contact_id
2849 * @return boolean Success
2851 public static function removeFromGroups($contact_id)
2853 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2857 * Is the contact a forum?
2859 * @param integer $contactid ID of the contact
2861 * @return boolean "true" if it is a forum
2863 public static function isForum($contactid)
2865 $fields = ['forum', 'prv'];
2866 $condition = ['id' => $contactid];
2867 $contact = DBA::selectFirst('contact', $fields, $condition);
2868 if (!DBA::isResult($contact)) {
2873 return ($contact['forum'] || $contact['prv']);
2877 * Can the remote contact receive private messages?
2879 * @param array $contact
2882 public static function canReceivePrivateMessages(array $contact)
2884 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2885 $self = $contact['self'] ?? false;
2887 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;