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 boolean $update true = always update, false = never update, null = update when not found or outdated
198 * @param array $fields Field list
199 * @param integer $uid User ID of the contact
200 * @return array contact array
202 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
204 if ($update || is_null($update)) {
205 $cid = self::getIdForURL($url, $uid, $update);
209 return self::getById($cid, $fields);
212 // Add internal fields
214 foreach (['id', 'updated', 'network'] as $internal) {
215 if (!in_array($internal, $fields)) {
216 $fields[] = $internal;
217 $removal[] = $internal;
221 // We first try the nurl (http://server.tld/nick), most common case
222 $options = ['order' => ['id']];
223 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
225 // Then the addr (nick@server.tld)
226 if (!DBA::isResult($contact)) {
227 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
230 // Then the alias (which could be anything)
231 if (!DBA::isResult($contact)) {
232 // The link could be provided as http although we stored it as https
233 $ssl_url = str_replace('http://', 'https://', $url);
234 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
235 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
238 // Update the contact in the background if needed
239 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
240 in_array($contact['network'], Protocol::FEDERATED)) {
241 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
244 // Remove the internal fields
245 foreach ($removal as $internal) {
246 unset($contact[$internal]);
253 * Fetches a contact for a given user by a given url.
254 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
256 * @param string $url profile url
257 * @param integer $uid User ID of the contact
258 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
259 * @param array $fields Field list
260 * @return array contact array
262 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
265 $contact = self::getByURL($url, $update, $fields, $uid);
266 if (!empty($contact)) {
267 if (!empty($contact['id'])) {
268 $contact['cid'] = $contact['id'];
275 $contact = self::getByURL($url, $update, $fields);
276 if (!empty($contact['id'])) {
278 $contact['zid'] = $contact['id'];
284 * Tests if the given contact is a follower
286 * @param int $cid Either public contact id or user's contact id
287 * @param int $uid User ID
289 * @return boolean is the contact id a follower?
290 * @throws HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 public static function isFollower($cid, $uid)
295 if (self::isBlockedByUser($cid, $uid)) {
299 $cdata = self::getPublicAndUserContacID($cid, $uid);
300 if (empty($cdata['user'])) {
304 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
305 return DBA::exists('contact', $condition);
309 * Tests if the given contact url is a follower
311 * @param string $url Contact URL
312 * @param int $uid User ID
314 * @return boolean is the contact id a follower?
315 * @throws HTTPException\InternalServerErrorException
316 * @throws \ImagickException
318 public static function isFollowerByURL($url, $uid)
320 $cid = self::getIdForURL($url, $uid, false);
326 return self::isFollower($cid, $uid);
330 * Tests if the given user follow the given contact
332 * @param int $cid Either public contact id or user's contact id
333 * @param int $uid User ID
335 * @return boolean is the contact url being followed?
336 * @throws HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 public static function isSharing($cid, $uid)
341 if (self::isBlockedByUser($cid, $uid)) {
345 $cdata = self::getPublicAndUserContacID($cid, $uid);
346 if (empty($cdata['user'])) {
350 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
351 return DBA::exists('contact', $condition);
355 * Tests if the given user follow the given contact url
357 * @param string $url Contact URL
358 * @param int $uid User ID
360 * @return boolean is the contact url being followed?
361 * @throws HTTPException\InternalServerErrorException
362 * @throws \ImagickException
364 public static function isSharingByURL($url, $uid)
366 $cid = self::getIdForURL($url, $uid, false);
372 return self::isSharing($cid, $uid);
376 * Get the basepath for a given contact link
378 * @param string $url The contact link
379 * @param boolean $dont_update Don't update the contact
381 * @return string basepath
382 * @throws HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function getBasepath($url, $dont_update = false)
387 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
388 if (!DBA::isResult($contact)) {
392 if (!empty($contact['baseurl'])) {
393 return $contact['baseurl'];
394 } elseif ($dont_update) {
398 // Update the existing contact
399 self::updateFromProbe($contact['id'], '', true);
401 // And fetch the result
402 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
403 if (empty($contact['baseurl'])) {
404 Logger::info('No baseurl for contact', ['url' => $url]);
408 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
409 return $contact['baseurl'];
413 * Check if the given contact url is on the same server
415 * @param string $url The contact link
417 * @return boolean Is it the same server?
419 public static function isLocal($url)
421 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
425 * Check if the given contact ID is on the same server
427 * @param string $url The contact link
429 * @return boolean Is it the same server?
431 public static function isLocalById(int $cid)
433 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
434 if (!DBA::isResult($contact)) {
438 if (empty($contact['baseurl'])) {
439 $baseurl = self::getBasepath($contact['url'], true);
441 $baseurl = $contact['baseurl'];
444 return Strings::compareLink($baseurl, DI::baseUrl());
448 * Returns the public contact id of the given user id
450 * @param integer $uid User ID
452 * @return integer|boolean Public contact id for given user id
455 public static function getPublicIdByUserId($uid)
457 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
458 if (!DBA::isResult($self)) {
461 return self::getIdForURL($self['url'], 0, false);
465 * Returns the contact id for the user and the public contact id for a given contact id
467 * @param int $cid Either public contact id or user's contact id
468 * @param int $uid User ID
470 * @return array with public and user's contact id
471 * @throws HTTPException\InternalServerErrorException
472 * @throws \ImagickException
474 public static function getPublicAndUserContacID($cid, $uid)
476 if (empty($uid) || empty($cid)) {
480 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
481 if (!DBA::isResult($contact)) {
485 // We quit when the user id don't match the user id of the provided contact
486 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
490 if ($contact['uid'] != 0) {
491 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
495 $ucid = $contact['id'];
497 $pcid = $contact['id'];
498 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
501 return ['public' => $pcid, 'user' => $ucid];
505 * Returns contact details for a given contact id in combination with a user id
507 * @param int $cid A contact ID
508 * @param int $uid The User ID
509 * @param array $fields The selected fields for the contact
511 * @return array The contact details
515 public static function getContactForUser($cid, $uid, array $fields = [])
517 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
519 if (!DBA::isResult($contact)) {
527 * Block contact id for user id
529 * @param int $cid Either public contact id or user's contact id
530 * @param int $uid User ID
531 * @param boolean $blocked Is the contact blocked or unblocked?
534 public static function setBlockedForUser($cid, $uid, $blocked)
536 $cdata = self::getPublicAndUserContacID($cid, $uid);
541 if ($cdata['user'] != 0) {
542 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
545 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
549 * Returns "block" state for contact id and user id
551 * @param int $cid Either public contact id or user's contact id
552 * @param int $uid User ID
554 * @return boolean is the contact id blocked for the given user?
557 public static function isBlockedByUser($cid, $uid)
559 $cdata = self::getPublicAndUserContacID($cid, $uid);
564 $public_blocked = false;
566 if (!empty($cdata['public'])) {
567 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
568 if (DBA::isResult($public_contact)) {
569 $public_blocked = $public_contact['blocked'];
573 $user_blocked = $public_blocked;
575 if (!empty($cdata['user'])) {
576 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
577 if (DBA::isResult($user_contact)) {
578 $user_blocked = $user_contact['blocked'];
582 if ($user_blocked != $public_blocked) {
583 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
586 return $user_blocked;
590 * Ignore contact id for user id
592 * @param int $cid Either public contact id or user's contact id
593 * @param int $uid User ID
594 * @param boolean $ignored Is the contact ignored or unignored?
597 public static function setIgnoredForUser($cid, $uid, $ignored)
599 $cdata = self::getPublicAndUserContacID($cid, $uid);
604 if ($cdata['user'] != 0) {
605 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
608 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
612 * Returns "ignore" state for contact id and user id
614 * @param int $cid Either public contact id or user's contact id
615 * @param int $uid User ID
617 * @return boolean is the contact id ignored for the given user?
620 public static function isIgnoredByUser($cid, $uid)
622 $cdata = self::getPublicAndUserContacID($cid, $uid);
627 $public_ignored = false;
629 if (!empty($cdata['public'])) {
630 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
631 if (DBA::isResult($public_contact)) {
632 $public_ignored = $public_contact['ignored'];
636 $user_ignored = $public_ignored;
638 if (!empty($cdata['user'])) {
639 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
640 if (DBA::isResult($user_contact)) {
641 $user_ignored = $user_contact['readonly'];
645 if ($user_ignored != $public_ignored) {
646 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
649 return $user_ignored;
653 * Set "collapsed" for contact id and user id
655 * @param int $cid Either public contact id or user's contact id
656 * @param int $uid User ID
657 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
660 public static function setCollapsedForUser($cid, $uid, $collapsed)
662 $cdata = self::getPublicAndUserContacID($cid, $uid);
667 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
671 * Returns "collapsed" state for contact id and user id
673 * @param int $cid Either public contact id or user's contact id
674 * @param int $uid User ID
676 * @return boolean is the contact id blocked for the given user?
677 * @throws HTTPException\InternalServerErrorException
678 * @throws \ImagickException
680 public static function isCollapsedByUser($cid, $uid)
682 $cdata = self::getPublicAndUserContacID($cid, $uid);
689 if (!empty($cdata['public'])) {
690 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
691 if (DBA::isResult($public_contact)) {
692 $collapsed = $public_contact['collapsed'];
700 * Returns a list of contacts belonging in a group
706 public static function getByGroupId($gid)
711 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
713 INNER JOIN `group_member`
714 ON `contact`.`id` = `group_member`.`contact-id`
716 AND `contact`.`uid` = ?
717 AND NOT `contact`.`self`
718 AND NOT `contact`.`deleted`
719 AND NOT `contact`.`blocked`
720 AND NOT `contact`.`pending`
721 ORDER BY `contact`.`name` ASC',
726 if (DBA::isResult($stmt)) {
727 $return = DBA::toArray($stmt);
735 * Creates the self-contact for the provided user id
738 * @return bool Operation success
739 * @throws HTTPException\InternalServerErrorException
741 public static function createSelfFromUserId($uid)
743 // Only create the entry if it doesn't exist yet
744 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
748 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
749 if (!DBA::isResult($user)) {
753 $return = DBA::insert('contact', [
754 'uid' => $user['uid'],
755 'created' => DateTimeFormat::utcNow(),
757 'name' => $user['username'],
758 'nick' => $user['nickname'],
759 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
760 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
761 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
764 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
765 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
766 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
767 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
768 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
769 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
770 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
771 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
772 'name-date' => DateTimeFormat::utcNow(),
773 'uri-date' => DateTimeFormat::utcNow(),
774 'avatar-date' => DateTimeFormat::utcNow(),
782 * Updates the self-contact for the provided user id
785 * @param boolean $update_avatar Force the avatar update
786 * @throws HTTPException\InternalServerErrorException
788 public static function updateSelfFromUserID($uid, $update_avatar = false)
790 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
791 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
792 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
793 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
794 if (!DBA::isResult($self)) {
798 $fields = ['nickname', 'page-flags', 'account-type'];
799 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
800 if (!DBA::isResult($user)) {
804 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
805 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
806 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
807 if (!DBA::isResult($profile)) {
811 $file_suffix = 'jpg';
813 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
814 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
815 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
816 'contact-type' => $user['account-type'],
817 'xmpp' => $profile['xmpp']];
819 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
820 if (DBA::isResult($avatar)) {
821 if ($update_avatar) {
822 $fields['avatar-date'] = DateTimeFormat::utcNow();
825 // Creating the path to the avatar, beginning with the file suffix
826 $types = Images::supportedTypes();
827 if (isset($types[$avatar['type']])) {
828 $file_suffix = $types[$avatar['type']];
831 // We are adding a timestamp value so that other systems won't use cached content
832 $timestamp = strtotime($fields['avatar-date']);
834 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
835 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
837 $fields['photo'] = $prefix . '4' . $suffix;
838 $fields['thumb'] = $prefix . '5' . $suffix;
839 $fields['micro'] = $prefix . '6' . $suffix;
841 // We hadn't found a photo entry, so we use the default avatar
842 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
843 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
844 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
847 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
848 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
849 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
850 $fields['unsearchable'] = !$profile['net-publish'];
852 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
853 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
854 $fields['nurl'] = Strings::normaliseLink($fields['url']);
855 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
856 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
857 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
858 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
859 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
860 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
864 foreach ($fields as $field => $content) {
865 if ($self[$field] != $content) {
871 if ($fields['name'] != $self['name']) {
872 $fields['name-date'] = DateTimeFormat::utcNow();
874 $fields['updated'] = DateTimeFormat::utcNow();
875 DBA::update('contact', $fields, ['id' => $self['id']]);
877 // Update the public contact as well
878 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
880 // Update the profile
881 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
882 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
883 DBA::update('profile', $fields, ['uid' => $uid]);
888 * Marks a contact for removal
890 * @param int $id contact id
892 * @throws HTTPException\InternalServerErrorException
894 public static function remove($id)
896 // We want just to make sure that we don't delete our "self" contact
897 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
898 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
902 // Archive the contact
903 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
905 // Delete it in the background
906 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
910 * Sends an unfriend message. Does not remove the contact
912 * @param array $user User unfriending
913 * @param array $contact Contact unfriended
914 * @param boolean $dissolve Remove the contact on the remote side
916 * @throws HTTPException\InternalServerErrorException
917 * @throws \ImagickException
919 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
921 if (empty($contact['network'])) {
925 $protocol = $contact['network'];
926 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
927 $protocol = Protocol::ACTIVITYPUB;
930 if (($protocol == Protocol::DFRN) && $dissolve) {
931 DFRN::deliver($user, $contact, 'placeholder', true);
932 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
933 // create an unfollow slap
935 $item['verb'] = Activity::O_UNFOLLOW;
936 $item['gravity'] = GRAVITY_ACTIVITY;
937 $item['follow'] = $contact["url"];
942 $item['attach'] = '';
943 $slap = OStatus::salmon($item, $user);
945 if (!empty($contact['notify'])) {
946 Salmon::slapper($user, $contact['notify'], $slap);
948 } elseif ($protocol == Protocol::DIASPORA) {
949 Diaspora::sendUnshare($user, $contact);
950 } elseif ($protocol == Protocol::ACTIVITYPUB) {
951 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
954 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
960 * Marks a contact for archival after a communication issue delay
962 * Contact has refused to recognise us as a friend. We will start a countdown.
963 * If they still don't recognise us in 32 days, the relationship is over,
964 * and we won't waste any more time trying to communicate with them.
965 * This provides for the possibility that their database is temporarily messed
966 * up or some other transient event and that there's a possibility we could recover from it.
968 * @param array $contact contact to mark for archival
970 * @throws HTTPException\InternalServerErrorException
972 public static function markForArchival(array $contact)
974 if (!isset($contact['url']) && !empty($contact['id'])) {
975 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
976 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
977 if (!DBA::isResult($contact)) {
980 } elseif (!isset($contact['url'])) {
981 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
984 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
986 // Contact already archived or "self" contact? => nothing to do
987 if ($contact['archive'] || $contact['self']) {
991 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
992 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
993 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
996 * We really should send a notification to the owner after 2-3 weeks
997 * so they won't be surprised when the contact vanishes and can take
998 * remedial action if this was a serious mistake or glitch
1001 /// @todo Check for contact vitality via probing
1002 $archival_days = DI::config()->get('system', 'archival_days', 32);
1004 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1005 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1006 /* Relationship is really truly dead. archive them rather than
1007 * delete, though if the owner tries to unarchive them we'll start
1008 * the whole process over again.
1010 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1011 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1012 GContact::updateFromPublicContactURL($contact['url']);
1018 * Cancels the archival countdown
1020 * @see Contact::markForArchival()
1022 * @param array $contact contact to be unmarked for archival
1024 * @throws \Exception
1026 public static function unmarkForArchival(array $contact)
1028 // Always unarchive the relay contact entry
1029 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1030 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
1031 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1032 DBA::update('contact', $fields, $condition);
1035 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1036 $exists = DBA::exists('contact', $condition);
1038 // We don't need to update, we never marked this contact for archival
1043 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
1045 if (!isset($contact['url']) && !empty($contact['id'])) {
1046 $fields = ['id', 'url', 'batch'];
1047 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1048 if (!DBA::isResult($contact)) {
1053 // It's a miracle. Our dead contact has inexplicably come back to life.
1054 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
1055 DBA::update('contact', $fields, ['id' => $contact['id']]);
1056 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1057 GContact::updateFromPublicContactURL($contact['url']);
1061 * Returns the data array for the photo menu of a given contact
1063 * @param array $contact contact
1064 * @param int $uid optional, default 0
1066 * @throws HTTPException\InternalServerErrorException
1067 * @throws \ImagickException
1069 public static function photoMenu(array $contact, $uid = 0)
1074 $contact_drop_link = '';
1078 $uid = local_user();
1081 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1083 $profile_link = self::magicLink($contact['url']);
1084 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1089 // Look for our own contact if the uid doesn't match and isn't public
1090 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1091 if (DBA::isResult($contact_own)) {
1092 return self::photoMenu($contact_own, $uid);
1097 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1099 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1101 $profile_link = $contact['url'];
1104 if ($profile_link === 'mailbox') {
1109 $status_link = $profile_link . '/status';
1110 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1111 $profile_link = $profile_link . '/profile';
1114 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1115 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1118 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1119 $poke_link = 'contact/' . $contact['id'] . '/poke';
1122 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1124 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1126 if (!$contact['self']) {
1127 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1131 $unfollow_link = '';
1132 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1133 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1134 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1135 } elseif(!$contact['pending']) {
1136 $follow_link = 'follow?url=' . urlencode($contact['url']);
1140 if (!empty($follow_link) || !empty($unfollow_link)) {
1141 $contact_drop_link = '';
1146 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1148 if (empty($contact['uid'])) {
1150 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1151 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1152 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1153 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1154 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1158 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1159 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1160 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1161 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1162 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1163 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1164 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1165 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1166 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1167 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1170 if (!empty($contact['pending'])) {
1171 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1172 if (DBA::isResult($intro)) {
1173 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1178 $args = ['contact' => $contact, 'menu' => &$menu];
1180 Hook::callAll('contact_photo_menu', $args);
1182 $menucondensed = [];
1184 foreach ($menu as $menuname => $menuitem) {
1185 if ($menuitem[1] != '') {
1186 $menucondensed[$menuname] = $menuitem;
1190 return $menucondensed;
1194 * Returns ungrouped contact count or list for user
1196 * Returns either the total number of ungrouped contacts for the given user
1197 * id or a paginated list of ungrouped contacts.
1199 * @param int $uid uid
1201 * @throws \Exception
1203 public static function getUngroupedList($uid)
1213 SELECT DISTINCT(`contact-id`)
1215 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1216 WHERE `group`.`uid` = %d
1217 )", intval($uid), intval($uid));
1221 * Have a look at all contact tables for a given profile url.
1222 * This function works as a replacement for probing the contact.
1224 * @param string $url Contact URL
1225 * @param integer $cid Contact ID
1227 * @return array Contact array in the "probe" structure
1229 private static function getProbeDataFromDatabase($url, $cid = null)
1231 // The link could be provided as http although we stored it as https
1232 $ssl_url = str_replace('http://', 'https://', $url);
1234 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1235 'photo', 'keywords', 'location', 'about', 'network',
1236 'priority', 'batch', 'request', 'confirm', 'poco'];
1239 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1240 if (DBA::isResult($data)) {
1245 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1247 if (!DBA::isResult($data)) {
1248 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1249 $data = DBA::selectFirst('contact', $fields, $condition);
1252 if (DBA::isResult($data)) {
1253 // For security reasons we don't fetch key data from our users
1254 $data["pubkey"] = '';
1258 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1259 'photo', 'keywords', 'location', 'about', 'network'];
1260 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1262 if (!DBA::isResult($data)) {
1263 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1264 $data = DBA::selectFirst('contact', $fields, $condition);
1267 if (DBA::isResult($data)) {
1268 $data["pubkey"] = '';
1270 $data["priority"] = 0;
1271 $data["batch"] = '';
1272 $data["request"] = '';
1273 $data["confirm"] = '';
1278 $data = ActivityPub::probeProfile($url, false);
1279 if (!empty($data)) {
1283 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1284 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1285 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1287 if (!DBA::isResult($data)) {
1288 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1289 $data = DBA::selectFirst('contact', $fields, $condition);
1292 if (DBA::isResult($data)) {
1293 $data["pubkey"] = '';
1294 $data["keywords"] = '';
1295 $data["location"] = '';
1296 $data["about"] = '';
1305 * Fetch the contact id for a given URL and user
1307 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1308 * `addr` or `alias`.
1310 * If there's no record and we aren't looking for a public contact, we quit.
1311 * If there's one, we check that it isn't time to update the picture else we
1312 * directly return the found contact id.
1314 * Second, we probe the provided $url whether it's http://server.tld/profile or
1315 * nick@server.tld. We quit if we can't get any info back.
1317 * Third, we create the contact record if it doesn't exist
1319 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1320 * if there's any updates
1322 * @param string $url Contact URL
1323 * @param integer $uid The user id for the contact (0 = public contact)
1324 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1325 * @param array $default Default value for creating the contact when every else fails
1326 * @param boolean $in_loop Internally used variable to prevent an endless loop
1328 * @return integer Contact ID
1329 * @throws HTTPException\InternalServerErrorException
1330 * @throws \ImagickException
1332 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1334 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1342 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1344 if (!empty($contact)) {
1345 $contact_id = $contact["id"];
1347 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1348 // Update public mail accounts via their user's accounts
1349 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1350 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1351 if (!DBA::isResult($mailcontact)) {
1352 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1355 if (DBA::isResult($mailcontact)) {
1356 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1360 if (empty($update)) {
1363 } elseif ($uid != 0) {
1364 // Non-existing user-specific contact, exiting
1368 if (!$update && empty($default)) {
1369 // When we don't want to update, we look if we know this contact in any way
1370 $data = self::getProbeDataFromDatabase($url, $contact_id);
1371 $background_update = true;
1372 } elseif (!$update && !empty($default['network'])) {
1373 // If there are default values, take these
1375 $background_update = false;
1378 $background_update = false;
1381 if ((empty($data) && is_null($update)) || $update) {
1382 $data = Probe::uri($url, "", $uid);
1385 // Take the default values when probing failed
1386 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1387 $data = array_merge($data, $default);
1390 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1391 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1395 if (!empty($data['baseurl'])) {
1396 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1399 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1400 $data['gsid'] = GServer::getID($data['baseurl']);
1403 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1404 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1410 'created' => DateTimeFormat::utcNow(),
1411 'url' => $data['url'],
1412 'nurl' => Strings::normaliseLink($data['url']),
1413 'addr' => $data['addr'] ?? '',
1414 'alias' => $data['alias'] ?? '',
1415 'notify' => $data['notify'] ?? '',
1416 'poll' => $data['poll'] ?? '',
1417 'name' => $data['name'] ?? '',
1418 'nick' => $data['nick'] ?? '',
1419 'photo' => $data['photo'] ?? '',
1420 'keywords' => $data['keywords'] ?? '',
1421 'location' => $data['location'] ?? '',
1422 'about' => $data['about'] ?? '',
1423 'network' => $data['network'],
1424 'pubkey' => $data['pubkey'] ?? '',
1425 'rel' => self::SHARING,
1426 'priority' => $data['priority'] ?? 0,
1427 'batch' => $data['batch'] ?? '',
1428 'request' => $data['request'] ?? '',
1429 'confirm' => $data['confirm'] ?? '',
1430 'poco' => $data['poco'] ?? '',
1431 'baseurl' => $data['baseurl'] ?? '',
1432 'gsid' => $data['gsid'] ?? null,
1433 'name-date' => DateTimeFormat::utcNow(),
1434 'uri-date' => DateTimeFormat::utcNow(),
1435 'avatar-date' => DateTimeFormat::utcNow(),
1441 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1443 // Before inserting we do check if the entry does exist now.
1444 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1445 if (!DBA::isResult($contact)) {
1446 Logger::info('Create new contact', $fields);
1448 self::insert($fields);
1450 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1451 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1452 if (!DBA::isResult($contact)) {
1453 Logger::info('Contact creation failed', $fields);
1458 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1461 $contact_id = $contact["id"];
1464 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1465 self::updateAvatar($data['photo'], $uid, $contact_id);
1468 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1469 if ($background_update) {
1470 // Update in the background when we fetched the data solely from the database
1471 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1473 // Else do a direct update
1474 self::updateFromProbe($contact_id, '', false);
1476 // Update the gcontact entry
1478 GContact::updateFromPublicContactID($contact_id);
1479 if (($data['network'] == Protocol::ACTIVITYPUB) && in_array(DI::config()->get('system', 'gcontact_discovery'), [GContact::DISCOVERY_DIRECT, GContact::DISCOVERY_RECURSIVE])) {
1480 GContact::discoverFollowers($data['url']);
1485 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1486 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1488 // This condition should always be true
1489 if (!DBA::isResult($contact)) {
1494 'url' => $data['url'],
1495 'nurl' => Strings::normaliseLink($data['url']),
1496 'updated' => DateTimeFormat::utcNow()
1499 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1501 foreach ($fields as $field) {
1502 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1505 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1506 $updated['uri-date'] = DateTimeFormat::utcNow();
1509 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1510 $updated['name-date'] = DateTimeFormat::utcNow();
1513 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1520 * Checks if the contact is archived
1522 * @param int $cid contact id
1524 * @return boolean Is the contact archived?
1525 * @throws HTTPException\InternalServerErrorException
1527 public static function isArchived(int $cid)
1533 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1534 if (!DBA::isResult($contact)) {
1538 if ($contact['archive']) {
1542 // Check status of ActivityPub endpoints
1543 $apcontact = APContact::getByURL($contact['url'], false);
1544 if (!empty($apcontact)) {
1545 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1549 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1554 // Check status of Diaspora endpoints
1555 if (!empty($contact['batch'])) {
1556 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1557 return DBA::exists('contact', $condition);
1564 * Checks if the contact is blocked
1566 * @param int $cid contact id
1568 * @return boolean Is the contact blocked?
1569 * @throws HTTPException\InternalServerErrorException
1571 public static function isBlocked($cid)
1577 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1578 if (!DBA::isResult($blocked)) {
1582 if (Network::isUrlBlocked($blocked['url'])) {
1586 return (bool) $blocked['blocked'];
1590 * Checks if the contact is hidden
1592 * @param int $cid contact id
1594 * @return boolean Is the contact hidden?
1595 * @throws \Exception
1597 public static function isHidden($cid)
1603 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1604 if (!DBA::isResult($hidden)) {
1607 return (bool) $hidden['hidden'];
1611 * Returns posts from a given contact url
1613 * @param string $contact_url Contact URL
1614 * @param bool $thread_mode
1615 * @param int $update
1616 * @return string posts in HTML
1617 * @throws \Exception
1619 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1621 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1625 * Returns posts from a given contact id
1627 * @param integer $cid
1628 * @param bool $thread_mode
1629 * @param integer $update
1630 * @return string posts in HTML
1631 * @throws \Exception
1633 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1637 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1638 if (!DBA::isResult($contact)) {
1642 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1643 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1645 $sql = "`item`.`uid` = ?";
1648 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1651 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1652 $cid, GRAVITY_PARENT, local_user()];
1654 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1655 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1658 if (DI::mode()->isMobile()) {
1659 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1660 DI::config()->get('system', 'itemspage_network_mobile'));
1662 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1663 DI::config()->get('system', 'itemspage_network'));
1666 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1668 $params = ['order' => ['received' => true],
1669 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1672 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1674 $items = Item::inArray($r);
1676 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1678 $r = Item::selectForUser(local_user(), [], $condition, $params);
1680 $items = Item::inArray($r);
1682 $o = conversation($a, $items, 'contact-posts', false);
1686 $o .= $pager->renderMinimal(count($items));
1693 * Returns the account type name
1695 * The function can be called with either the user or the contact array
1697 * @param array $contact contact or user array
1700 public static function getAccountType(array $contact)
1702 // There are several fields that indicate that the contact or user is a forum
1703 // "page-flags" is a field in the user table,
1704 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1705 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1706 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1707 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1708 || (isset($contact['forum']) && intval($contact['forum']))
1709 || (isset($contact['prv']) && intval($contact['prv']))
1710 || (isset($contact['community']) && intval($contact['community']))
1712 $type = self::TYPE_COMMUNITY;
1714 $type = self::TYPE_PERSON;
1717 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1718 if (isset($contact["contact-type"])) {
1719 $type = $contact["contact-type"];
1722 if (isset($contact["account-type"])) {
1723 $type = $contact["account-type"];
1727 case self::TYPE_ORGANISATION:
1728 $account_type = DI::l10n()->t("Organisation");
1731 case self::TYPE_NEWS:
1732 $account_type = DI::l10n()->t('News');
1735 case self::TYPE_COMMUNITY:
1736 $account_type = DI::l10n()->t("Forum");
1744 return $account_type;
1752 * @throws \Exception
1754 public static function block($cid, $reason = null)
1756 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1762 * Unblocks a contact
1766 * @throws \Exception
1768 public static function unblock($cid)
1770 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1776 * Updates the avatar links in a contact only if needed
1778 * @param string $avatar Link to avatar picture
1779 * @param int $uid User id of contact owner
1780 * @param int $cid Contact id
1781 * @param bool $force force picture update
1784 * @throws HTTPException\InternalServerErrorException
1785 * @throws HTTPException\NotFoundException
1786 * @throws \ImagickException
1788 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1790 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1791 if (!DBA::isResult($contact)) {
1796 $contact['photo'] ?? '',
1797 $contact['thumb'] ?? '',
1798 $contact['micro'] ?? '',
1801 foreach ($data as $image_uri) {
1802 $image_rid = Photo::ridFromURI($image_uri);
1803 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1804 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1809 if (($contact["avatar"] != $avatar) || $force) {
1810 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1813 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1814 DBA::update('contact', $fields, ['id' => $cid]);
1816 // Update the public contact (contact id = 0)
1818 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1819 if (DBA::isResult($pcontact)) {
1820 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1828 * Helper function for "updateFromProbe". Updates personal and public contact
1830 * @param integer $id contact id
1831 * @param integer $uid user id
1832 * @param string $url The profile URL of the contact
1833 * @param array $fields The fields that are updated
1835 * @throws \Exception
1837 private static function updateContact($id, $uid, $url, array $fields)
1839 if (!DBA::update('contact', $fields, ['id' => $id])) {
1840 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1844 // Search for duplicated contacts and get rid of them
1845 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1849 // Update the corresponding gcontact entry
1850 GContact::updateFromPublicContactID($id);
1852 // Archive or unarchive the contact. We only need to do this for the public contact.
1853 // The archive/unarchive function will update the personal contacts by themselves.
1854 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1855 if (!DBA::isResult($contact)) {
1856 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1860 if (!empty($fields['success_update'])) {
1861 self::unmarkForArchival($contact);
1862 } elseif (!empty($fields['failure_update'])) {
1863 self::markForArchival($contact);
1866 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1868 // These contacts are sharing with us, we don't poll them.
1869 // This means that we don't set the update fields in "OnePoll.php".
1870 $condition['rel'] = self::SHARING;
1871 DBA::update('contact', $fields, $condition);
1873 unset($fields['last-update']);
1874 unset($fields['success_update']);
1875 unset($fields['failure_update']);
1877 if (empty($fields)) {
1881 // We are polling these contacts, so we mustn't set the update fields here.
1882 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1883 DBA::update('contact', $fields, $condition);
1887 * Remove duplicated contacts
1889 * @param string $nurl Normalised contact url
1890 * @param integer $uid User id
1892 * @throws \Exception
1894 public static function removeDuplicates(string $nurl, int $uid)
1896 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1897 $count = DBA::count('contact', $condition);
1902 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1903 if (!DBA::isResult($first_contact)) {
1904 // Shouldn't happen - so we handle it
1908 $first = $first_contact['id'];
1909 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1910 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1911 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1912 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1916 // Find all duplicates
1917 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1918 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1919 while ($duplicate = DBA::fetch($duplicates)) {
1920 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1924 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1926 DBA::close($duplicates);
1927 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1932 * @param integer $id contact id
1933 * @param string $network Optional network we are probing for
1934 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1936 * @throws HTTPException\InternalServerErrorException
1937 * @throws \ImagickException
1939 public static function updateFromProbe($id, $network = '', $force = false)
1942 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1943 This will reliably kill your communication with old Friendica contacts.
1946 // These fields aren't updated by this routine:
1947 // 'xmpp', 'sensitive'
1949 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1950 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1951 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
1952 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1953 if (!DBA::isResult($contact)) {
1957 $uid = $contact['uid'];
1958 unset($contact['uid']);
1960 $pubkey = $contact['pubkey'];
1961 unset($contact['pubkey']);
1963 $contact['photo'] = $contact['avatar'];
1964 unset($contact['avatar']);
1966 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1968 $updated = DateTimeFormat::utcNow();
1970 // We must not try to update relay contacts via probe. They are no real contacts.
1971 // We check after the probing to be able to correct falsely detected contact types.
1972 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1973 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1974 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
1975 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1979 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1980 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1981 if ($force && ($uid == 0)) {
1982 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1987 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1988 $ret['unsearchable'] = $ret['hide'];
1991 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1992 $ret['forum'] = false;
1993 $ret['prv'] = false;
1994 $ret['contact-type'] = $ret['account-type'];
1995 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1996 $apcontact = APContact::getByURL($ret['url'], false);
1997 if (isset($apcontact['manually-approve'])) {
1998 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1999 $ret['prv'] = (bool)!$ret['forum'];
2004 $new_pubkey = $ret['pubkey'];
2008 // make sure to not overwrite existing values with blank entries except some technical fields
2009 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2010 foreach ($ret as $key => $val) {
2011 if (!array_key_exists($key, $contact)) {
2013 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2014 $ret[$key] = $contact[$key];
2015 } elseif ($ret[$key] != $contact[$key]) {
2020 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2021 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2026 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2029 // Update the public contact
2031 self::updateFromProbeByURL($ret['url']);
2037 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2038 $ret['updated'] = $updated;
2040 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2041 if (empty($pubkey) && !empty($new_pubkey)) {
2042 $ret['pubkey'] = $new_pubkey;
2045 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2046 $ret['uri-date'] = DateTimeFormat::utcNow();
2049 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2050 $ret['name-date'] = $updated;
2053 if ($force && ($uid == 0)) {
2054 $ret['last-update'] = $updated;
2055 $ret['success_update'] = $updated;
2058 unset($ret['photo']);
2060 self::updateContact($id, $uid, $ret['url'], $ret);
2065 public static function updateFromProbeByURL($url, $force = false)
2067 $id = self::getIdForURL($url);
2073 self::updateFromProbe($id, '', $force);
2079 * Detects if a given contact array belongs to a legacy DFRN connection
2081 * @param array $contact
2084 public static function isLegacyDFRNContact($contact)
2086 // Newer Friendica contacts are connected via AP, then these fields aren't set
2087 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2091 * Detects the communication protocol for a given contact url.
2092 * This is used to detect Friendica contacts that we can communicate via AP.
2094 * @param string $url contact url
2095 * @param string $network Network of that contact
2096 * @return string with protocol
2098 public static function getProtocol($url, $network)
2100 if ($network != Protocol::DFRN) {
2104 $apcontact = APContact::getByURL($url);
2105 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2106 return Protocol::ACTIVITYPUB;
2113 * Takes a $uid and a url/handle and adds a new contact
2115 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2116 * dfrn_request page.
2118 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2121 * $return['success'] boolean true if successful
2122 * $return['message'] error text if success is false.
2124 * Takes a $uid and a url/handle and adds a new contact
2126 * @param array $user The user the contact should be created for
2127 * @param string $url The profile URL of the contact
2128 * @param bool $interactive
2129 * @param string $network
2131 * @throws HTTPException\InternalServerErrorException
2132 * @throws HTTPException\NotFoundException
2133 * @throws \ImagickException
2135 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2137 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2139 // remove ajax junk, e.g. Twitter
2140 $url = str_replace('/#!/', '/', $url);
2142 if (!Network::isUrlAllowed($url)) {
2143 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2147 if (Network::isUrlBlocked($url)) {
2148 $result['message'] = DI::l10n()->t('Blocked domain');
2153 $result['message'] = DI::l10n()->t('Connect URL missing.');
2157 $arr = ['url' => $url, 'contact' => []];
2159 Hook::callAll('follow', $arr);
2162 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2166 if (!empty($arr['contact']['name'])) {
2167 $ret = $arr['contact'];
2169 $ret = Probe::uri($url, $network, $user['uid'], false);
2172 if (($network != '') && ($ret['network'] != $network)) {
2173 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2177 // check if we already have a contact
2178 // the poll url is more reliable than the profile url, as we may have
2179 // indirect links or webfinger links
2181 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2182 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2183 if (!DBA::isResult($contact)) {
2184 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2185 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2188 $protocol = self::getProtocol($ret['url'], $ret['network']);
2190 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2192 if (strlen(DI::baseUrl()->getUrlPath())) {
2193 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2195 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2198 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2202 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2203 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2204 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2208 // This extra param just confuses things, remove it
2209 if ($protocol === Protocol::DIASPORA) {
2210 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2213 // do we have enough information?
2214 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2215 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2216 if (empty($ret['poll'])) {
2217 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2219 if (empty($ret['name'])) {
2220 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2222 if (empty($ret['url'])) {
2223 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2225 if (strpos($ret['url'], '@') !== false) {
2226 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2227 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2232 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2233 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2234 $ret['notify'] = '';
2237 if (!$ret['notify']) {
2238 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2241 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2243 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2245 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2248 if ($protocol == Protocol::ACTIVITYPUB) {
2249 $apcontact = APContact::getByURL($ret['url'], false);
2250 if (isset($apcontact['manually-approve'])) {
2251 $pending = (bool)$apcontact['manually-approve'];
2255 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2259 if (DBA::isResult($contact)) {
2261 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2263 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2264 DBA::update('contact', $fields, ['id' => $contact['id']]);
2266 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2268 // create contact record
2270 'uid' => $user['uid'],
2271 'created' => DateTimeFormat::utcNow(),
2272 'url' => $ret['url'],
2273 'nurl' => Strings::normaliseLink($ret['url']),
2274 'addr' => $ret['addr'],
2275 'alias' => $ret['alias'],
2276 'batch' => $ret['batch'],
2277 'notify' => $ret['notify'],
2278 'poll' => $ret['poll'],
2279 'poco' => $ret['poco'],
2280 'name' => $ret['name'],
2281 'nick' => $ret['nick'],
2282 'network' => $ret['network'],
2283 'baseurl' => $ret['baseurl'],
2284 'gsid' => $ret['gsid'] ?? null,
2285 'protocol' => $protocol,
2286 'pubkey' => $ret['pubkey'],
2287 'rel' => $new_relation,
2288 'priority'=> $ret['priority'],
2289 'writable'=> $writeable,
2290 'hidden' => $hidden,
2293 'pending' => $pending,
2298 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2299 if (!DBA::isResult($contact)) {
2300 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2304 $contact_id = $contact['id'];
2305 $result['cid'] = $contact_id;
2307 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2309 // Update the avatar
2310 self::updateAvatar($ret['photo'], $user['uid'], $contact_id);
2312 // pull feed and consume it, which should subscribe to the hub.
2314 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2316 $owner = User::getOwnerDataById($user['uid']);
2318 if (DBA::isResult($owner)) {
2319 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2320 // create a follow slap
2322 $item['verb'] = Activity::FOLLOW;
2323 $item['gravity'] = GRAVITY_ACTIVITY;
2324 $item['follow'] = $contact["url"];
2326 $item['title'] = '';
2328 $item['uri-id'] = 0;
2329 $item['attach'] = '';
2331 $slap = OStatus::salmon($item, $owner);
2333 if (!empty($contact['notify'])) {
2334 Salmon::slapper($owner, $contact['notify'], $slap);
2336 } elseif ($protocol == Protocol::DIASPORA) {
2337 $ret = Diaspora::sendShare($owner, $contact);
2338 Logger::log('share returns: ' . $ret);
2339 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2340 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2341 if (empty($activity_id)) {
2342 // This really should never happen
2346 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2347 Logger::log('Follow returns: ' . $ret);
2351 $result['success'] = true;
2356 * Updated contact's SSL policy
2358 * @param array $contact Contact array
2359 * @param string $new_policy New policy, valid: self,full
2361 * @return array Contact array with updated values
2362 * @throws \Exception
2364 public static function updateSslPolicy(array $contact, $new_policy)
2366 $ssl_changed = false;
2367 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2368 $ssl_changed = true;
2369 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2370 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2371 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2372 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2373 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2374 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2377 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2378 $ssl_changed = true;
2379 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2380 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2381 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2382 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2383 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2384 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2388 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2389 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2390 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2391 DBA::update('contact', $fields, ['id' => $contact['id']]);
2398 * @param array $importer Owner (local user) data
2399 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2400 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2401 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2402 * @param string $note Introduction additional message
2403 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2404 * @throws HTTPException\InternalServerErrorException
2405 * @throws \ImagickException
2407 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2409 // Should always be set
2410 if (empty($datarray['author-id'])) {
2414 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2415 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2416 if (!DBA::isResult($pub_contact)) {
2417 // Should never happen
2421 // Contact is blocked at node-level
2422 if (self::isBlocked($datarray['author-id'])) {
2426 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2427 $name = $pub_contact['name'];
2428 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2429 $nick = $pub_contact['nick'];
2430 $network = $pub_contact['network'];
2432 // Ensure that we don't create a new contact when there already is one
2433 $cid = self::getIdForURL($url, $importer['uid']);
2435 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2438 if (!empty($contact)) {
2439 if (!empty($contact['pending'])) {
2440 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2444 // Contact is blocked at user-level
2445 if (!empty($contact['id']) && !empty($importer['id']) &&
2446 self::isBlockedByUser($contact['id'], $importer['id'])) {
2450 // Make sure that the existing contact isn't archived
2451 self::unmarkForArchival($contact);
2453 if (($contact['rel'] == self::SHARING)
2454 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2455 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2456 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2459 // Ensure to always have the correct network type, independent from the connection request method
2460 self::updateFromProbe($contact['id'], '', true);
2464 // send email notification to owner?
2465 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2466 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2470 // create contact record
2471 DBA::insert('contact', [
2472 'uid' => $importer['uid'],
2473 'created' => DateTimeFormat::utcNow(),
2475 'nurl' => Strings::normaliseLink($url),
2479 'network' => $network,
2480 'rel' => self::FOLLOWER,
2487 $contact_id = DBA::lastInsertId();
2489 // Ensure to always have the correct network type, independent from the connection request method
2490 self::updateFromProbe($contact_id, '', true);
2492 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2494 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2496 /// @TODO Encapsulate this into a function/method
2497 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2498 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2499 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2500 // create notification
2501 $hash = Strings::getRandomHex();
2503 if (is_array($contact_record)) {
2504 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2505 'blocked' => false, 'knowyou' => false, 'note' => $note,
2506 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2509 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2511 if (($user['notify-flags'] & Type::INTRO) &&
2512 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2515 'type' => Type::INTRO,
2516 'notify_flags' => $user['notify-flags'],
2517 'language' => $user['language'],
2518 'to_name' => $user['username'],
2519 'to_email' => $user['email'],
2520 'uid' => $user['uid'],
2521 'link' => DI::baseUrl() . '/notifications/intros',
2522 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2523 'source_link' => $contact_record['url'],
2524 'source_photo' => $contact_record['photo'],
2525 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2529 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2530 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2531 self::createFromProbe($importer, $url, false, $network);
2534 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2535 $fields = ['pending' => false];
2536 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2537 $fields['rel'] = Contact::FRIEND;
2540 DBA::update('contact', $fields, $condition);
2549 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2551 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2552 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2554 Contact::remove($contact['id']);
2558 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2560 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2561 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2563 Contact::remove($contact['id']);
2568 * Create a birthday event.
2570 * Update the year and the birthday.
2572 public static function updateBirthdays()
2576 AND `bd` > "0001-01-01"
2577 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2578 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2579 AND NOT `contact`.`pending`
2580 AND NOT `contact`.`hidden`
2581 AND NOT `contact`.`blocked`
2582 AND NOT `contact`.`archive`
2583 AND NOT `contact`.`deleted`',
2588 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2590 while ($contact = DBA::fetch($contacts)) {
2591 Logger::log('update_contact_birthday: ' . $contact['bd']);
2593 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2595 if (Event::createBirthday($contact, $nextbd)) {
2599 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2600 ['id' => $contact['id']]
2604 DBA::close($contacts);
2608 * Remove the unavailable contact ids from the provided list
2610 * @param array $contact_ids Contact id list
2612 * @throws \Exception
2614 public static function pruneUnavailable(array $contact_ids)
2616 if (empty($contact_ids)) {
2620 $contacts = Contact::selectToArray(['id'], [
2621 'id' => $contact_ids,
2627 return array_column($contacts, 'id');
2631 * Returns a magic link to authenticate remote visitors
2633 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2635 * @param string $contact_url The address of the target contact profile
2636 * @param string $url An url that we will be redirected to after the authentication
2638 * @return string with "redir" link
2639 * @throws HTTPException\InternalServerErrorException
2640 * @throws \ImagickException
2642 public static function magicLink($contact_url, $url = '')
2644 if (!Session::isAuthenticated()) {
2645 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2648 $data = self::getProbeDataFromDatabase($contact_url);
2650 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2653 // Prevents endless loop in case only a non-public contact exists for the contact URL
2654 unset($data['uid']);
2656 return self::magicLinkByContact($data, $url ?: $contact_url);
2660 * Returns a magic link to authenticate remote visitors
2662 * @param integer $cid The contact id of the target contact profile
2663 * @param string $url An url that we will be redirected to after the authentication
2665 * @return string with "redir" link
2666 * @throws HTTPException\InternalServerErrorException
2667 * @throws \ImagickException
2669 public static function magicLinkbyId($cid, $url = '')
2671 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2673 return self::magicLinkByContact($contact, $url);
2677 * Returns a magic link to authenticate remote visitors
2679 * @param array $contact The contact array with "uid", "network" and "url"
2680 * @param string $url An url that we will be redirected to after the authentication
2682 * @return string with "redir" link
2683 * @throws HTTPException\InternalServerErrorException
2684 * @throws \ImagickException
2686 public static function magicLinkByContact($contact, $url = '')
2688 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2690 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2691 return $destination;
2694 // Only redirections to the same host do make sense
2695 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2699 if (!empty($contact['uid'])) {
2700 return self::magicLink($contact['url'], $url);
2703 if (empty($contact['id'])) {
2704 return $destination;
2707 $redirect = 'redir/' . $contact['id'];
2709 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2710 $redirect .= '?url=' . $url;
2717 * Remove a contact from all groups
2719 * @param integer $contact_id
2721 * @return boolean Success
2723 public static function removeFromGroups($contact_id)
2725 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2729 * Is the contact a forum?
2731 * @param integer $contactid ID of the contact
2733 * @return boolean "true" if it is a forum
2735 public static function isForum($contactid)
2737 $fields = ['forum', 'prv'];
2738 $condition = ['id' => $contactid];
2739 $contact = DBA::selectFirst('contact', $fields, $condition);
2740 if (!DBA::isResult($contact)) {
2745 return ($contact['forum'] || $contact['prv']);
2749 * Can the remote contact receive private messages?
2751 * @param array $contact
2754 public static function canReceivePrivateMessages(array $contact)
2756 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2757 $self = $contact['self'] ?? false;
2759 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;