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\HTTPException;
36 use Friendica\Network\Probe;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\DFRN;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Salmon;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
49 * functions for interacting with a contact
54 * @deprecated since version 2019.03
55 * @see User::PAGE_FLAGS_NORMAL
57 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
59 * @deprecated since version 2019.03
60 * @see User::PAGE_FLAGS_SOAPBOX
62 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
64 * @deprecated since version 2019.03
65 * @see User::PAGE_FLAGS_COMMUNITY
67 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
69 * @deprecated since version 2019.03
70 * @see User::PAGE_FLAGS_FREELOVE
72 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
74 * @deprecated since version 2019.03
75 * @see User::PAGE_FLAGS_BLOG
77 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
79 * @deprecated since version 2019.03
80 * @see User::PAGE_FLAGS_PRVGROUP
82 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
90 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
92 * TYPE_PERSON - the account belongs to a person
93 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
95 * TYPE_ORGANISATION - the account belongs to an organisation
96 * Associated page type: PAGE_SOAPBOX
98 * TYPE_NEWS - the account is a news reflector
99 * Associated page type: PAGE_SOAPBOX
101 * TYPE_COMMUNITY - the account is community forum
102 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
104 * TYPE_RELAY - the account is a relay
105 * This will only be assigned to contacts, not to user accounts
108 const TYPE_UNKNOWN = -1;
109 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
110 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
111 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
112 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
113 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
132 * @param array $fields Array of selected fields, empty for all
133 * @param array $condition Array of fields for condition
134 * @param array $params Array of several parameters
138 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
140 return DBA::selectToArray('contact', $fields, $condition, $params);
144 * @param array $fields Array of selected fields, empty for all
145 * @param array $condition Array of fields for condition
146 * @param array $params Array of several parameters
150 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
152 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
158 * Insert a row into the contact table
159 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
161 * @param array $fields field array
162 * @param bool $on_duplicate_update Do an update on a duplicate entry
164 * @return boolean was the insert successful?
167 public static function insert(array $fields, bool $on_duplicate_update = false)
169 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
170 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
171 if (!DBA::isResult($contact)) {
176 // Search for duplicated contacts and get rid of them
177 self::removeDuplicates($contact['nurl'], $contact['uid']);
183 * @param integer $id Contact ID
184 * @param array $fields Array of selected fields, empty for all
185 * @return array|boolean Contact record if it exists, false otherwise
188 public static function getById($id, $fields = [])
190 return DBA::selectFirst('contact', $fields, ['id' => $id]);
194 * Fetches a contact by a given url
196 * @param string $url profile url
197 * @param integer $uid User ID of the contact
198 * @param array $fields Field list
199 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
200 * @return array contact array
202 public static function getByURL(string $url, int $uid = 0, array $fields = [], $update = null)
204 if ($update || is_null($update)) {
205 $cid = self::getIdForURL($url, $uid, !($update ?? false));
209 return self::getById($cid, $fields);
212 // We first try the nurl (http://server.tld/nick), most common case
213 $options = ['order' => ['id']];
214 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
216 // Then the addr (nick@server.tld)
217 if (!DBA::isResult($contact)) {
218 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
221 // Then the alias (which could be anything)
222 if (!DBA::isResult($contact)) {
223 // The link could be provided as http although we stored it as https
224 $ssl_url = str_replace('http://', 'https://', $url);
225 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
226 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
232 * Tests if the given contact is a follower
234 * @param int $cid Either public contact id or user's contact id
235 * @param int $uid User ID
237 * @return boolean is the contact id a follower?
238 * @throws HTTPException\InternalServerErrorException
239 * @throws \ImagickException
241 public static function isFollower($cid, $uid)
243 if (self::isBlockedByUser($cid, $uid)) {
247 $cdata = self::getPublicAndUserContacID($cid, $uid);
248 if (empty($cdata['user'])) {
252 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
253 return DBA::exists('contact', $condition);
257 * Tests if the given contact url is a follower
259 * @param string $url Contact URL
260 * @param int $uid User ID
262 * @return boolean is the contact id a follower?
263 * @throws HTTPException\InternalServerErrorException
264 * @throws \ImagickException
266 public static function isFollowerByURL($url, $uid)
268 $cid = self::getIdForURL($url, $uid, true);
274 return self::isFollower($cid, $uid);
278 * Tests if the given user follow the given contact
280 * @param int $cid Either public contact id or user's contact id
281 * @param int $uid User ID
283 * @return boolean is the contact url being followed?
284 * @throws HTTPException\InternalServerErrorException
285 * @throws \ImagickException
287 public static function isSharing($cid, $uid)
289 if (self::isBlockedByUser($cid, $uid)) {
293 $cdata = self::getPublicAndUserContacID($cid, $uid);
294 if (empty($cdata['user'])) {
298 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
299 return DBA::exists('contact', $condition);
303 * Tests if the given user follow the given contact url
305 * @param string $url Contact URL
306 * @param int $uid User ID
308 * @return boolean is the contact url being followed?
309 * @throws HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function isSharingByURL($url, $uid)
314 $cid = self::getIdForURL($url, $uid, true);
320 return self::isSharing($cid, $uid);
324 * Get the basepath for a given contact link
326 * @param string $url The contact link
327 * @param boolean $dont_update Don't update the contact
329 * @return string basepath
330 * @throws HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 public static function getBasepath($url, $dont_update = false)
335 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
336 if (!DBA::isResult($contact)) {
340 if (!empty($contact['baseurl'])) {
341 return $contact['baseurl'];
342 } elseif ($dont_update) {
346 // Update the existing contact
347 self::updateFromProbe($contact['id'], '', true);
349 // And fetch the result
350 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
351 if (empty($contact['baseurl'])) {
352 Logger::info('No baseurl for contact', ['url' => $url]);
356 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
357 return $contact['baseurl'];
361 * Check if the given contact url is on the same server
363 * @param string $url The contact link
365 * @return boolean Is it the same server?
367 public static function isLocal($url)
369 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
373 * Check if the given contact ID is on the same server
375 * @param string $url The contact link
377 * @return boolean Is it the same server?
379 public static function isLocalById(int $cid)
381 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
382 if (!DBA::isResult($contact)) {
386 if (empty($contact['baseurl'])) {
387 $baseurl = self::getBasepath($contact['url'], true);
389 $baseurl = $contact['baseurl'];
392 return Strings::compareLink($baseurl, DI::baseUrl());
396 * Returns the public contact id of the given user id
398 * @param integer $uid User ID
400 * @return integer|boolean Public contact id for given user id
403 public static function getPublicIdByUserId($uid)
405 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
406 if (!DBA::isResult($self)) {
409 return self::getIdForURL($self['url'], 0, true);
413 * Returns the contact id for the user and the public contact id for a given contact id
415 * @param int $cid Either public contact id or user's contact id
416 * @param int $uid User ID
418 * @return array with public and user's contact id
419 * @throws HTTPException\InternalServerErrorException
420 * @throws \ImagickException
422 public static function getPublicAndUserContacID($cid, $uid)
424 if (empty($uid) || empty($cid)) {
428 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
429 if (!DBA::isResult($contact)) {
433 // We quit when the user id don't match the user id of the provided contact
434 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
438 if ($contact['uid'] != 0) {
439 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
443 $ucid = $contact['id'];
445 $pcid = $contact['id'];
446 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
449 return ['public' => $pcid, 'user' => $ucid];
453 * Returns contact details for a given contact id in combination with a user id
455 * @param int $cid A contact ID
456 * @param int $uid The User ID
457 * @param array $fields The selected fields for the contact
459 * @return array The contact details
463 public static function getContactForUser($cid, $uid, array $fields = [])
465 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
467 if (!DBA::isResult($contact)) {
475 * Block contact id for user id
477 * @param int $cid Either public contact id or user's contact id
478 * @param int $uid User ID
479 * @param boolean $blocked Is the contact blocked or unblocked?
482 public static function setBlockedForUser($cid, $uid, $blocked)
484 $cdata = self::getPublicAndUserContacID($cid, $uid);
489 if ($cdata['user'] != 0) {
490 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
493 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
497 * Returns "block" state for contact id and user id
499 * @param int $cid Either public contact id or user's contact id
500 * @param int $uid User ID
502 * @return boolean is the contact id blocked for the given user?
505 public static function isBlockedByUser($cid, $uid)
507 $cdata = self::getPublicAndUserContacID($cid, $uid);
512 $public_blocked = false;
514 if (!empty($cdata['public'])) {
515 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
516 if (DBA::isResult($public_contact)) {
517 $public_blocked = $public_contact['blocked'];
521 $user_blocked = $public_blocked;
523 if (!empty($cdata['user'])) {
524 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
525 if (DBA::isResult($user_contact)) {
526 $user_blocked = $user_contact['blocked'];
530 if ($user_blocked != $public_blocked) {
531 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
534 return $user_blocked;
538 * Ignore contact id for user id
540 * @param int $cid Either public contact id or user's contact id
541 * @param int $uid User ID
542 * @param boolean $ignored Is the contact ignored or unignored?
545 public static function setIgnoredForUser($cid, $uid, $ignored)
547 $cdata = self::getPublicAndUserContacID($cid, $uid);
552 if ($cdata['user'] != 0) {
553 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
556 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
560 * Returns "ignore" state for contact id and user id
562 * @param int $cid Either public contact id or user's contact id
563 * @param int $uid User ID
565 * @return boolean is the contact id ignored for the given user?
568 public static function isIgnoredByUser($cid, $uid)
570 $cdata = self::getPublicAndUserContacID($cid, $uid);
575 $public_ignored = false;
577 if (!empty($cdata['public'])) {
578 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
579 if (DBA::isResult($public_contact)) {
580 $public_ignored = $public_contact['ignored'];
584 $user_ignored = $public_ignored;
586 if (!empty($cdata['user'])) {
587 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
588 if (DBA::isResult($user_contact)) {
589 $user_ignored = $user_contact['readonly'];
593 if ($user_ignored != $public_ignored) {
594 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
597 return $user_ignored;
601 * Set "collapsed" for contact id and user id
603 * @param int $cid Either public contact id or user's contact id
604 * @param int $uid User ID
605 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
608 public static function setCollapsedForUser($cid, $uid, $collapsed)
610 $cdata = self::getPublicAndUserContacID($cid, $uid);
615 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
619 * Returns "collapsed" state for contact id and user id
621 * @param int $cid Either public contact id or user's contact id
622 * @param int $uid User ID
624 * @return boolean is the contact id blocked for the given user?
625 * @throws HTTPException\InternalServerErrorException
626 * @throws \ImagickException
628 public static function isCollapsedByUser($cid, $uid)
630 $cdata = self::getPublicAndUserContacID($cid, $uid);
637 if (!empty($cdata['public'])) {
638 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
639 if (DBA::isResult($public_contact)) {
640 $collapsed = $public_contact['collapsed'];
648 * Returns a list of contacts belonging in a group
654 public static function getByGroupId($gid)
659 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
661 INNER JOIN `group_member`
662 ON `contact`.`id` = `group_member`.`contact-id`
664 AND `contact`.`uid` = ?
665 AND NOT `contact`.`self`
666 AND NOT `contact`.`deleted`
667 AND NOT `contact`.`blocked`
668 AND NOT `contact`.`pending`
669 ORDER BY `contact`.`name` ASC',
674 if (DBA::isResult($stmt)) {
675 $return = DBA::toArray($stmt);
683 * Creates the self-contact for the provided user id
686 * @return bool Operation success
687 * @throws HTTPException\InternalServerErrorException
689 public static function createSelfFromUserId($uid)
691 // Only create the entry if it doesn't exist yet
692 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
696 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
697 if (!DBA::isResult($user)) {
701 $return = DBA::insert('contact', [
702 'uid' => $user['uid'],
703 'created' => DateTimeFormat::utcNow(),
705 'name' => $user['username'],
706 'nick' => $user['nickname'],
707 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
708 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
709 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
712 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
713 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
714 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
715 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
716 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
717 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
718 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
719 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
720 'name-date' => DateTimeFormat::utcNow(),
721 'uri-date' => DateTimeFormat::utcNow(),
722 'avatar-date' => DateTimeFormat::utcNow(),
730 * Updates the self-contact for the provided user id
733 * @param boolean $update_avatar Force the avatar update
734 * @throws HTTPException\InternalServerErrorException
736 public static function updateSelfFromUserID($uid, $update_avatar = false)
738 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
739 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
740 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
741 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
742 if (!DBA::isResult($self)) {
746 $fields = ['nickname', 'page-flags', 'account-type'];
747 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
748 if (!DBA::isResult($user)) {
752 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
753 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
754 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
755 if (!DBA::isResult($profile)) {
759 $file_suffix = 'jpg';
761 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
762 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
763 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
764 'contact-type' => $user['account-type'],
765 'xmpp' => $profile['xmpp']];
767 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
768 if (DBA::isResult($avatar)) {
769 if ($update_avatar) {
770 $fields['avatar-date'] = DateTimeFormat::utcNow();
773 // Creating the path to the avatar, beginning with the file suffix
774 $types = Images::supportedTypes();
775 if (isset($types[$avatar['type']])) {
776 $file_suffix = $types[$avatar['type']];
779 // We are adding a timestamp value so that other systems won't use cached content
780 $timestamp = strtotime($fields['avatar-date']);
782 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
783 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
785 $fields['photo'] = $prefix . '4' . $suffix;
786 $fields['thumb'] = $prefix . '5' . $suffix;
787 $fields['micro'] = $prefix . '6' . $suffix;
789 // We hadn't found a photo entry, so we use the default avatar
790 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
791 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
792 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
795 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
796 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
797 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
798 $fields['unsearchable'] = !$profile['net-publish'];
800 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
801 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
802 $fields['nurl'] = Strings::normaliseLink($fields['url']);
803 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
804 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
805 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
806 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
807 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
808 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
812 foreach ($fields as $field => $content) {
813 if ($self[$field] != $content) {
819 if ($fields['name'] != $self['name']) {
820 $fields['name-date'] = DateTimeFormat::utcNow();
822 $fields['updated'] = DateTimeFormat::utcNow();
823 DBA::update('contact', $fields, ['id' => $self['id']]);
825 // Update the public contact as well
826 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
828 // Update the profile
829 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
830 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
831 DBA::update('profile', $fields, ['uid' => $uid]);
836 * Marks a contact for removal
838 * @param int $id contact id
840 * @throws HTTPException\InternalServerErrorException
842 public static function remove($id)
844 // We want just to make sure that we don't delete our "self" contact
845 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
846 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
850 // Archive the contact
851 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
853 // Delete it in the background
854 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
858 * Sends an unfriend message. Does not remove the contact
860 * @param array $user User unfriending
861 * @param array $contact Contact unfriended
862 * @param boolean $dissolve Remove the contact on the remote side
864 * @throws HTTPException\InternalServerErrorException
865 * @throws \ImagickException
867 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
869 if (empty($contact['network'])) {
873 $protocol = $contact['network'];
874 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
875 $protocol = Protocol::ACTIVITYPUB;
878 if (($protocol == Protocol::DFRN) && $dissolve) {
879 DFRN::deliver($user, $contact, 'placeholder', true);
880 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
881 // create an unfollow slap
883 $item['verb'] = Activity::O_UNFOLLOW;
884 $item['gravity'] = GRAVITY_ACTIVITY;
885 $item['follow'] = $contact["url"];
890 $item['attach'] = '';
891 $slap = OStatus::salmon($item, $user);
893 if (!empty($contact['notify'])) {
894 Salmon::slapper($user, $contact['notify'], $slap);
896 } elseif ($protocol == Protocol::DIASPORA) {
897 Diaspora::sendUnshare($user, $contact);
898 } elseif ($protocol == Protocol::ACTIVITYPUB) {
899 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
902 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
908 * Marks a contact for archival after a communication issue delay
910 * Contact has refused to recognise us as a friend. We will start a countdown.
911 * If they still don't recognise us in 32 days, the relationship is over,
912 * and we won't waste any more time trying to communicate with them.
913 * This provides for the possibility that their database is temporarily messed
914 * up or some other transient event and that there's a possibility we could recover from it.
916 * @param array $contact contact to mark for archival
918 * @throws HTTPException\InternalServerErrorException
920 public static function markForArchival(array $contact)
922 if (!isset($contact['url']) && !empty($contact['id'])) {
923 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
924 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
925 if (!DBA::isResult($contact)) {
928 } elseif (!isset($contact['url'])) {
929 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
932 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
934 // Contact already archived or "self" contact? => nothing to do
935 if ($contact['archive'] || $contact['self']) {
939 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
940 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
941 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
944 * We really should send a notification to the owner after 2-3 weeks
945 * so they won't be surprised when the contact vanishes and can take
946 * remedial action if this was a serious mistake or glitch
949 /// @todo Check for contact vitality via probing
950 $archival_days = DI::config()->get('system', 'archival_days', 32);
952 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
953 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
954 /* Relationship is really truly dead. archive them rather than
955 * delete, though if the owner tries to unarchive them we'll start
956 * the whole process over again.
958 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
959 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
960 GContact::updateFromPublicContactURL($contact['url']);
966 * Cancels the archival countdown
968 * @see Contact::markForArchival()
970 * @param array $contact contact to be unmarked for archival
974 public static function unmarkForArchival(array $contact)
976 // Always unarchive the relay contact entry
977 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
978 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
979 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
980 DBA::update('contact', $fields, $condition);
983 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
984 $exists = DBA::exists('contact', $condition);
986 // We don't need to update, we never marked this contact for archival
991 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
993 if (!isset($contact['url']) && !empty($contact['id'])) {
994 $fields = ['id', 'url', 'batch'];
995 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
996 if (!DBA::isResult($contact)) {
1001 // It's a miracle. Our dead contact has inexplicably come back to life.
1002 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
1003 DBA::update('contact', $fields, ['id' => $contact['id']]);
1004 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1005 GContact::updateFromPublicContactURL($contact['url']);
1009 * Get contact data for a given profile link
1011 * The function looks at several places (contact table and gcontact table) for the contact
1012 * It caches its result for the same script execution to prevent duplicate calls
1014 * @param string $url The profile link
1015 * @param int $uid User id
1016 * @param array $default If not data was found take this data as default value
1018 * @return array Contact data
1019 * @throws HTTPException\InternalServerErrorException
1021 public static function getDetailsByURL($url, $uid = -1, array $default = [])
1030 $uid = local_user();
1033 if (isset($cache[$url][$uid])) {
1034 return $cache[$url][$uid];
1037 $ssl_url = str_replace('http://', 'https://', $url);
1039 $nurl = Strings::normaliseLink($url);
1041 // Fetch contact data from the contact table for the given user
1042 $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`,
1043 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1044 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
1045 $r = DBA::toArray($s);
1047 // Fetch contact data from the contact table for the given user, checking with the alias
1048 if (!DBA::isResult($r)) {
1049 $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`,
1050 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1051 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
1052 $r = DBA::toArray($s);
1055 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1056 if (!DBA::isResult($r)) {
1057 $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`,
1058 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1059 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1060 $r = DBA::toArray($s);
1063 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1064 if (!DBA::isResult($r)) {
1065 $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`,
1066 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1067 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1068 $r = DBA::toArray($s);
1071 // Fetch the data from the gcontact table
1072 if (!DBA::isResult($r)) {
1073 $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`,
1074 `keywords`, `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`
1075 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1076 $r = DBA::toArray($s);
1079 if (DBA::isResult($r)) {
1080 // If there is more than one entry we filter out the connector networks
1081 if (count($r) > 1) {
1082 foreach ($r as $id => $result) {
1083 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1089 $profile = array_shift($r);
1092 if (!empty($profile)) {
1093 $authoritativeResult = true;
1094 // "bd" always contains the upcoming birthday of a contact.
1095 // "birthday" might contain the birthday including the year of birth.
1096 if ($profile["birthday"] > DBA::NULL_DATE) {
1097 $bd_timestamp = strtotime($profile["birthday"]);
1098 $month = date("m", $bd_timestamp);
1099 $day = date("d", $bd_timestamp);
1101 $current_timestamp = time();
1102 $current_year = date("Y", $current_timestamp);
1103 $current_month = date("m", $current_timestamp);
1104 $current_day = date("d", $current_timestamp);
1106 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1107 $current = $current_year . "-" . $current_month . "-" . $current_day;
1109 if ($profile["bd"] < $current) {
1110 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1113 $profile["bd"] = DBA::NULL_DATE;
1116 $authoritativeResult = false;
1117 $profile = $default;
1120 if (empty($profile["photo"]) && isset($default["photo"])) {
1121 $profile["photo"] = $default["photo"];
1124 if (empty($profile["name"]) && isset($default["name"])) {
1125 $profile["name"] = $default["name"];
1128 if (empty($profile["network"]) && isset($default["network"])) {
1129 $profile["network"] = $default["network"];
1132 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1133 $profile["thumb"] = $profile["photo"];
1136 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1137 $profile["micro"] = $profile["thumb"];
1140 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1141 && in_array($profile["network"], Protocol::FEDERATED)
1143 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1146 // Show contact details of Diaspora contacts only if connected
1147 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1148 $profile["location"] = "";
1149 $profile["about"] = "";
1150 $profile["birthday"] = DBA::NULL_DATE;
1153 // Only cache the result if it came from the DB since this method is used in widely different contexts
1154 // @see display_fetch_author for an example of $default parameter diverging from the DB result
1155 if ($authoritativeResult) {
1156 $cache[$url][$uid] = $profile;
1163 * Get contact data for a given address
1165 * The function looks at several places (contact table and gcontact table) for the contact
1167 * @param string $addr The profile link
1168 * @param int $uid User id
1170 * @return array Contact data
1171 * @throws HTTPException\InternalServerErrorException
1172 * @throws \ImagickException
1174 public static function getDetailsByAddr($addr, $uid = -1)
1181 $uid = local_user();
1184 // Fetch contact data from the contact table for the given user
1185 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1186 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`,`baseurl`
1187 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1191 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1192 if (!DBA::isResult($r)) {
1193 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1194 `keywords`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`, `baseurl`
1195 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1200 // Fetch the data from the gcontact table
1201 if (!DBA::isResult($r)) {
1202 $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`,
1203 `keywords`, `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`, `server_url` AS `baseurl`
1204 FROM `gcontact` WHERE `addr` = '%s'",
1209 if (!DBA::isResult($r)) {
1210 $data = Probe::uri($addr);
1212 $profile = self::getDetailsByURL($data['url'], $uid, $data);
1221 * Returns the data array for the photo menu of a given contact
1223 * @param array $contact contact
1224 * @param int $uid optional, default 0
1226 * @throws HTTPException\InternalServerErrorException
1227 * @throws \ImagickException
1229 public static function photoMenu(array $contact, $uid = 0)
1234 $contact_drop_link = '';
1238 $uid = local_user();
1241 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1243 $profile_link = self::magicLink($contact['url']);
1244 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1249 // Look for our own contact if the uid doesn't match and isn't public
1250 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1251 if (DBA::isResult($contact_own)) {
1252 return self::photoMenu($contact_own, $uid);
1257 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1259 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1261 $profile_link = $contact['url'];
1264 if ($profile_link === 'mailbox') {
1269 $status_link = $profile_link . '/status';
1270 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1271 $profile_link = $profile_link . '/profile';
1274 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1275 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1278 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1279 $poke_link = 'contact/' . $contact['id'] . '/poke';
1282 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1284 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1286 if (!$contact['self']) {
1287 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1291 $unfollow_link = '';
1292 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1293 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1294 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1295 } elseif(!$contact['pending']) {
1296 $follow_link = 'follow?url=' . urlencode($contact['url']);
1300 if (!empty($follow_link) || !empty($unfollow_link)) {
1301 $contact_drop_link = '';
1306 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1308 if (empty($contact['uid'])) {
1310 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1311 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1312 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1313 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1314 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1318 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1319 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1320 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1321 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1322 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1323 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1324 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1325 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1326 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1327 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1330 if (!empty($contact['pending'])) {
1331 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1332 if (DBA::isResult($intro)) {
1333 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1338 $args = ['contact' => $contact, 'menu' => &$menu];
1340 Hook::callAll('contact_photo_menu', $args);
1342 $menucondensed = [];
1344 foreach ($menu as $menuname => $menuitem) {
1345 if ($menuitem[1] != '') {
1346 $menucondensed[$menuname] = $menuitem;
1350 return $menucondensed;
1354 * Returns ungrouped contact count or list for user
1356 * Returns either the total number of ungrouped contacts for the given user
1357 * id or a paginated list of ungrouped contacts.
1359 * @param int $uid uid
1361 * @throws \Exception
1363 public static function getUngroupedList($uid)
1373 SELECT DISTINCT(`contact-id`)
1375 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1376 WHERE `group`.`uid` = %d
1377 )", intval($uid), intval($uid));
1381 * Have a look at all contact tables for a given profile url.
1382 * This function works as a replacement for probing the contact.
1384 * @param string $url Contact URL
1385 * @param integer $cid Contact ID
1387 * @return array Contact array in the "probe" structure
1389 private static function getProbeDataFromDatabase($url, $cid = null)
1391 // The link could be provided as http although we stored it as https
1392 $ssl_url = str_replace('http://', 'https://', $url);
1394 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1395 'photo', 'keywords', 'location', 'about', 'network',
1396 'priority', 'batch', 'request', 'confirm', 'poco'];
1399 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1400 if (DBA::isResult($data)) {
1405 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1407 if (!DBA::isResult($data)) {
1408 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1409 $data = DBA::selectFirst('contact', $fields, $condition);
1412 if (DBA::isResult($data)) {
1413 // For security reasons we don't fetch key data from our users
1414 $data["pubkey"] = '';
1418 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1419 'photo', 'keywords', 'location', 'about', 'network'];
1420 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1422 if (!DBA::isResult($data)) {
1423 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1424 $data = DBA::selectFirst('contact', $fields, $condition);
1427 if (DBA::isResult($data)) {
1428 $data["pubkey"] = '';
1430 $data["priority"] = 0;
1431 $data["batch"] = '';
1432 $data["request"] = '';
1433 $data["confirm"] = '';
1438 $data = ActivityPub::probeProfile($url, false);
1439 if (!empty($data)) {
1443 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1444 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1445 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1447 if (!DBA::isResult($data)) {
1448 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1449 $data = DBA::selectFirst('contact', $fields, $condition);
1452 if (DBA::isResult($data)) {
1453 $data["pubkey"] = '';
1454 $data["keywords"] = '';
1455 $data["location"] = '';
1456 $data["about"] = '';
1465 * Fetch the contact id for a given URL and user
1467 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1468 * `addr` or `alias`.
1470 * If there's no record and we aren't looking for a public contact, we quit.
1471 * If there's one, we check that it isn't time to update the picture else we
1472 * directly return the found contact id.
1474 * Second, we probe the provided $url whether it's http://server.tld/profile or
1475 * nick@server.tld. We quit if we can't get any info back.
1477 * Third, we create the contact record if it doesn't exist
1479 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1480 * if there's any updates
1482 * @param string $url Contact URL
1483 * @param integer $uid The user id for the contact (0 = public contact)
1484 * @param boolean $no_update Don't update the contact
1485 * @param array $default Default value for creating the contact when every else fails
1486 * @param boolean $in_loop Internally used variable to prevent an endless loop
1488 * @return integer Contact ID
1489 * @throws HTTPException\InternalServerErrorException
1490 * @throws \ImagickException
1492 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1494 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1502 $contact = self::getByURL($url, $uid, ['id', 'avatar', 'updated', 'network'], false);
1504 if (!empty($contact)) {
1505 $contact_id = $contact["id"];
1506 $update_contact = false;
1508 // Update the contact every 7 days (Don't update mail or feed contacts)
1509 if (in_array($contact['network'], Protocol::FEDERATED)) {
1510 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1512 // We force the update if the avatar is empty
1513 if (empty($contact['avatar'])) {
1514 $update_contact = true;
1516 } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1517 // Update public mail accounts via their user's accounts
1518 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1519 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1520 if (!DBA::isResult($mailcontact)) {
1521 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1524 if (DBA::isResult($mailcontact)) {
1525 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1529 // Update the contact in the background if needed but it is called by the frontend
1530 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1531 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1534 if (!$update_contact || $no_update) {
1537 } elseif ($uid != 0) {
1538 // Non-existing user-specific contact, exiting
1542 if ($no_update && empty($default)) {
1543 // When we don't want to update, we look if we know this contact in any way
1544 $data = self::getProbeDataFromDatabase($url, $contact_id);
1545 $background_update = true;
1546 } elseif ($no_update && !empty($default['network'])) {
1547 // If there are default values, take these
1549 $background_update = false;
1552 $background_update = false;
1556 $data = Probe::uri($url, "", $uid);
1559 // Take the default values when probing failed
1560 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1561 $data = array_merge($data, $default);
1564 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1565 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1569 if (!empty($data['baseurl'])) {
1570 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1573 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1574 $data['gsid'] = GServer::getID($data['baseurl']);
1577 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1578 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1584 'created' => DateTimeFormat::utcNow(),
1585 'url' => $data['url'],
1586 'nurl' => Strings::normaliseLink($data['url']),
1587 'addr' => $data['addr'] ?? '',
1588 'alias' => $data['alias'] ?? '',
1589 'notify' => $data['notify'] ?? '',
1590 'poll' => $data['poll'] ?? '',
1591 'name' => $data['name'] ?? '',
1592 'nick' => $data['nick'] ?? '',
1593 'photo' => $data['photo'] ?? '',
1594 'keywords' => $data['keywords'] ?? '',
1595 'location' => $data['location'] ?? '',
1596 'about' => $data['about'] ?? '',
1597 'network' => $data['network'],
1598 'pubkey' => $data['pubkey'] ?? '',
1599 'rel' => self::SHARING,
1600 'priority' => $data['priority'] ?? 0,
1601 'batch' => $data['batch'] ?? '',
1602 'request' => $data['request'] ?? '',
1603 'confirm' => $data['confirm'] ?? '',
1604 'poco' => $data['poco'] ?? '',
1605 'baseurl' => $data['baseurl'] ?? '',
1606 'gsid' => $data['gsid'] ?? null,
1607 'name-date' => DateTimeFormat::utcNow(),
1608 'uri-date' => DateTimeFormat::utcNow(),
1609 'avatar-date' => DateTimeFormat::utcNow(),
1615 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1617 // Before inserting we do check if the entry does exist now.
1618 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1619 if (!DBA::isResult($contact)) {
1620 Logger::info('Create new contact', $fields);
1622 self::insert($fields);
1624 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1625 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1626 if (!DBA::isResult($contact)) {
1627 Logger::info('Contact creation failed', $fields);
1632 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1635 $contact_id = $contact["id"];
1638 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1639 self::updateAvatar($data['photo'], $uid, $contact_id);
1642 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1643 if ($background_update) {
1644 // Update in the background when we fetched the data solely from the database
1645 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1647 // Else do a direct update
1648 self::updateFromProbe($contact_id, '', false);
1650 // Update the gcontact entry
1652 GContact::updateFromPublicContactID($contact_id);
1653 if (($data['network'] == Protocol::ACTIVITYPUB) && in_array(DI::config()->get('system', 'gcontact_discovery'), [GContact::DISCOVERY_DIRECT, GContact::DISCOVERY_RECURSIVE])) {
1654 GContact::discoverFollowers($data['url']);
1659 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1660 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1662 // This condition should always be true
1663 if (!DBA::isResult($contact)) {
1668 'url' => $data['url'],
1669 'nurl' => Strings::normaliseLink($data['url']),
1670 'updated' => DateTimeFormat::utcNow()
1673 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1675 foreach ($fields as $field) {
1676 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1679 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1680 $updated['uri-date'] = DateTimeFormat::utcNow();
1683 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1684 $updated['name-date'] = DateTimeFormat::utcNow();
1687 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1694 * Checks if the contact is archived
1696 * @param int $cid contact id
1698 * @return boolean Is the contact archived?
1699 * @throws HTTPException\InternalServerErrorException
1701 public static function isArchived(int $cid)
1707 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1708 if (!DBA::isResult($contact)) {
1712 if ($contact['archive']) {
1716 // Check status of ActivityPub endpoints
1717 $apcontact = APContact::getByURL($contact['url'], false);
1718 if (!empty($apcontact)) {
1719 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1723 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1728 // Check status of Diaspora endpoints
1729 if (!empty($contact['batch'])) {
1730 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1731 return DBA::exists('contact', $condition);
1738 * Checks if the contact is blocked
1740 * @param int $cid contact id
1742 * @return boolean Is the contact blocked?
1743 * @throws HTTPException\InternalServerErrorException
1745 public static function isBlocked($cid)
1751 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1752 if (!DBA::isResult($blocked)) {
1756 if (Network::isUrlBlocked($blocked['url'])) {
1760 return (bool) $blocked['blocked'];
1764 * Checks if the contact is hidden
1766 * @param int $cid contact id
1768 * @return boolean Is the contact hidden?
1769 * @throws \Exception
1771 public static function isHidden($cid)
1777 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1778 if (!DBA::isResult($hidden)) {
1781 return (bool) $hidden['hidden'];
1785 * Returns posts from a given contact url
1787 * @param string $contact_url Contact URL
1788 * @param bool $thread_mode
1789 * @param int $update
1790 * @return string posts in HTML
1791 * @throws \Exception
1793 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1795 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1799 * Returns posts from a given contact id
1801 * @param integer $cid
1802 * @param bool $thread_mode
1803 * @param integer $update
1804 * @return string posts in HTML
1805 * @throws \Exception
1807 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1811 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1812 if (!DBA::isResult($contact)) {
1816 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1817 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1819 $sql = "`item`.`uid` = ?";
1822 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1825 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1826 $cid, GRAVITY_PARENT, local_user()];
1828 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1829 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1832 if (DI::mode()->isMobile()) {
1833 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1834 DI::config()->get('system', 'itemspage_network_mobile'));
1836 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1837 DI::config()->get('system', 'itemspage_network'));
1840 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1842 $params = ['order' => ['received' => true],
1843 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1846 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1848 $items = Item::inArray($r);
1850 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1852 $r = Item::selectForUser(local_user(), [], $condition, $params);
1854 $items = Item::inArray($r);
1856 $o = conversation($a, $items, 'contact-posts', false);
1860 $o .= $pager->renderMinimal(count($items));
1867 * Returns the account type name
1869 * The function can be called with either the user or the contact array
1871 * @param array $contact contact or user array
1874 public static function getAccountType(array $contact)
1876 // There are several fields that indicate that the contact or user is a forum
1877 // "page-flags" is a field in the user table,
1878 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1879 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1880 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1881 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1882 || (isset($contact['forum']) && intval($contact['forum']))
1883 || (isset($contact['prv']) && intval($contact['prv']))
1884 || (isset($contact['community']) && intval($contact['community']))
1886 $type = self::TYPE_COMMUNITY;
1888 $type = self::TYPE_PERSON;
1891 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1892 if (isset($contact["contact-type"])) {
1893 $type = $contact["contact-type"];
1896 if (isset($contact["account-type"])) {
1897 $type = $contact["account-type"];
1901 case self::TYPE_ORGANISATION:
1902 $account_type = DI::l10n()->t("Organisation");
1905 case self::TYPE_NEWS:
1906 $account_type = DI::l10n()->t('News');
1909 case self::TYPE_COMMUNITY:
1910 $account_type = DI::l10n()->t("Forum");
1918 return $account_type;
1926 * @throws \Exception
1928 public static function block($cid, $reason = null)
1930 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1936 * Unblocks a contact
1940 * @throws \Exception
1942 public static function unblock($cid)
1944 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1950 * Updates the avatar links in a contact only if needed
1952 * @param string $avatar Link to avatar picture
1953 * @param int $uid User id of contact owner
1954 * @param int $cid Contact id
1955 * @param bool $force force picture update
1958 * @throws HTTPException\InternalServerErrorException
1959 * @throws HTTPException\NotFoundException
1960 * @throws \ImagickException
1962 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1964 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1965 if (!DBA::isResult($contact)) {
1970 $contact['photo'] ?? '',
1971 $contact['thumb'] ?? '',
1972 $contact['micro'] ?? '',
1975 foreach ($data as $image_uri) {
1976 $image_rid = Photo::ridFromURI($image_uri);
1977 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1978 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1983 if (($contact["avatar"] != $avatar) || $force) {
1984 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1987 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1988 DBA::update('contact', $fields, ['id' => $cid]);
1990 // Update the public contact (contact id = 0)
1992 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1993 if (DBA::isResult($pcontact)) {
1994 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
2002 * Helper function for "updateFromProbe". Updates personal and public contact
2004 * @param integer $id contact id
2005 * @param integer $uid user id
2006 * @param string $url The profile URL of the contact
2007 * @param array $fields The fields that are updated
2009 * @throws \Exception
2011 private static function updateContact($id, $uid, $url, array $fields)
2013 if (!DBA::update('contact', $fields, ['id' => $id])) {
2014 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2018 // Search for duplicated contacts and get rid of them
2019 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
2023 // Update the corresponding gcontact entry
2024 GContact::updateFromPublicContactID($id);
2026 // Archive or unarchive the contact. We only need to do this for the public contact.
2027 // The archive/unarchive function will update the personal contacts by themselves.
2028 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2029 if (!DBA::isResult($contact)) {
2030 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2034 if (!empty($fields['success_update'])) {
2035 self::unmarkForArchival($contact);
2036 } elseif (!empty($fields['failure_update'])) {
2037 self::markForArchival($contact);
2040 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2042 // These contacts are sharing with us, we don't poll them.
2043 // This means that we don't set the update fields in "OnePoll.php".
2044 $condition['rel'] = self::SHARING;
2045 DBA::update('contact', $fields, $condition);
2047 unset($fields['last-update']);
2048 unset($fields['success_update']);
2049 unset($fields['failure_update']);
2051 if (empty($fields)) {
2055 // We are polling these contacts, so we mustn't set the update fields here.
2056 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2057 DBA::update('contact', $fields, $condition);
2061 * Remove duplicated contacts
2063 * @param string $nurl Normalised contact url
2064 * @param integer $uid User id
2066 * @throws \Exception
2068 public static function removeDuplicates(string $nurl, int $uid)
2070 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2071 $count = DBA::count('contact', $condition);
2076 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2077 if (!DBA::isResult($first_contact)) {
2078 // Shouldn't happen - so we handle it
2082 $first = $first_contact['id'];
2083 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2084 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2085 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2086 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2090 // Find all duplicates
2091 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2092 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2093 while ($duplicate = DBA::fetch($duplicates)) {
2094 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2098 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2100 DBA::close($duplicates);
2101 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2106 * @param integer $id contact id
2107 * @param string $network Optional network we are probing for
2108 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2110 * @throws HTTPException\InternalServerErrorException
2111 * @throws \ImagickException
2113 public static function updateFromProbe($id, $network = '', $force = false)
2116 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2117 This will reliably kill your communication with old Friendica contacts.
2120 // These fields aren't updated by this routine:
2121 // 'xmpp', 'sensitive'
2123 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2124 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2125 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
2126 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2127 if (!DBA::isResult($contact)) {
2131 $uid = $contact['uid'];
2132 unset($contact['uid']);
2134 $pubkey = $contact['pubkey'];
2135 unset($contact['pubkey']);
2137 $contact['photo'] = $contact['avatar'];
2138 unset($contact['avatar']);
2140 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2142 $updated = DateTimeFormat::utcNow();
2144 // We must not try to update relay contacts via probe. They are no real contacts.
2145 // We check after the probing to be able to correct falsely detected contact types.
2146 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2147 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2148 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2149 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2153 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2154 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2155 if ($force && ($uid == 0)) {
2156 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2161 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2162 $ret['unsearchable'] = $ret['hide'];
2165 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2166 $ret['forum'] = false;
2167 $ret['prv'] = false;
2168 $ret['contact-type'] = $ret['account-type'];
2169 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2170 $apcontact = APContact::getByURL($ret['url'], false);
2171 if (isset($apcontact['manually-approve'])) {
2172 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2173 $ret['prv'] = (bool)!$ret['forum'];
2178 $new_pubkey = $ret['pubkey'];
2182 // make sure to not overwrite existing values with blank entries except some technical fields
2183 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2184 foreach ($ret as $key => $val) {
2185 if (!array_key_exists($key, $contact)) {
2187 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2188 $ret[$key] = $contact[$key];
2189 } elseif ($ret[$key] != $contact[$key]) {
2194 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2195 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2200 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2203 // Update the public contact
2205 self::updateFromProbeByURL($ret['url']);
2211 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2212 $ret['updated'] = $updated;
2214 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2215 if (empty($pubkey) && !empty($new_pubkey)) {
2216 $ret['pubkey'] = $new_pubkey;
2219 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2220 $ret['uri-date'] = DateTimeFormat::utcNow();
2223 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2224 $ret['name-date'] = $updated;
2227 if ($force && ($uid == 0)) {
2228 $ret['last-update'] = $updated;
2229 $ret['success_update'] = $updated;
2232 unset($ret['photo']);
2234 self::updateContact($id, $uid, $ret['url'], $ret);
2239 public static function updateFromProbeByURL($url, $force = false)
2241 $id = self::getIdForURL($url);
2247 self::updateFromProbe($id, '', $force);
2253 * Detects if a given contact array belongs to a legacy DFRN connection
2255 * @param array $contact
2258 public static function isLegacyDFRNContact($contact)
2260 // Newer Friendica contacts are connected via AP, then these fields aren't set
2261 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2265 * Detects the communication protocol for a given contact url.
2266 * This is used to detect Friendica contacts that we can communicate via AP.
2268 * @param string $url contact url
2269 * @param string $network Network of that contact
2270 * @return string with protocol
2272 public static function getProtocol($url, $network)
2274 if ($network != Protocol::DFRN) {
2278 $apcontact = APContact::getByURL($url);
2279 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2280 return Protocol::ACTIVITYPUB;
2287 * Takes a $uid and a url/handle and adds a new contact
2289 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2290 * dfrn_request page.
2292 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2295 * $return['success'] boolean true if successful
2296 * $return['message'] error text if success is false.
2298 * Takes a $uid and a url/handle and adds a new contact
2300 * @param array $user The user the contact should be created for
2301 * @param string $url The profile URL of the contact
2302 * @param bool $interactive
2303 * @param string $network
2305 * @throws HTTPException\InternalServerErrorException
2306 * @throws HTTPException\NotFoundException
2307 * @throws \ImagickException
2309 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2311 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2313 // remove ajax junk, e.g. Twitter
2314 $url = str_replace('/#!/', '/', $url);
2316 if (!Network::isUrlAllowed($url)) {
2317 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2321 if (Network::isUrlBlocked($url)) {
2322 $result['message'] = DI::l10n()->t('Blocked domain');
2327 $result['message'] = DI::l10n()->t('Connect URL missing.');
2331 $arr = ['url' => $url, 'contact' => []];
2333 Hook::callAll('follow', $arr);
2336 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2340 if (!empty($arr['contact']['name'])) {
2341 $ret = $arr['contact'];
2343 $ret = Probe::uri($url, $network, $user['uid'], false);
2346 if (($network != '') && ($ret['network'] != $network)) {
2347 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2351 // check if we already have a contact
2352 // the poll url is more reliable than the profile url, as we may have
2353 // indirect links or webfinger links
2355 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2356 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2357 if (!DBA::isResult($contact)) {
2358 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2359 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2362 $protocol = self::getProtocol($ret['url'], $ret['network']);
2364 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2366 if (strlen(DI::baseUrl()->getUrlPath())) {
2367 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2369 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2372 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2376 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2377 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2378 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2382 // This extra param just confuses things, remove it
2383 if ($protocol === Protocol::DIASPORA) {
2384 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2387 // do we have enough information?
2388 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2389 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2390 if (empty($ret['poll'])) {
2391 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2393 if (empty($ret['name'])) {
2394 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2396 if (empty($ret['url'])) {
2397 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2399 if (strpos($ret['url'], '@') !== false) {
2400 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2401 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2406 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2407 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2408 $ret['notify'] = '';
2411 if (!$ret['notify']) {
2412 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2415 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2417 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2419 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2422 if ($protocol == Protocol::ACTIVITYPUB) {
2423 $apcontact = APContact::getByURL($ret['url'], false);
2424 if (isset($apcontact['manually-approve'])) {
2425 $pending = (bool)$apcontact['manually-approve'];
2429 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2433 if (DBA::isResult($contact)) {
2435 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2437 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2438 DBA::update('contact', $fields, ['id' => $contact['id']]);
2440 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2442 // create contact record
2444 'uid' => $user['uid'],
2445 'created' => DateTimeFormat::utcNow(),
2446 'url' => $ret['url'],
2447 'nurl' => Strings::normaliseLink($ret['url']),
2448 'addr' => $ret['addr'],
2449 'alias' => $ret['alias'],
2450 'batch' => $ret['batch'],
2451 'notify' => $ret['notify'],
2452 'poll' => $ret['poll'],
2453 'poco' => $ret['poco'],
2454 'name' => $ret['name'],
2455 'nick' => $ret['nick'],
2456 'network' => $ret['network'],
2457 'baseurl' => $ret['baseurl'],
2458 'gsid' => $ret['gsid'] ?? null,
2459 'protocol' => $protocol,
2460 'pubkey' => $ret['pubkey'],
2461 'rel' => $new_relation,
2462 'priority'=> $ret['priority'],
2463 'writable'=> $writeable,
2464 'hidden' => $hidden,
2467 'pending' => $pending,
2472 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2473 if (!DBA::isResult($contact)) {
2474 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2478 $contact_id = $contact['id'];
2479 $result['cid'] = $contact_id;
2481 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2483 // Update the avatar
2484 self::updateAvatar($ret['photo'], $user['uid'], $contact_id);
2486 // pull feed and consume it, which should subscribe to the hub.
2488 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2490 $owner = User::getOwnerDataById($user['uid']);
2492 if (DBA::isResult($owner)) {
2493 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2494 // create a follow slap
2496 $item['verb'] = Activity::FOLLOW;
2497 $item['gravity'] = GRAVITY_ACTIVITY;
2498 $item['follow'] = $contact["url"];
2500 $item['title'] = '';
2502 $item['uri-id'] = 0;
2503 $item['attach'] = '';
2505 $slap = OStatus::salmon($item, $owner);
2507 if (!empty($contact['notify'])) {
2508 Salmon::slapper($owner, $contact['notify'], $slap);
2510 } elseif ($protocol == Protocol::DIASPORA) {
2511 $ret = Diaspora::sendShare($owner, $contact);
2512 Logger::log('share returns: ' . $ret);
2513 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2514 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2515 if (empty($activity_id)) {
2516 // This really should never happen
2520 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2521 Logger::log('Follow returns: ' . $ret);
2525 $result['success'] = true;
2530 * Updated contact's SSL policy
2532 * @param array $contact Contact array
2533 * @param string $new_policy New policy, valid: self,full
2535 * @return array Contact array with updated values
2536 * @throws \Exception
2538 public static function updateSslPolicy(array $contact, $new_policy)
2540 $ssl_changed = false;
2541 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2542 $ssl_changed = true;
2543 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2544 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2545 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2546 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2547 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2548 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2551 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2552 $ssl_changed = true;
2553 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2554 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2555 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2556 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2557 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2558 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2562 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2563 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2564 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2565 DBA::update('contact', $fields, ['id' => $contact['id']]);
2572 * @param array $importer Owner (local user) data
2573 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2574 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2575 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2576 * @param string $note Introduction additional message
2577 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2578 * @throws HTTPException\InternalServerErrorException
2579 * @throws \ImagickException
2581 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2583 // Should always be set
2584 if (empty($datarray['author-id'])) {
2588 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2589 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2590 if (!DBA::isResult($pub_contact)) {
2591 // Should never happen
2595 // Contact is blocked at node-level
2596 if (self::isBlocked($datarray['author-id'])) {
2600 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2601 $name = $pub_contact['name'];
2602 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2603 $nick = $pub_contact['nick'];
2604 $network = $pub_contact['network'];
2606 // Ensure that we don't create a new contact when there already is one
2607 $cid = self::getIdForURL($url, $importer['uid']);
2609 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2612 if (!empty($contact)) {
2613 if (!empty($contact['pending'])) {
2614 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2618 // Contact is blocked at user-level
2619 if (!empty($contact['id']) && !empty($importer['id']) &&
2620 self::isBlockedByUser($contact['id'], $importer['id'])) {
2624 // Make sure that the existing contact isn't archived
2625 self::unmarkForArchival($contact);
2627 if (($contact['rel'] == self::SHARING)
2628 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2629 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2630 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2633 // Ensure to always have the correct network type, independent from the connection request method
2634 self::updateFromProbe($contact['id'], '', true);
2638 // send email notification to owner?
2639 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2640 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2644 // create contact record
2645 DBA::insert('contact', [
2646 'uid' => $importer['uid'],
2647 'created' => DateTimeFormat::utcNow(),
2649 'nurl' => Strings::normaliseLink($url),
2653 'network' => $network,
2654 'rel' => self::FOLLOWER,
2661 $contact_id = DBA::lastInsertId();
2663 // Ensure to always have the correct network type, independent from the connection request method
2664 self::updateFromProbe($contact_id, '', true);
2666 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2668 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2670 /// @TODO Encapsulate this into a function/method
2671 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2672 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2673 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2674 // create notification
2675 $hash = Strings::getRandomHex();
2677 if (is_array($contact_record)) {
2678 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2679 'blocked' => false, 'knowyou' => false, 'note' => $note,
2680 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2683 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2685 if (($user['notify-flags'] & Type::INTRO) &&
2686 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2689 'type' => Type::INTRO,
2690 'notify_flags' => $user['notify-flags'],
2691 'language' => $user['language'],
2692 'to_name' => $user['username'],
2693 'to_email' => $user['email'],
2694 'uid' => $user['uid'],
2695 'link' => DI::baseUrl() . '/notifications/intros',
2696 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2697 'source_link' => $contact_record['url'],
2698 'source_photo' => $contact_record['photo'],
2699 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2703 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2704 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2705 self::createFromProbe($importer, $url, false, $network);
2708 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2709 $fields = ['pending' => false];
2710 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2711 $fields['rel'] = Contact::FRIEND;
2714 DBA::update('contact', $fields, $condition);
2723 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2725 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2726 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2728 Contact::remove($contact['id']);
2732 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2734 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2735 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2737 Contact::remove($contact['id']);
2742 * Create a birthday event.
2744 * Update the year and the birthday.
2746 public static function updateBirthdays()
2750 AND `bd` > "0001-01-01"
2751 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2752 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2753 AND NOT `contact`.`pending`
2754 AND NOT `contact`.`hidden`
2755 AND NOT `contact`.`blocked`
2756 AND NOT `contact`.`archive`
2757 AND NOT `contact`.`deleted`',
2762 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2764 while ($contact = DBA::fetch($contacts)) {
2765 Logger::log('update_contact_birthday: ' . $contact['bd']);
2767 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2769 if (Event::createBirthday($contact, $nextbd)) {
2773 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2774 ['id' => $contact['id']]
2778 DBA::close($contacts);
2782 * Remove the unavailable contact ids from the provided list
2784 * @param array $contact_ids Contact id list
2786 * @throws \Exception
2788 public static function pruneUnavailable(array $contact_ids)
2790 if (empty($contact_ids)) {
2794 $contacts = Contact::selectToArray(['id'], [
2795 'id' => $contact_ids,
2801 return array_column($contacts, 'id');
2805 * Returns a magic link to authenticate remote visitors
2807 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2809 * @param string $contact_url The address of the target contact profile
2810 * @param string $url An url that we will be redirected to after the authentication
2812 * @return string with "redir" link
2813 * @throws HTTPException\InternalServerErrorException
2814 * @throws \ImagickException
2816 public static function magicLink($contact_url, $url = '')
2818 if (!Session::isAuthenticated()) {
2819 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2822 $data = self::getProbeDataFromDatabase($contact_url);
2824 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2827 // Prevents endless loop in case only a non-public contact exists for the contact URL
2828 unset($data['uid']);
2830 return self::magicLinkByContact($data, $url ?: $contact_url);
2834 * Returns a magic link to authenticate remote visitors
2836 * @param integer $cid The contact id of the target contact profile
2837 * @param string $url An url that we will be redirected to after the authentication
2839 * @return string with "redir" link
2840 * @throws HTTPException\InternalServerErrorException
2841 * @throws \ImagickException
2843 public static function magicLinkbyId($cid, $url = '')
2845 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2847 return self::magicLinkByContact($contact, $url);
2851 * Returns a magic link to authenticate remote visitors
2853 * @param array $contact The contact array with "uid", "network" and "url"
2854 * @param string $url An url that we will be redirected to after the authentication
2856 * @return string with "redir" link
2857 * @throws HTTPException\InternalServerErrorException
2858 * @throws \ImagickException
2860 public static function magicLinkByContact($contact, $url = '')
2862 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2864 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2865 return $destination;
2868 // Only redirections to the same host do make sense
2869 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2873 if (!empty($contact['uid'])) {
2874 return self::magicLink($contact['url'], $url);
2877 if (empty($contact['id'])) {
2878 return $destination;
2881 $redirect = 'redir/' . $contact['id'];
2883 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2884 $redirect .= '?url=' . $url;
2891 * Remove a contact from all groups
2893 * @param integer $contact_id
2895 * @return boolean Success
2897 public static function removeFromGroups($contact_id)
2899 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2903 * Is the contact a forum?
2905 * @param integer $contactid ID of the contact
2907 * @return boolean "true" if it is a forum
2909 public static function isForum($contactid)
2911 $fields = ['forum', 'prv'];
2912 $condition = ['id' => $contactid];
2913 $contact = DBA::selectFirst('contact', $fields, $condition);
2914 if (!DBA::isResult($contact)) {
2919 return ($contact['forum'] || $contact['prv']);
2923 * Can the remote contact receive private messages?
2925 * @param array $contact
2928 public static function canReceivePrivateMessages(array $contact)
2930 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2931 $self = $contact['self'] ?? false;
2933 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;