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 if (!empty($fields)) {
215 foreach (['id', 'updated', 'network'] as $internal) {
216 if (!in_array($internal, $fields)) {
217 $fields[] = $internal;
218 $removal[] = $internal;
223 // We first try the nurl (http://server.tld/nick), most common case
224 $options = ['order' => ['id']];
225 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
227 // Then the addr (nick@server.tld)
228 if (!DBA::isResult($contact)) {
229 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
232 // Then the alias (which could be anything)
233 if (!DBA::isResult($contact)) {
234 // The link could be provided as http although we stored it as https
235 $ssl_url = str_replace('http://', 'https://', $url);
236 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
237 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
240 // Update the contact in the background if needed
241 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
242 in_array($contact['network'], Protocol::FEDERATED)) {
243 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
246 // Remove the internal fields
247 foreach ($removal as $internal) {
248 unset($contact[$internal]);
255 * Fetches a contact for a given user by a given url.
256 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
258 * @param string $url profile url
259 * @param integer $uid User ID of the contact
260 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
261 * @param array $fields Field list
262 * @return array contact array
264 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
267 $contact = self::getByURL($url, $update, $fields, $uid);
268 if (!empty($contact)) {
269 if (!empty($contact['id'])) {
270 $contact['cid'] = $contact['id'];
277 $contact = self::getByURL($url, $update, $fields);
278 if (!empty($contact['id'])) {
280 $contact['zid'] = $contact['id'];
286 * Tests if the given contact is a follower
288 * @param int $cid Either public contact id or user's contact id
289 * @param int $uid User ID
291 * @return boolean is the contact id a follower?
292 * @throws HTTPException\InternalServerErrorException
293 * @throws \ImagickException
295 public static function isFollower($cid, $uid)
297 if (self::isBlockedByUser($cid, $uid)) {
301 $cdata = self::getPublicAndUserContacID($cid, $uid);
302 if (empty($cdata['user'])) {
306 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
307 return DBA::exists('contact', $condition);
311 * Tests if the given contact url is a follower
313 * @param string $url Contact URL
314 * @param int $uid User ID
316 * @return boolean is the contact id a follower?
317 * @throws HTTPException\InternalServerErrorException
318 * @throws \ImagickException
320 public static function isFollowerByURL($url, $uid)
322 $cid = self::getIdForURL($url, $uid, false);
328 return self::isFollower($cid, $uid);
332 * Tests if the given user follow the given contact
334 * @param int $cid Either public contact id or user's contact id
335 * @param int $uid User ID
337 * @return boolean is the contact url being followed?
338 * @throws HTTPException\InternalServerErrorException
339 * @throws \ImagickException
341 public static function isSharing($cid, $uid)
343 if (self::isBlockedByUser($cid, $uid)) {
347 $cdata = self::getPublicAndUserContacID($cid, $uid);
348 if (empty($cdata['user'])) {
352 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
353 return DBA::exists('contact', $condition);
357 * Tests if the given user follow the given contact url
359 * @param string $url Contact URL
360 * @param int $uid User ID
362 * @return boolean is the contact url being followed?
363 * @throws HTTPException\InternalServerErrorException
364 * @throws \ImagickException
366 public static function isSharingByURL($url, $uid)
368 $cid = self::getIdForURL($url, $uid, false);
374 return self::isSharing($cid, $uid);
378 * Get the basepath for a given contact link
380 * @param string $url The contact link
381 * @param boolean $dont_update Don't update the contact
383 * @return string basepath
384 * @throws HTTPException\InternalServerErrorException
385 * @throws \ImagickException
387 public static function getBasepath($url, $dont_update = false)
389 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
390 if (!DBA::isResult($contact)) {
394 if (!empty($contact['baseurl'])) {
395 return $contact['baseurl'];
396 } elseif ($dont_update) {
400 // Update the existing contact
401 self::updateFromProbe($contact['id'], '', true);
403 // And fetch the result
404 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
405 if (empty($contact['baseurl'])) {
406 Logger::info('No baseurl for contact', ['url' => $url]);
410 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
411 return $contact['baseurl'];
415 * Check if the given contact url is on the same server
417 * @param string $url The contact link
419 * @return boolean Is it the same server?
421 public static function isLocal($url)
423 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
427 * Check if the given contact ID is on the same server
429 * @param string $url The contact link
431 * @return boolean Is it the same server?
433 public static function isLocalById(int $cid)
435 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
436 if (!DBA::isResult($contact)) {
440 if (empty($contact['baseurl'])) {
441 $baseurl = self::getBasepath($contact['url'], true);
443 $baseurl = $contact['baseurl'];
446 return Strings::compareLink($baseurl, DI::baseUrl());
450 * Returns the public contact id of the given user id
452 * @param integer $uid User ID
454 * @return integer|boolean Public contact id for given user id
457 public static function getPublicIdByUserId($uid)
459 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
460 if (!DBA::isResult($self)) {
463 return self::getIdForURL($self['url'], 0, false);
467 * Returns the contact id for the user and the public contact id for a given contact id
469 * @param int $cid Either public contact id or user's contact id
470 * @param int $uid User ID
472 * @return array with public and user's contact id
473 * @throws HTTPException\InternalServerErrorException
474 * @throws \ImagickException
476 public static function getPublicAndUserContacID($cid, $uid)
478 if (empty($uid) || empty($cid)) {
482 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
483 if (!DBA::isResult($contact)) {
487 // We quit when the user id don't match the user id of the provided contact
488 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
492 if ($contact['uid'] != 0) {
493 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
497 $ucid = $contact['id'];
499 $pcid = $contact['id'];
500 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
503 return ['public' => $pcid, 'user' => $ucid];
507 * Returns contact details for a given contact id in combination with a user id
509 * @param int $cid A contact ID
510 * @param int $uid The User ID
511 * @param array $fields The selected fields for the contact
513 * @return array The contact details
517 public static function getContactForUser($cid, $uid, array $fields = [])
519 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
521 if (!DBA::isResult($contact)) {
529 * Block contact id for user id
531 * @param int $cid Either public contact id or user's contact id
532 * @param int $uid User ID
533 * @param boolean $blocked Is the contact blocked or unblocked?
536 public static function setBlockedForUser($cid, $uid, $blocked)
538 $cdata = self::getPublicAndUserContacID($cid, $uid);
543 if ($cdata['user'] != 0) {
544 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
547 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
551 * Returns "block" state for contact id and user id
553 * @param int $cid Either public contact id or user's contact id
554 * @param int $uid User ID
556 * @return boolean is the contact id blocked for the given user?
559 public static function isBlockedByUser($cid, $uid)
561 $cdata = self::getPublicAndUserContacID($cid, $uid);
566 $public_blocked = false;
568 if (!empty($cdata['public'])) {
569 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
570 if (DBA::isResult($public_contact)) {
571 $public_blocked = $public_contact['blocked'];
575 $user_blocked = $public_blocked;
577 if (!empty($cdata['user'])) {
578 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
579 if (DBA::isResult($user_contact)) {
580 $user_blocked = $user_contact['blocked'];
584 if ($user_blocked != $public_blocked) {
585 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
588 return $user_blocked;
592 * Ignore contact id for user id
594 * @param int $cid Either public contact id or user's contact id
595 * @param int $uid User ID
596 * @param boolean $ignored Is the contact ignored or unignored?
599 public static function setIgnoredForUser($cid, $uid, $ignored)
601 $cdata = self::getPublicAndUserContacID($cid, $uid);
606 if ($cdata['user'] != 0) {
607 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
610 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
614 * Returns "ignore" state for contact id and user id
616 * @param int $cid Either public contact id or user's contact id
617 * @param int $uid User ID
619 * @return boolean is the contact id ignored for the given user?
622 public static function isIgnoredByUser($cid, $uid)
624 $cdata = self::getPublicAndUserContacID($cid, $uid);
629 $public_ignored = false;
631 if (!empty($cdata['public'])) {
632 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
633 if (DBA::isResult($public_contact)) {
634 $public_ignored = $public_contact['ignored'];
638 $user_ignored = $public_ignored;
640 if (!empty($cdata['user'])) {
641 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
642 if (DBA::isResult($user_contact)) {
643 $user_ignored = $user_contact['readonly'];
647 if ($user_ignored != $public_ignored) {
648 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
651 return $user_ignored;
655 * Set "collapsed" for contact id and user id
657 * @param int $cid Either public contact id or user's contact id
658 * @param int $uid User ID
659 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
662 public static function setCollapsedForUser($cid, $uid, $collapsed)
664 $cdata = self::getPublicAndUserContacID($cid, $uid);
669 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
673 * Returns "collapsed" state for contact id and user id
675 * @param int $cid Either public contact id or user's contact id
676 * @param int $uid User ID
678 * @return boolean is the contact id blocked for the given user?
679 * @throws HTTPException\InternalServerErrorException
680 * @throws \ImagickException
682 public static function isCollapsedByUser($cid, $uid)
684 $cdata = self::getPublicAndUserContacID($cid, $uid);
691 if (!empty($cdata['public'])) {
692 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
693 if (DBA::isResult($public_contact)) {
694 $collapsed = $public_contact['collapsed'];
702 * Returns a list of contacts belonging in a group
708 public static function getByGroupId($gid)
713 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
715 INNER JOIN `group_member`
716 ON `contact`.`id` = `group_member`.`contact-id`
718 AND `contact`.`uid` = ?
719 AND NOT `contact`.`self`
720 AND NOT `contact`.`deleted`
721 AND NOT `contact`.`blocked`
722 AND NOT `contact`.`pending`
723 ORDER BY `contact`.`name` ASC',
728 if (DBA::isResult($stmt)) {
729 $return = DBA::toArray($stmt);
737 * Creates the self-contact for the provided user id
740 * @return bool Operation success
741 * @throws HTTPException\InternalServerErrorException
743 public static function createSelfFromUserId($uid)
745 // Only create the entry if it doesn't exist yet
746 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
750 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
751 if (!DBA::isResult($user)) {
755 $return = DBA::insert('contact', [
756 'uid' => $user['uid'],
757 'created' => DateTimeFormat::utcNow(),
759 'name' => $user['username'],
760 'nick' => $user['nickname'],
761 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
762 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
763 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
766 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
767 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
768 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
769 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
770 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
771 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
772 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
773 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
774 'name-date' => DateTimeFormat::utcNow(),
775 'uri-date' => DateTimeFormat::utcNow(),
776 'avatar-date' => DateTimeFormat::utcNow(),
784 * Updates the self-contact for the provided user id
787 * @param boolean $update_avatar Force the avatar update
788 * @throws HTTPException\InternalServerErrorException
790 public static function updateSelfFromUserID($uid, $update_avatar = false)
792 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
793 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
794 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
795 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
796 if (!DBA::isResult($self)) {
800 $fields = ['nickname', 'page-flags', 'account-type'];
801 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
802 if (!DBA::isResult($user)) {
806 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
807 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
808 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
809 if (!DBA::isResult($profile)) {
813 $file_suffix = 'jpg';
815 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
816 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
817 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
818 'contact-type' => $user['account-type'],
819 'xmpp' => $profile['xmpp']];
821 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
822 if (DBA::isResult($avatar)) {
823 if ($update_avatar) {
824 $fields['avatar-date'] = DateTimeFormat::utcNow();
827 // Creating the path to the avatar, beginning with the file suffix
828 $types = Images::supportedTypes();
829 if (isset($types[$avatar['type']])) {
830 $file_suffix = $types[$avatar['type']];
833 // We are adding a timestamp value so that other systems won't use cached content
834 $timestamp = strtotime($fields['avatar-date']);
836 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
837 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
839 $fields['photo'] = $prefix . '4' . $suffix;
840 $fields['thumb'] = $prefix . '5' . $suffix;
841 $fields['micro'] = $prefix . '6' . $suffix;
843 // We hadn't found a photo entry, so we use the default avatar
844 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
845 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
846 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
849 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
850 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
851 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
852 $fields['unsearchable'] = !$profile['net-publish'];
854 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
855 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
856 $fields['nurl'] = Strings::normaliseLink($fields['url']);
857 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
858 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
859 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
860 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
861 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
862 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
866 foreach ($fields as $field => $content) {
867 if ($self[$field] != $content) {
873 if ($fields['name'] != $self['name']) {
874 $fields['name-date'] = DateTimeFormat::utcNow();
876 $fields['updated'] = DateTimeFormat::utcNow();
877 DBA::update('contact', $fields, ['id' => $self['id']]);
879 // Update the public contact as well
880 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
882 // Update the profile
883 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
884 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
885 DBA::update('profile', $fields, ['uid' => $uid]);
890 * Marks a contact for removal
892 * @param int $id contact id
894 * @throws HTTPException\InternalServerErrorException
896 public static function remove($id)
898 // We want just to make sure that we don't delete our "self" contact
899 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
900 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
904 // Archive the contact
905 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
907 // Delete it in the background
908 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
912 * Sends an unfriend message. Does not remove the contact
914 * @param array $user User unfriending
915 * @param array $contact Contact unfriended
916 * @param boolean $dissolve Remove the contact on the remote side
918 * @throws HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
923 if (empty($contact['network'])) {
927 $protocol = $contact['network'];
928 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
929 $protocol = Protocol::ACTIVITYPUB;
932 if (($protocol == Protocol::DFRN) && $dissolve) {
933 DFRN::deliver($user, $contact, 'placeholder', true);
934 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
935 // create an unfollow slap
937 $item['verb'] = Activity::O_UNFOLLOW;
938 $item['gravity'] = GRAVITY_ACTIVITY;
939 $item['follow'] = $contact["url"];
944 $item['attach'] = '';
945 $slap = OStatus::salmon($item, $user);
947 if (!empty($contact['notify'])) {
948 Salmon::slapper($user, $contact['notify'], $slap);
950 } elseif ($protocol == Protocol::DIASPORA) {
951 Diaspora::sendUnshare($user, $contact);
952 } elseif ($protocol == Protocol::ACTIVITYPUB) {
953 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
956 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
962 * Marks a contact for archival after a communication issue delay
964 * Contact has refused to recognise us as a friend. We will start a countdown.
965 * If they still don't recognise us in 32 days, the relationship is over,
966 * and we won't waste any more time trying to communicate with them.
967 * This provides for the possibility that their database is temporarily messed
968 * up or some other transient event and that there's a possibility we could recover from it.
970 * @param array $contact contact to mark for archival
972 * @throws HTTPException\InternalServerErrorException
974 public static function markForArchival(array $contact)
976 if (!isset($contact['url']) && !empty($contact['id'])) {
977 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
978 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
979 if (!DBA::isResult($contact)) {
982 } elseif (!isset($contact['url'])) {
983 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
986 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
988 // Contact already archived or "self" contact? => nothing to do
989 if ($contact['archive'] || $contact['self']) {
993 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
994 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
995 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
998 * We really should send a notification to the owner after 2-3 weeks
999 * so they won't be surprised when the contact vanishes and can take
1000 * remedial action if this was a serious mistake or glitch
1003 /// @todo Check for contact vitality via probing
1004 $archival_days = DI::config()->get('system', 'archival_days', 32);
1006 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1007 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1008 /* Relationship is really truly dead. archive them rather than
1009 * delete, though if the owner tries to unarchive them we'll start
1010 * the whole process over again.
1012 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1013 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1014 GContact::updateFromPublicContactURL($contact['url']);
1020 * Cancels the archival countdown
1022 * @see Contact::markForArchival()
1024 * @param array $contact contact to be unmarked for archival
1026 * @throws \Exception
1028 public static function unmarkForArchival(array $contact)
1030 // Always unarchive the relay contact entry
1031 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1032 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1033 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1034 DBA::update('contact', $fields, $condition);
1037 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1038 $exists = DBA::exists('contact', $condition);
1040 // We don't need to update, we never marked this contact for archival
1045 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
1047 if (!isset($contact['url']) && !empty($contact['id'])) {
1048 $fields = ['id', 'url', 'batch'];
1049 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1050 if (!DBA::isResult($contact)) {
1055 // It's a miracle. Our dead contact has inexplicably come back to life.
1056 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1057 DBA::update('contact', $fields, ['id' => $contact['id']]);
1058 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1059 GContact::updateFromPublicContactURL($contact['url']);
1063 * Returns the data array for the photo menu of a given contact
1065 * @param array $contact contact
1066 * @param int $uid optional, default 0
1068 * @throws HTTPException\InternalServerErrorException
1069 * @throws \ImagickException
1071 public static function photoMenu(array $contact, $uid = 0)
1076 $contact_drop_link = '';
1080 $uid = local_user();
1083 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1085 $profile_link = self::magicLink($contact['url']);
1086 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1091 // Look for our own contact if the uid doesn't match and isn't public
1092 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1093 if (DBA::isResult($contact_own)) {
1094 return self::photoMenu($contact_own, $uid);
1099 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1101 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1103 $profile_link = $contact['url'];
1106 if ($profile_link === 'mailbox') {
1111 $status_link = $profile_link . '/status';
1112 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1113 $profile_link = $profile_link . '/profile';
1116 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1117 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1120 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1121 $poke_link = 'contact/' . $contact['id'] . '/poke';
1124 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1126 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1128 if (!$contact['self']) {
1129 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1133 $unfollow_link = '';
1134 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1135 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1136 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1137 } elseif(!$contact['pending']) {
1138 $follow_link = 'follow?url=' . urlencode($contact['url']);
1142 if (!empty($follow_link) || !empty($unfollow_link)) {
1143 $contact_drop_link = '';
1148 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1150 if (empty($contact['uid'])) {
1152 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1153 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1154 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1155 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1156 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1160 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1161 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1162 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1163 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1164 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1165 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1166 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1167 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1168 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1169 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1172 if (!empty($contact['pending'])) {
1173 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1174 if (DBA::isResult($intro)) {
1175 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1180 $args = ['contact' => $contact, 'menu' => &$menu];
1182 Hook::callAll('contact_photo_menu', $args);
1184 $menucondensed = [];
1186 foreach ($menu as $menuname => $menuitem) {
1187 if ($menuitem[1] != '') {
1188 $menucondensed[$menuname] = $menuitem;
1192 return $menucondensed;
1196 * Returns ungrouped contact count or list for user
1198 * Returns either the total number of ungrouped contacts for the given user
1199 * id or a paginated list of ungrouped contacts.
1201 * @param int $uid uid
1203 * @throws \Exception
1205 public static function getUngroupedList($uid)
1215 SELECT DISTINCT(`contact-id`)
1217 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1218 WHERE `group`.`uid` = %d
1219 )", intval($uid), intval($uid));
1223 * Have a look at all contact tables for a given profile url.
1224 * This function works as a replacement for probing the contact.
1226 * @param string $url Contact URL
1227 * @param integer $cid Contact ID
1229 * @return array Contact array in the "probe" structure
1231 private static function getProbeDataFromDatabase($url, $cid = null)
1233 // The link could be provided as http although we stored it as https
1234 $ssl_url = str_replace('http://', 'https://', $url);
1236 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1237 'photo', 'keywords', 'location', 'about', 'network',
1238 'priority', 'batch', 'request', 'confirm', 'poco'];
1241 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1242 if (DBA::isResult($data)) {
1247 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1249 if (!DBA::isResult($data)) {
1250 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1251 $data = DBA::selectFirst('contact', $fields, $condition);
1254 if (DBA::isResult($data)) {
1255 // For security reasons we don't fetch key data from our users
1256 $data["pubkey"] = '';
1260 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1261 'photo', 'keywords', 'location', 'about', 'network'];
1262 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1264 if (!DBA::isResult($data)) {
1265 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1266 $data = DBA::selectFirst('contact', $fields, $condition);
1269 if (DBA::isResult($data)) {
1270 $data["pubkey"] = '';
1272 $data["priority"] = 0;
1273 $data["batch"] = '';
1274 $data["request"] = '';
1275 $data["confirm"] = '';
1280 $data = ActivityPub::probeProfile($url, false);
1281 if (!empty($data)) {
1285 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1286 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1287 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1289 if (!DBA::isResult($data)) {
1290 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1291 $data = DBA::selectFirst('contact', $fields, $condition);
1294 if (DBA::isResult($data)) {
1295 $data["pubkey"] = '';
1296 $data["keywords"] = '';
1297 $data["location"] = '';
1298 $data["about"] = '';
1307 * Fetch the contact id for a given URL and user
1309 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1310 * `addr` or `alias`.
1312 * If there's no record and we aren't looking for a public contact, we quit.
1313 * If there's one, we check that it isn't time to update the picture else we
1314 * directly return the found contact id.
1316 * Second, we probe the provided $url whether it's http://server.tld/profile or
1317 * nick@server.tld. We quit if we can't get any info back.
1319 * Third, we create the contact record if it doesn't exist
1321 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1322 * if there's any updates
1324 * @param string $url Contact URL
1325 * @param integer $uid The user id for the contact (0 = public contact)
1326 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1327 * @param array $default Default value for creating the contact when every else fails
1328 * @param boolean $in_loop Internally used variable to prevent an endless loop
1330 * @return integer Contact ID
1331 * @throws HTTPException\InternalServerErrorException
1332 * @throws \ImagickException
1334 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1336 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1344 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1346 if (!empty($contact)) {
1347 $contact_id = $contact["id"];
1349 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1350 // Update public mail accounts via their user's accounts
1351 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1352 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1353 if (!DBA::isResult($mailcontact)) {
1354 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1357 if (DBA::isResult($mailcontact)) {
1358 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1362 if (empty($update)) {
1365 } elseif ($uid != 0) {
1366 // Non-existing user-specific contact, exiting
1370 if (!$update && empty($default)) {
1371 // When we don't want to update, we look if we know this contact in any way
1372 $data = self::getProbeDataFromDatabase($url, $contact_id);
1373 $background_update = true;
1374 } elseif (!$update && !empty($default['network'])) {
1375 // If there are default values, take these
1377 $background_update = false;
1380 $background_update = false;
1383 if ((empty($data) && is_null($update)) || $update) {
1384 $data = Probe::uri($url, "", $uid);
1387 // Take the default values when probing failed
1388 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1389 $data = array_merge($data, $default);
1392 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1393 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1397 if (!empty($data['baseurl'])) {
1398 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1401 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1402 $data['gsid'] = GServer::getID($data['baseurl']);
1405 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1406 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1412 'created' => DateTimeFormat::utcNow(),
1413 'url' => $data['url'],
1414 'nurl' => Strings::normaliseLink($data['url']),
1415 'addr' => $data['addr'] ?? '',
1416 'alias' => $data['alias'] ?? '',
1417 'notify' => $data['notify'] ?? '',
1418 'poll' => $data['poll'] ?? '',
1419 'name' => $data['name'] ?? '',
1420 'nick' => $data['nick'] ?? '',
1421 'photo' => $data['photo'] ?? '',
1422 'keywords' => $data['keywords'] ?? '',
1423 'location' => $data['location'] ?? '',
1424 'about' => $data['about'] ?? '',
1425 'network' => $data['network'],
1426 'pubkey' => $data['pubkey'] ?? '',
1427 'rel' => self::SHARING,
1428 'priority' => $data['priority'] ?? 0,
1429 'batch' => $data['batch'] ?? '',
1430 'request' => $data['request'] ?? '',
1431 'confirm' => $data['confirm'] ?? '',
1432 'poco' => $data['poco'] ?? '',
1433 'baseurl' => $data['baseurl'] ?? '',
1434 'gsid' => $data['gsid'] ?? null,
1435 'name-date' => DateTimeFormat::utcNow(),
1436 'uri-date' => DateTimeFormat::utcNow(),
1437 'avatar-date' => DateTimeFormat::utcNow(),
1443 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1445 // Before inserting we do check if the entry does exist now.
1446 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1447 if (!DBA::isResult($contact)) {
1448 Logger::info('Create new contact', $fields);
1450 self::insert($fields);
1452 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1453 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1454 if (!DBA::isResult($contact)) {
1455 Logger::info('Contact creation failed', $fields);
1460 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1463 $contact_id = $contact["id"];
1466 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1467 self::updateAvatar($contact_id, $data['photo']);
1470 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1471 if ($background_update) {
1472 // Update in the background when we fetched the data solely from the database
1473 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1475 // Else do a direct update
1476 self::updateFromProbe($contact_id, '', false);
1478 // Update the gcontact entry
1480 GContact::updateFromPublicContactID($contact_id);
1481 if (($data['network'] == Protocol::ACTIVITYPUB) && in_array(DI::config()->get('system', 'gcontact_discovery'), [GContact::DISCOVERY_DIRECT, GContact::DISCOVERY_RECURSIVE])) {
1482 GContact::discoverFollowers($data['url']);
1487 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1488 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1490 // This condition should always be true
1491 if (!DBA::isResult($contact)) {
1496 'url' => $data['url'],
1497 'nurl' => Strings::normaliseLink($data['url']),
1498 'updated' => DateTimeFormat::utcNow(),
1502 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1504 foreach ($fields as $field) {
1505 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1508 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1509 $updated['uri-date'] = DateTimeFormat::utcNow();
1512 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1513 $updated['name-date'] = DateTimeFormat::utcNow();
1516 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1523 * Checks if the contact is archived
1525 * @param int $cid contact id
1527 * @return boolean Is the contact archived?
1528 * @throws HTTPException\InternalServerErrorException
1530 public static function isArchived(int $cid)
1536 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1537 if (!DBA::isResult($contact)) {
1541 if ($contact['archive']) {
1545 // Check status of ActivityPub endpoints
1546 $apcontact = APContact::getByURL($contact['url'], false);
1547 if (!empty($apcontact)) {
1548 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1552 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1557 // Check status of Diaspora endpoints
1558 if (!empty($contact['batch'])) {
1559 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1560 return DBA::exists('contact', $condition);
1567 * Checks if the contact is blocked
1569 * @param int $cid contact id
1571 * @return boolean Is the contact blocked?
1572 * @throws HTTPException\InternalServerErrorException
1574 public static function isBlocked($cid)
1580 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1581 if (!DBA::isResult($blocked)) {
1585 if (Network::isUrlBlocked($blocked['url'])) {
1589 return (bool) $blocked['blocked'];
1593 * Checks if the contact is hidden
1595 * @param int $cid contact id
1597 * @return boolean Is the contact hidden?
1598 * @throws \Exception
1600 public static function isHidden($cid)
1606 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1607 if (!DBA::isResult($hidden)) {
1610 return (bool) $hidden['hidden'];
1614 * Returns posts from a given contact url
1616 * @param string $contact_url Contact URL
1617 * @param bool $thread_mode
1618 * @param int $update
1619 * @return string posts in HTML
1620 * @throws \Exception
1622 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1624 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1628 * Returns posts from a given contact id
1630 * @param integer $cid
1631 * @param bool $thread_mode
1632 * @param integer $update
1633 * @return string posts in HTML
1634 * @throws \Exception
1636 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1640 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1641 if (!DBA::isResult($contact)) {
1645 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1646 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1648 $sql = "`item`.`uid` = ?";
1651 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1654 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1655 $cid, GRAVITY_PARENT, local_user()];
1657 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1658 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1661 if (DI::mode()->isMobile()) {
1662 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1663 DI::config()->get('system', 'itemspage_network_mobile'));
1665 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1666 DI::config()->get('system', 'itemspage_network'));
1669 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1671 $params = ['order' => ['received' => true],
1672 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1675 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1677 $items = Item::inArray($r);
1679 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1681 $r = Item::selectForUser(local_user(), [], $condition, $params);
1683 $items = Item::inArray($r);
1685 $o = conversation($a, $items, 'contact-posts', false);
1689 $o .= $pager->renderMinimal(count($items));
1696 * Returns the account type name
1698 * The function can be called with either the user or the contact array
1700 * @param array $contact contact or user array
1703 public static function getAccountType(array $contact)
1705 // There are several fields that indicate that the contact or user is a forum
1706 // "page-flags" is a field in the user table,
1707 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1708 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1709 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1710 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1711 || (isset($contact['forum']) && intval($contact['forum']))
1712 || (isset($contact['prv']) && intval($contact['prv']))
1713 || (isset($contact['community']) && intval($contact['community']))
1715 $type = self::TYPE_COMMUNITY;
1717 $type = self::TYPE_PERSON;
1720 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1721 if (isset($contact["contact-type"])) {
1722 $type = $contact["contact-type"];
1725 if (isset($contact["account-type"])) {
1726 $type = $contact["account-type"];
1730 case self::TYPE_ORGANISATION:
1731 $account_type = DI::l10n()->t("Organisation");
1734 case self::TYPE_NEWS:
1735 $account_type = DI::l10n()->t('News');
1738 case self::TYPE_COMMUNITY:
1739 $account_type = DI::l10n()->t("Forum");
1747 return $account_type;
1755 * @throws \Exception
1757 public static function block($cid, $reason = null)
1759 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1765 * Unblocks a contact
1769 * @throws \Exception
1771 public static function unblock($cid)
1773 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1779 * Ensure that cached avatar exist
1781 * @param integer $cid
1783 public static function checkAvatarCache(int $cid)
1785 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1786 if (!DBA::isResult($contact)) {
1790 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1794 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1796 self::updateAvatar($cid, $contact['avatar'], true);
1800 * Updates the avatar links in a contact only if needed
1802 * @param int $cid Contact id
1803 * @param string $avatar Link to avatar picture
1804 * @param bool $force force picture update
1807 * @throws HTTPException\InternalServerErrorException
1808 * @throws HTTPException\NotFoundException
1809 * @throws \ImagickException
1811 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1813 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1814 if (!DBA::isResult($contact)) {
1818 $uid = $contact['uid'];
1820 // Only update the cached photo links of public contacts when they already are cached
1821 if (($uid == 0) && !$force && empty($contact['photo']) && empty($contact['thumb']) && empty($contact['micro'])) {
1822 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1823 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1828 $contact['photo'] ?? '',
1829 $contact['thumb'] ?? '',
1830 $contact['micro'] ?? '',
1833 foreach ($data as $image_uri) {
1834 $image_rid = Photo::ridFromURI($image_uri);
1835 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1836 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1841 if (($contact["avatar"] != $avatar) || $force) {
1842 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1845 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1846 DBA::update('contact', $fields, ['id' => $cid]);
1848 // Update the public contact (contact id = 0)
1850 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1851 if (DBA::isResult($pcontact)) {
1852 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1860 * Helper function for "updateFromProbe". Updates personal and public contact
1862 * @param integer $id contact id
1863 * @param integer $uid user id
1864 * @param string $url The profile URL of the contact
1865 * @param array $fields The fields that are updated
1867 * @throws \Exception
1869 private static function updateContact($id, $uid, $url, array $fields)
1871 if (!DBA::update('contact', $fields, ['id' => $id])) {
1872 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1876 // Search for duplicated contacts and get rid of them
1877 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1881 // Update the corresponding gcontact entry
1882 GContact::updateFromPublicContactID($id);
1884 // Archive or unarchive the contact. We only need to do this for the public contact.
1885 // The archive/unarchive function will update the personal contacts by themselves.
1886 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1887 if (!DBA::isResult($contact)) {
1888 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1892 if (!empty($fields['success_update'])) {
1893 self::unmarkForArchival($contact);
1894 } elseif (!empty($fields['failure_update'])) {
1895 self::markForArchival($contact);
1898 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1900 // These contacts are sharing with us, we don't poll them.
1901 // This means that we don't set the update fields in "OnePoll.php".
1902 $condition['rel'] = self::SHARING;
1903 DBA::update('contact', $fields, $condition);
1905 unset($fields['last-update']);
1906 unset($fields['success_update']);
1907 unset($fields['failure_update']);
1909 if (empty($fields)) {
1913 // We are polling these contacts, so we mustn't set the update fields here.
1914 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1915 DBA::update('contact', $fields, $condition);
1919 * Remove duplicated contacts
1921 * @param string $nurl Normalised contact url
1922 * @param integer $uid User id
1924 * @throws \Exception
1926 public static function removeDuplicates(string $nurl, int $uid)
1928 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1929 $count = DBA::count('contact', $condition);
1934 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1935 if (!DBA::isResult($first_contact)) {
1936 // Shouldn't happen - so we handle it
1940 $first = $first_contact['id'];
1941 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1942 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1943 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1944 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1948 // Find all duplicates
1949 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1950 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1951 while ($duplicate = DBA::fetch($duplicates)) {
1952 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1956 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1958 DBA::close($duplicates);
1959 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1964 * @param integer $id contact id
1965 * @param string $network Optional network we are probing for
1966 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1968 * @throws HTTPException\InternalServerErrorException
1969 * @throws \ImagickException
1971 public static function updateFromProbe($id, $network = '', $force = false)
1974 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1975 This will reliably kill your communication with old Friendica contacts.
1978 // These fields aren't updated by this routine:
1979 // 'xmpp', 'sensitive'
1981 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1982 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1983 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
1984 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1985 if (!DBA::isResult($contact)) {
1989 $uid = $contact['uid'];
1990 unset($contact['uid']);
1992 $pubkey = $contact['pubkey'];
1993 unset($contact['pubkey']);
1995 $contact['photo'] = $contact['avatar'];
1996 unset($contact['avatar']);
1998 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2000 $updated = DateTimeFormat::utcNow();
2002 // We must not try to update relay contacts via probe. They are no real contacts.
2003 // We check after the probing to be able to correct falsely detected contact types.
2004 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2005 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2006 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2007 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2011 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2012 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2013 if ($force && ($uid == 0)) {
2014 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2019 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2020 $ret['unsearchable'] = $ret['hide'];
2023 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2024 $ret['forum'] = false;
2025 $ret['prv'] = false;
2026 $ret['contact-type'] = $ret['account-type'];
2027 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2028 $apcontact = APContact::getByURL($ret['url'], false);
2029 if (isset($apcontact['manually-approve'])) {
2030 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2031 $ret['prv'] = (bool)!$ret['forum'];
2036 $new_pubkey = $ret['pubkey'];
2040 // make sure to not overwrite existing values with blank entries except some technical fields
2041 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2042 foreach ($ret as $key => $val) {
2043 if (!array_key_exists($key, $contact)) {
2045 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2046 $ret[$key] = $contact[$key];
2047 } elseif ($ret[$key] != $contact[$key]) {
2052 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2053 self::updateAvatar($id, $ret['photo'], $update || $force);
2058 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2061 // Update the public contact
2063 self::updateFromProbeByURL($ret['url']);
2069 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2070 $ret['updated'] = $updated;
2072 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2073 if (empty($pubkey) && !empty($new_pubkey)) {
2074 $ret['pubkey'] = $new_pubkey;
2077 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2078 $ret['uri-date'] = DateTimeFormat::utcNow();
2081 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2082 $ret['name-date'] = $updated;
2085 if ($force && ($uid == 0)) {
2086 $ret['last-update'] = $updated;
2087 $ret['success_update'] = $updated;
2088 $ret['failed'] = false;
2091 unset($ret['photo']);
2093 self::updateContact($id, $uid, $ret['url'], $ret);
2098 public static function updateFromProbeByURL($url, $force = false)
2100 $id = self::getIdForURL($url);
2106 self::updateFromProbe($id, '', $force);
2112 * Detects if a given contact array belongs to a legacy DFRN connection
2114 * @param array $contact
2117 public static function isLegacyDFRNContact($contact)
2119 // Newer Friendica contacts are connected via AP, then these fields aren't set
2120 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2124 * Detects the communication protocol for a given contact url.
2125 * This is used to detect Friendica contacts that we can communicate via AP.
2127 * @param string $url contact url
2128 * @param string $network Network of that contact
2129 * @return string with protocol
2131 public static function getProtocol($url, $network)
2133 if ($network != Protocol::DFRN) {
2137 $apcontact = APContact::getByURL($url);
2138 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2139 return Protocol::ACTIVITYPUB;
2146 * Takes a $uid and a url/handle and adds a new contact
2148 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2149 * dfrn_request page.
2151 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2154 * $return['success'] boolean true if successful
2155 * $return['message'] error text if success is false.
2157 * Takes a $uid and a url/handle and adds a new contact
2159 * @param array $user The user the contact should be created for
2160 * @param string $url The profile URL of the contact
2161 * @param bool $interactive
2162 * @param string $network
2164 * @throws HTTPException\InternalServerErrorException
2165 * @throws HTTPException\NotFoundException
2166 * @throws \ImagickException
2168 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2170 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2172 // remove ajax junk, e.g. Twitter
2173 $url = str_replace('/#!/', '/', $url);
2175 if (!Network::isUrlAllowed($url)) {
2176 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2180 if (Network::isUrlBlocked($url)) {
2181 $result['message'] = DI::l10n()->t('Blocked domain');
2186 $result['message'] = DI::l10n()->t('Connect URL missing.');
2190 $arr = ['url' => $url, 'contact' => []];
2192 Hook::callAll('follow', $arr);
2195 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2199 if (!empty($arr['contact']['name'])) {
2200 $ret = $arr['contact'];
2202 $ret = Probe::uri($url, $network, $user['uid'], false);
2205 if (($network != '') && ($ret['network'] != $network)) {
2206 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2210 // check if we already have a contact
2211 // the poll url is more reliable than the profile url, as we may have
2212 // indirect links or webfinger links
2214 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2215 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2216 if (!DBA::isResult($contact)) {
2217 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2218 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2221 $protocol = self::getProtocol($ret['url'], $ret['network']);
2223 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2225 if (strlen(DI::baseUrl()->getUrlPath())) {
2226 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2228 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2231 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2235 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2236 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2237 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2241 // This extra param just confuses things, remove it
2242 if ($protocol === Protocol::DIASPORA) {
2243 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2246 // do we have enough information?
2247 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2248 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2249 if (empty($ret['poll'])) {
2250 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2252 if (empty($ret['name'])) {
2253 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2255 if (empty($ret['url'])) {
2256 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2258 if (strpos($ret['url'], '@') !== false) {
2259 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2260 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2265 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2266 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2267 $ret['notify'] = '';
2270 if (!$ret['notify']) {
2271 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2274 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2276 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2278 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2281 if ($protocol == Protocol::ACTIVITYPUB) {
2282 $apcontact = APContact::getByURL($ret['url'], false);
2283 if (isset($apcontact['manually-approve'])) {
2284 $pending = (bool)$apcontact['manually-approve'];
2288 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2292 if (DBA::isResult($contact)) {
2294 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2296 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2297 DBA::update('contact', $fields, ['id' => $contact['id']]);
2299 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2301 // create contact record
2303 'uid' => $user['uid'],
2304 'created' => DateTimeFormat::utcNow(),
2305 'url' => $ret['url'],
2306 'nurl' => Strings::normaliseLink($ret['url']),
2307 'addr' => $ret['addr'],
2308 'alias' => $ret['alias'],
2309 'batch' => $ret['batch'],
2310 'notify' => $ret['notify'],
2311 'poll' => $ret['poll'],
2312 'poco' => $ret['poco'],
2313 'name' => $ret['name'],
2314 'nick' => $ret['nick'],
2315 'network' => $ret['network'],
2316 'baseurl' => $ret['baseurl'],
2317 'gsid' => $ret['gsid'] ?? null,
2318 'protocol' => $protocol,
2319 'pubkey' => $ret['pubkey'],
2320 'rel' => $new_relation,
2321 'priority'=> $ret['priority'],
2322 'writable'=> $writeable,
2323 'hidden' => $hidden,
2326 'pending' => $pending,
2331 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2332 if (!DBA::isResult($contact)) {
2333 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2337 $contact_id = $contact['id'];
2338 $result['cid'] = $contact_id;
2340 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2342 // Update the avatar
2343 self::updateAvatar($contact_id, $ret['photo']);
2345 // pull feed and consume it, which should subscribe to the hub.
2347 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2349 $owner = User::getOwnerDataById($user['uid']);
2351 if (DBA::isResult($owner)) {
2352 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2353 // create a follow slap
2355 $item['verb'] = Activity::FOLLOW;
2356 $item['gravity'] = GRAVITY_ACTIVITY;
2357 $item['follow'] = $contact["url"];
2359 $item['title'] = '';
2361 $item['uri-id'] = 0;
2362 $item['attach'] = '';
2364 $slap = OStatus::salmon($item, $owner);
2366 if (!empty($contact['notify'])) {
2367 Salmon::slapper($owner, $contact['notify'], $slap);
2369 } elseif ($protocol == Protocol::DIASPORA) {
2370 $ret = Diaspora::sendShare($owner, $contact);
2371 Logger::log('share returns: ' . $ret);
2372 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2373 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2374 if (empty($activity_id)) {
2375 // This really should never happen
2379 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2380 Logger::log('Follow returns: ' . $ret);
2384 $result['success'] = true;
2389 * Updated contact's SSL policy
2391 * @param array $contact Contact array
2392 * @param string $new_policy New policy, valid: self,full
2394 * @return array Contact array with updated values
2395 * @throws \Exception
2397 public static function updateSslPolicy(array $contact, $new_policy)
2399 $ssl_changed = false;
2400 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2401 $ssl_changed = true;
2402 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2403 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2404 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2405 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2406 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2407 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2410 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2411 $ssl_changed = true;
2412 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2413 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2414 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2415 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2416 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2417 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2421 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2422 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2423 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2424 DBA::update('contact', $fields, ['id' => $contact['id']]);
2431 * @param array $importer Owner (local user) data
2432 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2433 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2434 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2435 * @param string $note Introduction additional message
2436 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2437 * @throws HTTPException\InternalServerErrorException
2438 * @throws \ImagickException
2440 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2442 // Should always be set
2443 if (empty($datarray['author-id'])) {
2447 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2448 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2449 if (!DBA::isResult($pub_contact)) {
2450 // Should never happen
2454 // Contact is blocked at node-level
2455 if (self::isBlocked($datarray['author-id'])) {
2459 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2460 $name = $pub_contact['name'];
2461 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2462 $nick = $pub_contact['nick'];
2463 $network = $pub_contact['network'];
2465 // Ensure that we don't create a new contact when there already is one
2466 $cid = self::getIdForURL($url, $importer['uid']);
2468 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2471 if (!empty($contact)) {
2472 if (!empty($contact['pending'])) {
2473 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2477 // Contact is blocked at user-level
2478 if (!empty($contact['id']) && !empty($importer['id']) &&
2479 self::isBlockedByUser($contact['id'], $importer['id'])) {
2483 // Make sure that the existing contact isn't archived
2484 self::unmarkForArchival($contact);
2486 if (($contact['rel'] == self::SHARING)
2487 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2488 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2489 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2492 // Ensure to always have the correct network type, independent from the connection request method
2493 self::updateFromProbe($contact['id'], '', true);
2497 // send email notification to owner?
2498 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2499 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2503 // create contact record
2504 DBA::insert('contact', [
2505 'uid' => $importer['uid'],
2506 'created' => DateTimeFormat::utcNow(),
2508 'nurl' => Strings::normaliseLink($url),
2512 'network' => $network,
2513 'rel' => self::FOLLOWER,
2520 $contact_id = DBA::lastInsertId();
2522 // Ensure to always have the correct network type, independent from the connection request method
2523 self::updateFromProbe($contact_id, '', true);
2525 self::updateAvatar($contact_id, $photo, true);
2527 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2529 /// @TODO Encapsulate this into a function/method
2530 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2531 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2532 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2533 // create notification
2534 $hash = Strings::getRandomHex();
2536 if (is_array($contact_record)) {
2537 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2538 'blocked' => false, 'knowyou' => false, 'note' => $note,
2539 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2542 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2544 if (($user['notify-flags'] & Type::INTRO) &&
2545 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2548 'type' => Type::INTRO,
2549 'notify_flags' => $user['notify-flags'],
2550 'language' => $user['language'],
2551 'to_name' => $user['username'],
2552 'to_email' => $user['email'],
2553 'uid' => $user['uid'],
2554 'link' => DI::baseUrl() . '/notifications/intros',
2555 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2556 'source_link' => $contact_record['url'],
2557 'source_photo' => $contact_record['photo'],
2558 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2562 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2563 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2564 self::createFromProbe($importer, $url, false, $network);
2567 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2568 $fields = ['pending' => false];
2569 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2570 $fields['rel'] = Contact::FRIEND;
2573 DBA::update('contact', $fields, $condition);
2582 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2584 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2585 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2587 Contact::remove($contact['id']);
2591 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2593 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2594 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2596 Contact::remove($contact['id']);
2601 * Create a birthday event.
2603 * Update the year and the birthday.
2605 public static function updateBirthdays()
2609 AND `bd` > "0001-01-01"
2610 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2611 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2612 AND NOT `contact`.`pending`
2613 AND NOT `contact`.`hidden`
2614 AND NOT `contact`.`blocked`
2615 AND NOT `contact`.`archive`
2616 AND NOT `contact`.`deleted`',
2621 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2623 while ($contact = DBA::fetch($contacts)) {
2624 Logger::log('update_contact_birthday: ' . $contact['bd']);
2626 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2628 if (Event::createBirthday($contact, $nextbd)) {
2632 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2633 ['id' => $contact['id']]
2637 DBA::close($contacts);
2641 * Remove the unavailable contact ids from the provided list
2643 * @param array $contact_ids Contact id list
2645 * @throws \Exception
2647 public static function pruneUnavailable(array $contact_ids)
2649 if (empty($contact_ids)) {
2653 $contacts = Contact::selectToArray(['id'], [
2654 'id' => $contact_ids,
2660 return array_column($contacts, 'id');
2664 * Returns a magic link to authenticate remote visitors
2666 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2668 * @param string $contact_url The address of the target contact profile
2669 * @param string $url An url that we will be redirected to after the authentication
2671 * @return string with "redir" link
2672 * @throws HTTPException\InternalServerErrorException
2673 * @throws \ImagickException
2675 public static function magicLink($contact_url, $url = '')
2677 if (!Session::isAuthenticated()) {
2678 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2681 $data = self::getProbeDataFromDatabase($contact_url);
2683 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2686 // Prevents endless loop in case only a non-public contact exists for the contact URL
2687 unset($data['uid']);
2689 return self::magicLinkByContact($data, $url ?: $contact_url);
2693 * Returns a magic link to authenticate remote visitors
2695 * @param integer $cid The contact id of the target contact profile
2696 * @param string $url An url that we will be redirected to after the authentication
2698 * @return string with "redir" link
2699 * @throws HTTPException\InternalServerErrorException
2700 * @throws \ImagickException
2702 public static function magicLinkbyId($cid, $url = '')
2704 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2706 return self::magicLinkByContact($contact, $url);
2710 * Returns a magic link to authenticate remote visitors
2712 * @param array $contact The contact array with "uid", "network" and "url"
2713 * @param string $url An url that we will be redirected to after the authentication
2715 * @return string with "redir" link
2716 * @throws HTTPException\InternalServerErrorException
2717 * @throws \ImagickException
2719 public static function magicLinkByContact($contact, $url = '')
2721 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2723 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2724 return $destination;
2727 // Only redirections to the same host do make sense
2728 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2732 if (!empty($contact['uid'])) {
2733 return self::magicLink($contact['url'], $url);
2736 if (empty($contact['id'])) {
2737 return $destination;
2740 $redirect = 'redir/' . $contact['id'];
2742 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2743 $redirect .= '?url=' . $url;
2750 * Remove a contact from all groups
2752 * @param integer $contact_id
2754 * @return boolean Success
2756 public static function removeFromGroups($contact_id)
2758 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2762 * Is the contact a forum?
2764 * @param integer $contactid ID of the contact
2766 * @return boolean "true" if it is a forum
2768 public static function isForum($contactid)
2770 $fields = ['forum', 'prv'];
2771 $condition = ['id' => $contactid];
2772 $contact = DBA::selectFirst('contact', $fields, $condition);
2773 if (!DBA::isResult($contact)) {
2778 return ($contact['forum'] || $contact['prv']);
2782 * Can the remote contact receive private messages?
2784 * @param array $contact
2787 public static function canReceivePrivateMessages(array $contact)
2789 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2790 $self = $contact['self'] ?? false;
2792 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;